我正在尝试使用更高级的功能逐个组件添加元组列表。结果应该是(第一个组件的总和,第二个组件的总和)。
sumPointwise :: Num a => [(a,a)] -> (a,a)
sumPointwise tl = (sumPw1, sumPw2) -- 42:1
where sumPw1 = foldr (\ x y -> (fst x) + (fst y)) 0 tl
sumPw2 = foldr (\ x y -> (snd x) + (snd y)) 0 tl
但我收到以下错误:
Couldn't match type `a' with `(a, b0)'
`a' is a rigid type variable bound by
the type signature for sumPointwise :: Num a => [(a, a)] -> (a, a)
at .hs:42:1
In the first argument of `fst', namely `y'
In the second argument of `(+)', namely `(fst y)'
In the expression: (fst x) + (fst y)
似乎lambda函数是错误的。但是我没理解。
感谢您的帮助!
答案 0 :(得分:3)
foldr
的第二个参数是汇总值:foldr :: (a -> b -> b) -> b -> [a] -> b
。所以,你的表达式看起来应该是
sumPw1 = foldr (\ x s -> (fst x) + s) 0 tl
更简洁的解决方法是
sumPointwise tl = let (xs, ys) = unzip tl in (sum xs, sum ys)