Map, filter and fold

Map, filter and fold

map, filter and foldr are three commonly used functions to manipulate a list. map applys f on all as in a list of a. filter just filters the list according to p. foldr destructs the list by replacing every : with a operator/or function.

Here are the definitions.

map' :: forall a b. (a -> b) -> [a] -> [b]
map' f  []      = []
map' f [x|xs] = [f x | map' f xs]

> map' (\x -> x +1 ) [1..10]
[2,3,4,5,6,7,8,9,10,11]

filter' :: forall a. (a -> Boolean) -> [a] -> [a]
filter' p []     = []
filter' p [x|xs] = if p x
                   then [x | filter p xs]
                   else filter p xs

> filter' (\x -> x > 5) [1..10]
[6,7,8,9,10]

foldl' :: forall a b. (b -> a -> b) -> b -> [a] -> b
foldl' f k []     = k
foldl' f k [x|xs] = foldl' f (f k x) xs

> foldl' (+) 0 [1..10]
55