Using Haskell's map function to calculate the sum of a list

Sudantha  picture Sudantha · May 30, 2011 · Viewed 32.3k times · Source

Haskell

addm::[Int]->Int
addm (x:xs) = sum(x:xs)

I was able to achieve to get a sum of a list using sum function but is it possible to get the sum of a list using map function? Also what the use of map function?

Answer

Waldheinz picture Waldheinz · May 30, 2011

You can't really use map to sum up a list, because map treats each list element independently from the others. You can use map for example to increment each value in a list like in

map (+1) [1,2,3,4] -- gives [2,3,4,5]

Another way to implement your addm would be to use foldl:

addm' = foldl (+) 0