Taking and returning functions
A higher-order function (HOF) is a function that takes another function as a parameter, returns one, or both. In Scala a function is an ordinary value with a type such as Int => Int ("takes an Int, returns an Int") or (String, Int) => Boolean. You pass it like any other argument — you have been doing it since Module 03 every time you wrote xs.map(_ * 2).
def applyTwice(f: Int => Int, x: Int): Int = f(f(x))
def multiplier(n: Int): Int => Int = x => x * n
def describe(label: String, f: Int => Int): String =
s"$label: ${(1 to 4).map(f).mkString(", ")}"
@main def run(): Unit =
println(applyTwice(_ + 3, 10))
println(applyTwice(x => x * x, 3))
val triple = multiplier(3)
println(triple(7))
println(applyTwice(triple, 2))
println(describe("double", multiplier(2)))
println(describe("square", x => x * x))16
81
21
18
double: 2, 4, 6, 8
square: 1, 4, 9, 16multiplier returns a function: multiplier(3) is a value of type Int => Int you can store, call and pass on. applyTwice does not care which function it gets, only its type.
Write def adder(n: Int): Int => Int and use it with applyTwice to add 5 twice to 100.
A lambda with no parameter type to infer
@main def run(): Unit =
val inc = x => x + 1
println(inc(4))-- [E081] Type Error: Main.scala:2:12
2 | val inc = x => x + 1
| ^
| Missing parameter type
|
| I could not infer the type of the parameter x
1 error found
Compilation failedWhen you pass x => x + 1 to map, the compiler knows from map's signature what x must be. Stored in a bare val there is nothing to infer from, and x could be an Int, a String or anything else with a +.
Give the parameter a type, or give the val a function type so the compiler can work backwards.
@main def run(): Unit =
val inc = (x: Int) => x + 1
val dec: Int => Int = x => x - 1
println(inc(4))
println(dec(4))