Scala Higher-Order Functions
A higher-order function is a function that takes another function as an argument or returns a function as its result. It lets small pieces of behaviour be reused in new combinations.
A function can be passed as an argument
applyTwice runs its function argument two times in a row. Doubling 3 twice gives 12.
@main def main(): Unit =
def applyTwice(f: Int => Int, x: Int): Int = f(f(x))
println(applyTwice(x => x * 2, 3))A function can be returned from a function
makeAdder builds an adder for a fixed number. The adder for 5 turns 10 into 15.
@main def main(): Unit =
def makeAdder(n: Int): Int => Int = x => x + n
val add5 = makeAdder(5)
println(add5(10))A stored function works with map
A function value can be handed to map like any argument. Every number in the list is tripled.
@main def main(): Unit =
val nums = List(1, 2, 3)
val triple = (x: Int) => x * 3
println(nums.map(triple))Example
@main def main(): Unit =
def twice(f: Int => Int): Int => Int = x => f(f(x))
val add3Twice = twice(x => x + 3)
println(add3Twice(10))
println(List(1, 2, 3).map(add3Twice))Key points
- Higher-order function: a function that takes a function or returns a function.
- Function value: a function stored in a val and passed around like any other value.
- Function type: Int => Int means a function from one Int to one Int.
- Passing a function: a caller supplies the behaviour and the receiver decides when to run it.
- Returning a function: a maker function can build a specialised function and hand it back.
In this example, twice takes a function and returns a new function that runs it two times. add3Twice is twice with adding 3, so it adds 6 in total. Applying it to 10 gives 16, and mapping it over the list adds 6 to each number.
Note
a function value is not a method call. It is the behaviour itself, ready to run later.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
Given def twice(f: Int => Int): Int => Int = x => f(f(x)), what is twice(x => x * 2)(3)?