user1876106
user1876106

Reputation: 37

Sum of elements in a list at the same position

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

Answers (3)

Ben James
Ben James

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

mhwombat
mhwombat

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

Petr
Petr

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

Related Questions