Scala Higher-Order Functions
A higher-order function is a function that takes another function as a parameter, returns a function, or both. They let you separate what to do with each item from how to walk through the data, and they are the reason Scala code can be both short and expressive.
Taking a function as a parameter
def applyTwice(f: Int => Int, x: Int): Int = f(f(x))
def transformAll(items: List[String], f: String => String): List[String] =
for item <- items yield f(item)
@main def run(): Unit =
println(applyTwice(_ + 3, 10))
println(applyTwice(n => n * n, 3))
println(transformAll(List("a", "b"), s => s + s))
println(transformAll(List("Tom", "Ana"), _.toLowerCase))16
81
List(aa, bb)
List(tom, ana)
The parameter type Int => Int describes the shape of the function that callers must supply.
The big three: map, filter, reduce
Most collection processing is a combination of three higher-order methods.
| Method | Takes | Returns |
|---|---|---|
map(f) |
A => B |
a collection with f applied to every element |
filter(p) |
A => Boolean |
only the elements where p is true |
reduce(op) / foldLeft(z)(op) |
(B, A) => B |
a single combined value |
case class Order(id: Int, amount: Double, paid: Boolean)
@main def run(): Unit =
val orders = List(Order(1, 20.0, true), Order(2, 55.5, false), Order(3, 14.5, true))
val paidTotal = orders.filter(_.paid).map(_.amount).sum
val ids = orders.map(_.id)
val largest = orders.map(_.amount).reduce((a, b) => a max b)
val summary = orders.foldLeft("")((acc, o) => acc + s"#${o.id} ")
println(paidTotal)
println(ids)
println(largest)
println(summary.trim)34.5
List(1, 2, 3)
55.5
#1 #2 #3
Returning a function
A method can build and return a new function. This is a common way to create configurable behaviour.
def discount(percent: Int): Double => Double =
price => price * (100 - percent) / 100
def validator(min: Int, max: Int): Int => Either[String, Int] =
n => if n < min || n > max then Left(s"$n not in [$min, $max]") else Right(n)
@main def run(): Unit =
val summerSale = discount(25)
println(summerSale(80.0))
val checkAge = validator(0, 130)
println(checkAge(42))
println(checkAge(200))60.0
Right(42)
Left(200 not in [0, 130])
Composing functions
Functions have andThen and compose methods that glue them into a pipeline.
@main def run(): Unit =
val trim: String => String = _.trim
val lower: String => String = _.toLowerCase
val slug: String => String = _.replace(' ', '-')
val toSlug = trim andThen lower andThen slug
println(toSlug(" Hello Scala World "))
val square: Int => Int = n => n * n
val inc: Int => Int = _ + 1
println((square compose inc)(4)) // square(inc(4))
println((square andThen inc)(4)) // inc(square(4))hello-scala-world
25
17
Currying
A curried function takes its arguments one list at a time. Supplying the first list returns a specialised function.
def priceWith(currency: String)(amount: Double): String =
f"$amount%.2f $currency"
@main def run(): Unit =
val inEuro = priceWith("EUR")
val inYen = priceWith("JPY")
println(List(9.5, 120.0).map(inEuro))
println(inYen(1500))
val add3 = (a: Int, b: Int, c: Int) => a + b + c
val curried = add3.curried
println(curried(1)(2)(3))List(9.50 EUR, 120.00 EUR)
1500.00 JPY
6
Why higher-order functions matter
| Without them | With them |
|---|---|
A loop, a mutable accumulator, an if inside |
xs.filter(p).map(f).sum |
| Copy-pasting a loop for each variation | one generic method that takes the variation as a function |
| Hard-wired configuration | functions returned from factory methods |
Tip: Read a chain like
orders.filter(_.paid).map(_.amount).sumfrom left to right as a sentence: "take the orders, keep the paid ones, get their amounts, add them up."
Test yourself
Which of these is a higher-order function?
def add(a: Int, b: Int) = a + bdef twice(f: Int => Int, x: Int) = f(f(x))val pi = 3.14def hello() = println("hi")
What is (square compose inc)(4) if square(n) = n*n and inc(n) = n+1?
- 17
- 25
- 16
- 20
What does discount(25) return in the example?
- A
Double - A function
Double => Double 75- A
List