Currying is a technique used to translate a function that takes
multiple arguments into a sequence of single-argument functions. For
example, here is a normal function with 2 arguments:
With currying, it can be translated into a function same as below:
We can call the curried function like this:
Implementing currying
As we can see, the function curry should take a normal function, and
return its curried function. The curried function actually needs to do
two things:
collecting arguments, and
returning another curried function that does the same two things
Obviously, it is a recursive pattern:
In addition, we also need to terminate the recursion when it has
collected enough arguments, and finally apply the arguments to the
input function.
Here is the complete curry:
It takes 3 arguments: a function f, the number of arguments to
accumulate nargs, and the accumulated arguments args.
Try it with some examples:
Passing multiple arguments is possible for the sake of convenience:
Note that if you need to bind an argument to a function that only
takes a single argument, below is the only way:
Implementing uncurrying
Uncurrying is the reverse operation to currying. It converts a curried
function to a function that takes multiple arguments. Uncurrying can
be also implemented in a recursive way. Uncurrying a function
involves:
call the curried function with a single argument, and
uncurry the curried function returned by step 1
Same as currying, the recursion stops when it consumed enough
arguments:
Some examples:
Conclusion
Play with it if you are interested. All code in this article is
available at
here
and tested under Node.js.