Map, Filter and Fold in Haskell
This example shows 3 key features of functional programming:
map function using haskell.
The function takes a function from a to b
(a -> b) and a list of a
[a] then product a list of b
map :: (a -> b) -> [a] -> [b] map f xs = [ f x | x <- xs ] mapRec :: (a -> b) -> [a] -> [b] mapRec f  =  mapRec f (x:xs) = f x : mapRec f xs
The function takes a predicate function
(a -> Bool) that return boolean (true/false) and a list
[a] then produce a filtered list
filter :: (a -> Bool) -> [a] -> [a] filter p xs = [ x | x <- xs, p x ] filterRec :: (a -> Bool) -> [a] -> [a] filterRec p  =  filterRec p (x:xs) | p x = x : filterRec p xs | otherwise = filterRec p xs
The function takes a 2 parameters function
(a -> a -> a), an initial accumulator and a list then return an accumulate result.
foldr :: (a -> a -> a) -> a -> [a] -> a foldr f a  = a foldr f a (x:xs) = f x (foldr f a xs) foldl :: (a -> a -> a) -> a -> [a] -> a foldl f a  = a foldl f a (x:xs) = foldl f (f a x) xs