Currying refers to the process of transforming a function with multiple arity into the same function with less arity. The curried effect is achieved by binding some of the arguments to the first function invoke, so that those values are fixed for the next invocation. Here’s an example of what a curried function looks like:
babyAnimals is a curried function; it is designed for the first argument to be ‘prefilled’ before the function itself is fully executed. With this pattern, ‘koala’ can be bound to babyAnimals, and my love for animals other than elephants can easily be expressed.
Currying can be integrated with callbacks to create higher-order ‘factory’ functions. This pattern is extremely useful in event handling, and can also replace the callback pattern that is utilized in node.js (Brun Jouhie has an excellent blog post on this pattern). Here is an example of combining currying with node.js to process a file:
At first it may not seem like much happened here, but this pattern is actually quite powerful. Integrating node with curried functions allows for the read data to be passed around to other bits of code as the file is getting processed. We can defer invoking the read function’s callback until the result is needed. Currying node.js functions can allow for sequential and parallel I/O processing of multiple files, much like the async library for node.js.
Now we can apply currying to any function by passing the function as the first argument to currier.
And that’s it for currying. I hope you have learned something new about this powerful technique! Do you have an example of currying that you’d like to share? If so, please leave it as a gist in the comments.