I am reading this tutorial on Haskell. They define function composition as the following:
(.) :: (b->c) -> (a->b) -> (a->c)
f . g = \ x -> f (g x)
No examples were provided, which I believe would enlighten me as to what is being defined here.
Can someone provide a simple example (with explanation) of how function composition is used?
Function composition is a way to “compose” two functions together into a single function. Here’s an example:
Say you have these functions:
and you want to define your own
myOdd :: Int -> Boolfunction using the two above.The obvious way to do this is the following:
But this can be done more succinctly using function composition:
The
myOddfunctions behave exactly the same, but the second one is created by “glue-ing” two functions together.A scenario where this is especially useful is to remove the need for an explicit lambda. E.g:
can be rewritten to:
A bit shorter, less room for errors.