Functions in Haskell can be composed just as they can be in math. If the function types match you can compose them by simply putting a dot between them.
:t (.)
(.) :: (b -> c) -> (a -> b) -> a -> c
The composition operator takes two function parameters and returns the function that is the composition of its parameters.
- What is the type of the following functions and what are they doing?
show . (*2)
length . (++[1..10])
(+2) . (*10)
-
Rewrite your code from the lambda function lecture to print out even if the length of the word is even and odd otherwise. The following function might be useful evenOdd :: Bool -> String. Use higher order functions and function composition.
-
Create an operator that does the same thing as (.) but with the parameters swapped.
(>>>) :: (a -> b) -> (b -> c) -> a -> c
f >>> g = undefined
The $ operator can be used to reduce the number of parentheses. Consider the following function call.
even (length [1..10])
The parentheses are needed because function application has the highest precedence in Haskell. If you delete the parentheses ghc thinks that you would like to call even with two parameters: the length function and the list [1..10].
You can use the function application operator to avoid the use of parentheses.
even $ length [1..10]
The $ operator will simply call the left parameter on the right parameter. It has the lowest precedence value so both parameters are going to be evaluated before applying the function to the parameter.
- Rewrite at least three old exercises to use function application operator instead of parentheses.