1. What Currying Is
According to the Wikipedia entry, in computer science currying is the technique of converting a function that takes multiple arguments into a function that takes a single argument (the first argument of the original function), and returns a new function that accepts the remaining arguments and returns a result.
The English definition is a two-level relative clause, so a literal translation ends up with clauses that run too long, and the definition above is a bit of a mouthful. There are a few key points here:
- Multiple arguments are turned into a single argument
- It accepts the remaining arguments
- It returns a new function
Expressed as a formula:
f(x, y, z, ...) => f(x)(y)(z)...
A chain of calls with single arguments replaces a call with multiple arguments.
2. What Currying Is For
In functional programming we often write code with similar functionality but different parameters. Because there is no inheritance or generics, a project accumulates a lot of redundant code that is hard to maintain.
Currying solves this problem. As the definition shows, currying is used to generate functions. Through currying, function calls can be simplified and code can be written that is easier to understand.
In terms of implementation, because it needs to return a stateful anonymous function, it has to be built on closures, and because it also involves chained calls, it has to be built on recursive functions. Although it is simple to use, writing a curry function is not simple.
3. A Currying Example
Below is a currying example in JavaScript:
| |
Run the code above in a browser Console and a dialog box shows 6. curriedSum(1, 2, 3) and curriedSum(1)(2,3) produce the same result.
The logic of this code is to compare the length of curried’s actual arguments with the number of formal parameters of the sum function. When the actual arguments are fewer than the formal parameters, the recursive call keeps increasing the number of actual arguments, for example (1) -> (1, 2). Once the actual arguments are (1, 2, 3) and the length equals the number of formal parameters of sum, the sum function is called.
4. How It Differs from Partial Functions
A partial function expressed as a formula is:
| |
Python provides the functools.partial function, which freezes arguments. Freezing some of the arguments is the defining characteristic of a partial function. Consider the example below:
| |
In the example above, partial functions can likewise generate a variety of functions with similar functionality. This also has very broad applications in engineering. For example, many functional modules need to print logs, and a partial function can generate a logger for each functional module. This both decouples the modules and improves code readability: DevOpsLogger, IstioLogger, IamLogger, and so on.
