Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum over same indices of list of lists?

Tags:

haskell

How can I sum a list of lists where all the values at the a index?

For example:

let k = [ [1,1,1], [2,2,2], [3,3,3] ]
sumFoo k
> [ 6, 6, 6]

I know that I can sum two lists as:

zipWith (+) [1,2,3] [2,3,4]

But what about a list of list? I tried something like:

foldr (\xs ys -> zipWith (+) xs ys) [] k

but that gives me an empty list!

like image 497
Andriy Drozdyuk Avatar asked Mar 02 '12 18:03

Andriy Drozdyuk


1 Answers

To answer the OPs question:

foldl1 (zipWith (+)) k

should do the trick. Foldl1 starts with the first element of the list as the accumulator value, which is what you want.

You can also use zipWith3, zipWith4, .... all the way up to 7, if you prefer.

-----------To find the overall sum ------

You first want to map sum over each element of the list (i.e. each nested list), and then run sum over the result.

So:

sum . map sum $ k

And that's it!

Notes if you're unfamiliar with . or $ syntax - $ is function application, but is right associative (saving you parentheses), and . is function composition.

like image 189
danieltahara Avatar answered Sep 28 '22 03:09

danieltahara