Higher Order functions
Functions, functions, functions
A function parameterized by another function or returning a function is called a higher-order function.
Currying
Strictly speaking, every curried function in Haskell is a function returning another function:
elem :: Eq a => a -> ([a] -> Bool)
elem 3 :: (Eq a, Num a) => [a] -> Bool
Filtering and mapping
Two of the most useful list functions are higher-order, as they each take a function as an argument:
filter :: (a -> Bool) -> ([a] -> [a])
map :: (a -> b) -> ([a] -> [b])
The use of a function a -> Bool
to express a predicate is generally common. And mapping a function over a data structure is an operation that isn’t limited to lists.
Folds
The functions foldr
and foldl'
are among the most general
higher-order functions on lists. Nearly any other list function can be
expressed in terms of them.
Some rules of thumb:
- If a more specific function applies (such as
filter
ormap
), use that. - If a function becomes more readable by using a fold, then use it. It has the advantage that it also signals to the programmer that a common pattern is being used and nothing special is going on.
- If a function becomes harder to read by using a fold, then do not force it into that pattern (except perhaps for training purposes).