- Learn Scala Programming
- Slava Schmidt
- 278字
- 2025-02-24 07:23:50
Currying
Speaking about partial application, we have not referred to one special case of this, currying. Currying is in a sense a partial application where we take a function of N arguments and apply partial application for each argument in a row each time, to produce a function that takes one argument less. We repeat this process until we're left with N functions, each taking one argument. If it sounds complicated, consider the next example of a function of two arguments:
def sum(a: Int, b: Int) = a + b
Using two parameter lists, we can rewrite it as follows:
def sumAB(a: Int)(b: Int) = a + b
The type of this method is (a: Int)(b: Int): Int or expressed as a function:
:type sumAB _
Int => (Int => Int)
This is a function that takes an Int and returns a function from Int to Int! The number of arguments is not limited to just two of course:
scala> val sum6 = (a: Int) => (b: Int) => (c: Int) => (d: Int) => (e: Int) => (f: Int) => a + b + c + d+ e + f
sum6: Int => (Int => (Int => (Int => (Int => (Int => Int)))))
The placeholder syntax will give us the same functionality, but in uncurried form:
scala> val sum6Placeholder = (_: Int) + (_: Int) + (_: Int) + (_: Int) + (_: Int) + (_: Int)
sum6Placeholder: (Int, Int, Int, Int, Int, Int) => Int
Currying is not very important in Scala compared to some other functional programming languages, but it is good to know as a useful functional programming concept.