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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With