【问题标题】:Adding corresponding values of Tuple in a list in Haskell在 Haskell 的列表中添加对应的 Tuple 值
【发布时间】: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

标签: list haskell tuples


【解决方案1】:

你也可以使用foldr1:

foldr1 :: Foldable t => (a -> a -> a) -> t a -> a

在这种情况下,

sumSecondTuple :: Num a => [(a,a)] -> (a,a)
sumSecondTuple = foldr1 f
    where
        f = (\ (a,b) (c,d) -> (a+c,b+d) )

但是,sumSecondTuple [] 返回异常 Prelude.foldr1: empty list。因此,在这种情况下使用foldr 比使用foldr1 更好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    • 2022-10-13
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    相关资源
    最近更新 更多