Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 535
Sudantha Avatar asked May 30 '11 10:05

Sudantha


People also ask

How does map function work in Haskell?

The map() function takes two parameters namely a list and the function to be applied on each element in the list and returns a new list as the output. The map() function is available in Data. Map module in Haskell programming language.

What does filter function do in Haskell?

As we know a filter is used to filter or extract the data or elements from the given data structure for use. This filter condition can be anything based on the predicate we apply. Once we apply the predicate it will return us the elements which satisfy the predicate condition.


2 Answers

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
like image 147
Waldheinz Avatar answered Oct 05 '22 05:10

Waldheinz


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.

like image 29
Will Ness Avatar answered Oct 05 '22 03:10

Will Ness