Haskell Higher-Order Functions
A higher-order function is a function that takes another function as an argument. It applies the function it receives inside its own work.
applyTwice applies a named function twice
applyTwice takes a function f and a value x. It applies double to 3, then applies double again to the result.
double x = x * 2
applyTwice f x = f (f x)
main :: IO ()
main = print (applyTwice double 3)applyTwice can take a lambda
The lambda adds 5 to its input. applyTwice applies it to 10 and then applies it again to that result.
applyTwice f x = f (f x)
main :: IO ()
main = print (applyTwice (\x -> x + 5) 10)A function argument can be used once
applyToTen applies whichever function it receives to 10. Here it receives square, so the result is 10 times 10.
applyToTen f = f 10
square x = x * x
main :: IO ()
main = print (applyToTen square)Example
double x = x * 2
addThree x = x + 3
applyTwice f x = f (f x)
main :: IO ()
main = print [applyTwice double 2, applyTwice addThree 10, applyTwice (\x -> x * x) 3]Key points
- Higher-order function: a function that takes another function as one of its arguments.
- Function argument: the caller passes a function in, and the receiving function applies it where it needs it.
- applyTwice: the function applyTwice f x applies f to x, then applies f again to that result.
- Named argument: a function defined by name, such as double, can be passed by its name alone.
- Lambda argument: a lambda can be passed in brackets when no named function fits.
In this example, applyTwice receives double first and applies it twice to 2, giving 8. It then applies addThree twice to 10, giving 16, and applies a squaring lambda twice to 3, giving 81.
Note
passing a function does not run it, because the receiving function decides where to apply it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What is applyTwice (\x -> x + 1) 4?