Using Haskell's map function to calculate the sum of a list
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
Here it is, the supposedly impossible definition of sum
in terms of map
:
sum' xs = let { ys = 0 : map (\(a,b) -> a + b) (zip xs ys) } in last ys
this actually shows how scanl
can be implemented in terms of map
(and zip
and last
), the above being equivalent to foldl (+) 0 xs === last $ scanl (+) 0 xs
:
scanl' f z xs = let { ys = z : map (uncurry f) (zip ys xs) } in ys
I expect one can calculate many things with map
, arranging for all kinds of information flow through zip
.
edit: the above is just a zipWith
in disguise of course (and zipWith
is kind of a map2
):
sum' xs = let { ys = 0 : zipWith (+) ys xs } in last ys
This seems to suggest that scanl
is more versatile than foldl
.
It is not possible to use map
to reduce a list to its sum. That recursive pattern is a fold
.
sum :: [Int] -> Int
sum = foldr (+) 0
As an aside, note that you can define map
as a fold as well:
map :: (a -> b) -> ([a] -> [b])
map f = fold (\x xs -> f x : xs) []
This is because foldr
is the canonical recursive function on lists.
References: A tutorial on the universality and expressiveness of fold, Graham Hutton, J. Functional Programming 9 (4): 355–372, July 1999.