Partial application and currying
A curried method takes its arguments one list at a time, and a call that stops after the first list has a value: a function of the rest. The same idea in the other direction is partial application, where an argument of a function value is left open with an underscore. Both are ways to turn a general function into the specific one a call needs.
A curried method
add(a: Int)(b: Int) has two parameter lists. The call add(5) fills the first and returns a function of the second, which is why addFive(3) and add(5)(3) are the same call:
currying.scala
def add(a: Int)(b: Int): Int = a + b
def greet(greeting: String)(name: String): String = s"$greeting, $name"
@main def currying(): Unit =
val addFive = add(5)
println(addFive(3))
println(add(2)(3))
val hello = greet("Hello")
println(hello("Ada"))
println(List("Ada", "Grace").map(hello))
scala-cli run --server=false currying.scala
8
5
Hello, Ada
List(Hello, Ada, Hello, Grace)
The second list is where a dependency or a configuration belongs: the first call fixes the greeting, and the resulting function is then a candidate for map. A method with a using clause has the same shape, and the given lesson uses it that way.
Partial application with an underscore
A function value of two arguments can be called with one of them replaced by _, which leaves a function of one argument. The standard library offers the same move as a method: curried turns a function of two arguments into one of two lists, and tupled takes a function of two arguments and a pair:
placeholders.scala
@main def placeholders(): Unit =
val add = (a: Int, b: Int) => a + b
val addTen = add(10, _)
println(addTen(5))
val curried = add.curried
println(curried(1)(2))
val tupled = add.tupled
println(tupled((3, 4)))
println(List(1, 2, 3).map(_ + 1))
scala-cli run --server=false placeholders.scala
15
3
7
List(2, 3, 4)
add(10, _) is the partial application, add.curried the method that gives the same effect to a function value, and add.tupled the form that takes the pair a zip produces. The last line is the plain placeholder again, and it is the form a reader meets most often.
Related
- Higher-order functions: the methods that use a function returned this way.
- Methods and parameters: several parameter lists on a method.
- given and using: the second list as a dependency.
- Partial functions: a function defined on part of its domain, which is a different idea with a similar name.
Article author: Arthur Isaev