【发布时间】:2017-11-08 02:08:51
【问题描述】:
我有一个列表,例如:[(1,2),(3,4),(5,6)],该函数应该返回相应元组的总和。所以,这个列表应该返回 (9,12)。我知道如何使元组单独加起来,但我很难把它们放在一起。
sumSecondTuple list = foldl (\acc (x,y) -> (+) y acc) 0 list
sumFirstTuple list = foldl (\acc (x,y) -> (+) x acc) 0 list
到目前为止,我有这么多。有没有办法让他们一起合作?
【问题讨论】:
-
sumTuples list = foldl (\(xAcc, yAcc) (x,y) -> (xAcc + x, yAcc + y)) (0,0) list -
@Alec 这行得通。非常感谢。
-
或者
sumTuples xs = (sumOver fst, sumOver snd) where sumOver x = sum $ map x xs