9.3 Function Literals
It would be inconvenient if, to use higher-order functions like find, you always had to separately define (and name) argument functions like hasID12345 and greaterThan90. After all, when you call a function on a string or an integer, you don’t need to define (and name) the values first. This is because programming languages define a syntax for strings and integer literals, like the "foo" and 42 that are sprinkled throughout this book’s code illustrations. Similarly, functional programming languages, which rely heavily on higher-order functions, offer syntax for function literals, also called anonymous functions. The most common form of function literals is lambda expressions, which are often the first thing that comes to mind when you hear that a language has support for functional programming.
In Scala, the syntax for lambda expressions is (v1: T1, v2: T2, ...) => expr.2 This defines a function with arguments v1, v2, . . . that returns the value produced by expr. For instance, the following expression is a function, of type Int => Int, that adds 1 to an integer:
Scala
(x: Int) => x + 1
Function literals can be used to simplify calls to higher-order functions like find:
Scala
temps.find((temp: Int) => temp > 90) projects.find((proj: Project) => proj.id == 12345L)
The Boolean functions “to be greater than 90” and “to have identity 12345” are implemented as lambda expressions, which are passed directly as arguments to method find.
You can also use function literals as return values of other functions. So, a third way to define functions greaterThan and hasID, besides using named local functions or currying, is as follows:
Scala
Listing 9.5: Example of higher-order functions defined using lambda expressions.
def greaterThan(bound: Int): Int => Boolean = (x: Int) => x > bound def hasID(identity: Long): Project => Boolean = (p: Project) => p.id == identity
The expression (x: Int) => x > bound replaces the local function greaterThanBound from Listing 9.3.
Function literals have no name, and usually do not declare their return type. Compilers can sometimes infer the types of their arguments. You could omit argument types in all the examples written so far:
Scala
temps.find(temp => temp > 90) projects.find(proj => proj.id == 12345L) def greaterThan(bound: Int): Int => Boolean = x => x > bound def hasID(identity: Long): Project => Boolean = p => p.id == identity
Today, many programming languages have a syntax for function literals. The Scala expression (temp: Int) => temp > 90 could be written in other languages as shown here:
(int temp) -> temp > 90 // Java (int temp) => temp > 90 // C# [](int temp) { return temp > 90; } // C++ { temp: Int -> temp > 90 } // Kotlin fn temp: int => temp > 90 // ML fn temp -> temp > 90 end // Elixir function (temp) { return temp > 90 } // JavaScript temp => temp > 90 // also JavaScript lambda { |temp| temp > 90 } // Ruby -> temp { temp > 90 } // also Ruby (lambda (temp) (> temp 90)) // Lisp (fn [temp] (> temp 90)) // Clojure lambda temp: temp > 90 // Python
The argument (or arguments) of a lambda expression can be composite types. For example, assume you have a list of pairs (date, temperature), and you need to find a temperature greater than 90 in January, February, or March. You can use find with a lambda expression on pairs:
Scala
val datedTemps: List[(LocalDate, Int)] = ... datedTemps.find(dt => dt(0).getMonthValue <= 3 && dt(1) > 90)
The test checks that the first element of a pair (a date) is in the first three months of the year, and that the second element of the pair (a temperature) is greater than 90.
Languages that support pattern matching often let you use it within a lambda expression. In the preceding example, you can use pattern matching to extract the date and temperature from a pair, instead of dt(0) and dt(1):
Scala
datedTemps.find((date, temp) => date.getMonthValue <= 3 && temp > 90)
This is a lot more readable than the variant that uses dt(0) and dt(1).
More complex patterns can be used. In Scala, a series of case patterns, enclosed in curly braces, also define an anonymous function. For instance, if a list contains temperatures with an optional date, and temperatures without a date are not eligible, you can search for a temperature greater than 90 in the first three months with the following code:3
Scala
val optionalDatedTemps: List[(Option[LocalDate], Int)] = ... optionalDatedTemps.find { case (Some(date), temp) => date.getMonthValue <= 3 && temp > 90 case _ => false }