为什么这不起作用?
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)))'
Run Code Online (Sandbox Code Playgroud)
ken*_*ytm 12
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)]
Run Code Online (Sandbox Code Playgroud)
或使用现有的功能
(sum . map snd) [(1,2),(3,4)]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
176 次 |
| 最近记录: |