Reputation: 105
I have a list for example: [(1,2),(3,4),(5,6)] and the function should return me the sum of the corresponding Tuples. So, this list should return (9,12). I know how to make the tuples add up individually but I have having troubles doing it them together.
sumSecondTuple list = foldl (\acc (x,y) -> (+) y acc) 0 list
sumFirstTuple list = foldl (\acc (x,y) -> (+) x acc) 0 list
I have this much so far. Is there a way I can incooperate them together?
Upvotes: 2
Views: 275
Reputation: 130
You can also use foldr1
:
foldr1 :: Foldable t => (a -> a -> a) -> t a -> a
In this case,
sumSecondTuple :: Num a => [(a,a)] -> (a,a)
sumSecondTuple = foldr1 f
where
f = (\ (a,b) (c,d) -> (a+c,b+d) )
However, sumSecondTuple []
returns an exception Prelude.foldr1: empty list
. So, it's better to use foldr
than use foldr1
on this occasion.
Upvotes: 1