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.

  1. map' :: forall a b. (a -> b) -> [a] -> [b]
  2. map' f [] = []
  3. map' f [x|xs] = [f x | map' f xs]
  4. > map' (\x -> x +1 ) [1..10]
  5. [2,3,4,5,6,7,8,9,10,11]
  6. filter' :: forall a. (a -> Boolean) -> [a] -> [a]
  7. filter' p [] = []
  8. filter' p [x|xs] = if p x
  9. then [x | filter p xs]
  10. else filter p xs
  11. > filter' (\x -> x > 5) [1..10]
  12. [6,7,8,9,10]
  13. foldl' :: forall a b. (b -> a -> b) -> b -> [a] -> b
  14. foldl' f k [] = k
  15. foldl' f k [x|xs] = foldl' f (f k x) xs
  16. > foldl' (+) 0 [1..10]
  17. 55