Higher-order functions

A method or a function that takes a function is higher-order, and so is one that returns a function. They are the reason a Scala program can express a loop as map and a filter as filter: the shape of the traversal is written once, and the step is an argument.

A method that takes a function

applyTwice takes a function and a value and applies the function twice. twice takes a function and returns a new one with the same shape; the two are the two directions of the same idea.

higher_order.scala

def applyTwice(f: Int => Int, n: Int): Int = f(f(n)) def twice(f: Int => Int): Int => Int = n => f(f(n)) @main def higherOrder(): Unit = println(applyTwice(_ + 3, 1)) val addTen = twice(_ + 5) println(addTen(0)) println(List(1, 2, 3).map(_ * 10)) println(List(1, 2, 3, 4).filter(_ % 2 == 0)) println(List(1, 2, 3, 4).foldLeft(0)(_ + _))

scala-cli run --server=false higher_order.scala

7
10
List(10, 20, 30)
List(2, 4)
10

applyTwice(_ + 3, 1) passes a lambda of one argument, and twice(_ + 5) returns a function that adds ten. The last three lines are the same shape in the standard library: map transforms each element, filter keeps the ones the function accepts, and foldLeft carries an accumulator from left to right.

A pipeline over data

A program that reads a collection is a chain of these calls. The one below takes a list of employees, extracts the salaries, drops the small ones, sums the rest, and sorts the names by salary — all without a loop and without a mutable variable:

pipeline.scala

case class Employee(name: String, salary: Int) @main def payroll(): Unit = val staff = List(Employee("Ada", 120), Employee("Grace", 90), Employee("Linus", 60)) val total = staff.map(_.salary).filter(_ > 70).sum println(total) println(staff.sortBy(employee => -employee.salary).map(_.name))

scala-cli run --server=false pipeline.scala

210
List(Ada, Grace, Linus)

_.salary is a function of one argument, and sortBy(employee => -employee.salary) sorts by a computed key: the minus turns the descending order into an ascending sort of the negated numbers. Each step returns a new list, so the original staff is unchanged, and the chain reads in the order the data moves.

Related

Article author: Arthur Isaev