【发布时间】:2018-12-12 18:54:19
【问题描述】:
我是 Haskell 的新手。我很擅长命令式语言,但不擅长功能性语言。 Haskell 是我的第一个函数式语言。
我想弄清楚,如何获取列表中最小元素由我定义的最小元素的索引。
让我通过例子来解释。
例如:
函数签名 minList :: x -> [x]
let x = 2
let list = [2,3,5,4,6,5,2,1,7,9,2]
minList x list --output 1 <- is index
这应该返回 1。因为 at list[1] 是 3。它返回 1 因为 3 是 x (=2) 之后的最小元素。
let x = 1
let list = [3,5,4,6,5,2,1,7,9,2]
minList x list -- output 9 <- is index
它应该返回 9,因为在 list[9] 处是 2,而 2 是 1 之后的最小元素。x = 1 这是我定义的。
到目前为止我已经尝试过什么。
minListIndex :: (Ord a, Num a) => a -> [a] -> a
minListIndex x [] = 0
minListIndex x (y:ys)
| x > y = length ys
| otherwise = m
where m = minListIndex x ys
当我加载文件时出现此错误
• Couldn't match expected type ‘a’ with actual type ‘Int’
‘a’ is a rigid type variable bound by
the type signature for:
minListIndex :: forall a. (Ord a, Num a) => a -> [a] -> a
at myFile.hs:36:17
• In the expression: 1 + length ys
In an equation for ‘minListIndex’:
minListIndex x (y : ys)
| x > y = 1 + length ys
| otherwise = 1 + m
where
m = minListIndex x ys
• Relevant bindings include
m :: a (bound at myFile.hs:41:19)
ys :: [a] (bound at myFile.hs:38:19)
y :: a (bound at myFile.hs:38:17)
x :: a (bound at myFile.hs:38:14)
minListIndex :: a -> [a] -> a (bound at myFile.hs:37:1)
当我像这样修改函数时
minListIndex :: (Ord a, Num a) => a -> [a] -> a
minListIndex x [] = 0
minListIndex x (y:ys)
| x > y = 2 -- <- modified...
| otherwise = 3 -- <- modifiedd
where m = minListIndex x ys
我再次加载文件,然后它编译并运行,但输出不需要。
有什么问题
| x > y = length ys
| otherwise = m
?
简而言之:基本上,我想找到最小元素的索引,但高于我在参数/函数签名中定义的 x。
提前感谢您的帮助!
【问题讨论】:
-
你能解释一下
x > y = length ys这行背后的原因吗?为什么如果列表的第一个元素小于x,它应该返回列表其余部分的长度? -
您自己“定义最小元素”也有点“奇怪”。如果是这种情况,那么这基本上“崩溃”为
findIndex。 -
@WillemVanOnsem 感谢您的回答。我只是在测试长度 ys 并且它失败了。关于 findIndex,我不想导入任何库。 :(
-
根据例子,看起来你基本上想找到给定元素之后的最小元素的index?
-
是的,正是……
标签: list haskell compiler-errors