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?
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.
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.
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
.
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