为什么这不起作用?
Prelude> foldl1 (\a b -> ((snd a) + (snd b))) [(1,2),(3,4)]
<interactive>:1:17:
Occurs check: cannot construct the infinite type: b = (a, b)
Expected type: (a, b)
Inferred type: b
In the expression: ((snd a) + (snd b))
In the first argument of `foldl1', namely
`(\ a b -> ((snd a) + (snd b)))'
最佳答案
foldl1
的函数参数必须具有类型 a -> a -> a
,即 2 个输入参数和返回值必须具有相同的类型。在您的表达式中,该函数应返回一个 2 元组 Num b => (a, b)
, 不是纯数字 Num b => b
,因此“发生检查”。
您可以使用 foldl
并提供一个初始值,例如
foldl (\acc elm -> acc + snd elm) 0 [(1,2),(3,4)]
或使用现有功能
(sum . map snd) [(1,2),(3,4)]
关于"foldl1 (\a b -> (and a + and b)) [(1,2), (3,4)] 的 Haskell 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4379437/