Scala Currying and Partial Application
Currying is a way of writing a function with several argument lists instead of one argument list. Partial application is fixing some of those arguments early and keeping the rest for later.
A curried function takes one argument list at a time
add takes its first number and then its second number. Adding 2 and 3 gives 5.
@main def main(): Unit =
def add(a: Int)(b: Int): Int = a + b
println(add(2)(3))Partial application fixes the first argument
add2 fixes the first argument as 2 and waits for the second. Adding 2 to 10 gives 12.
@main def main(): Unit =
def add(a: Int)(b: Int): Int = a + b
val add2 = (b: Int) => add(2)(b)
println(add2(10))Currying can carry a range check in stages
between fixes the low end and then the high end before testing a value. 7 is inside 1 to 10, and 20 is not.
@main def main(): Unit =
def between(lo: Int)(hi: Int)(x: Int): Boolean = x >= lo && x <= hi
println(between(1)(10)(7))
println(between(1)(10)(20))Example
@main def main(): Unit =
def multiply(a: Int)(b: Int): Int = a * b
val triple = (b: Int) => multiply(3)(b)
println(List(1, 2, 3).map(triple))
println(triple(10))Key points
- Curried function: a function written with more than one argument list.
- Argument list: one pair of parentheses holding one or more arguments.
- Partial application: fixing the first arguments now and supplying the rest later.
- Specialised function: a new function made by fixing some arguments of a general one.
- Readable call: separate argument lists can group settings apart from the main value.
In this example, multiply is curried, and triple fixes its first argument as 3. Mapping triple over the list multiplies each number by 3. Applying triple to 10 gives 30.
Note
a curried call needs each argument list in turn. Missing a list leaves a function, not a result.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
Given def add(a: Int)(b: Int): Int = a + b and val add5 = (b: Int) => add(5)(b), what is add5(4)?