Function composition
Function composition is a well-known operator from mathematics, written as ∘, that combines two functions into a new one.
Basic function composition
Consider the following anonymous function:
\l -> show (length l)
This function returns the length of a list rendered as a string. It is not in the right shape to apply eta reduction to because, in its current form, we cannot identify one function that is applied to l
.
The function composition operator captures this particular pattern in a general way:
Prelude
(.) :: (b -> c) -> (a -> b) -> (a -> c)
f . g = \x -> f (g x)
This higher-order operator takes two functions and returns a new function that applies the first to the output of the second. We can use this to replace our preceding example with the following:
show . length
This can be read as "show composed with length" or, better, "show after length".
Pipelines
The function composition...