1 haskell functional-programming tuples list fold
我一直在挠头试图弄清楚这一点。如何使用foldr1(或任何其他折叠)来获取列表中元组的总和。
\n例子:
\nlist = [(1,2), (3,4)]\nsum = 10\nRun Code Online (Sandbox Code Playgroud)\n我已经尝试过,foldr1 (\\x y -> fst(x) + snd(x) + y) [(1,2),(3,4)]但它不起作用,我怀疑它与执行折叠时创建的类型而不是元组有关。
当我运行上述命令时,我得到以下信息:
\nfoldr1 (\\x y -> fst(x) + snd(x) + y) [(1,2),(3,4)]\n\n\xe2\x80\xa2 Occurs check: cannot construct the infinite type: a ~ (a, a)\n \xe2\x80\xa2 In the second argument of \xe2\x80\x98(+)\xe2\x80\x99, namely \xe2\x80\x98y\xe2\x80\x99\n In the expression: fst (x) + snd (x) + y\n In the first argument of \xe2\x80\x98foldr1\xe2\x80\x99, namely\n \xe2\x80\x98(\\ x y -> fst (x) + snd (x) + y)\xe2\x80\x99\n \xe2\x80\xa2 Relevant bindings include\n y :: (a, a) (bound at <interactive>:30:12)\n x :: (a, a) (bound at <interactive>:30:10)\n it :: (a, a) (bound at <interactive>:30:1)\nRun Code Online (Sandbox Code Playgroud)\n我究竟做错了什么?折叠函数不适合这个吗(我已经使用 sum 和 map 一起解决了这个问题,并且得到了正确的答案)?
\n您不能使用foldr1,因为第一项是 2 元组,所以那么也y将是 2 元组。
您可以使用foldr:
foldr (\x y -> fst(x) + snd(x) + y) 0 [(1,2),(3,4)]
Run Code Online (Sandbox Code Playgroud)
或者更简单:
foldr (\(x1, x2) y -> x1 + x2 + y) 0 [(1,2),(3,4)]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |