0

我正在尝试使用更高的函数来逐个添加元组列表。结果应该是(第一个组件的总和,第二个组件的总和)。

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 函数是错误的。但我不明白。

谢谢你的帮助!

4

1 回答 1

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)
于 2013-06-09T12:50:25.770 回答