Reputation: 37
How can I do the sum of elements in a list at the same position? For example:
[[2,3,4],[5,6,7],[8,9,10]]=[15,18,21]
Thanks
Upvotes: 2
Views: 318
Reputation: 125147
You could transpose the list, and sum each list in the result:
ghci> import Data.List (transpose)
ghci> map sum $ transpose [[2,3,4],[5,6,7],[8,9,10]]
[15,18,21]
Unlike the other solutions, this works for lists of non-uniform length.
Upvotes: 2
Reputation: 8136
Here's an example in GHCi:
λ> let xs = [[2,3,4],[5,6,7],[8,9,10]]
λ> foldr1 (zipWith (+)) xs
[15,18,21]
Upvotes: 2
Reputation: 63359
Try:
sumIn :: Num a => [[a]] -> [a]
sumIn = foldl (zipWith (+)) (repeat 0)
Note that if the argument is an empty list, the result is an infinite list of zeros. So you may want to treat this case separately, for example
sumIn :: Num a => [[a]] -> [a]
sumIn [] = []
sumIn xs = foldl (zipWith (+)) (repeat 0) xs
Upvotes: 2