/ es6

Curry

This week I had a passing conversation with another engineer that highlighted a misunderstanding that I had about what exactly it means to create a curried function. My misuse of the term had concerned the pipe function because, as I understood it, to curry a function was to create a function that would stow the initial arguments and return a new function to await its final arguments.

In fact this is not quite accurate. What it truly means to curry a function is to create a new function which allows the original function, now curried, to be passed multiple arguments independently. A simple example might go like this:

//Not curried
const greeter = (name, time) => `Good ${time}, ${name}`;
greeter('John', 'afternoon'); //Good afternoon, John

//Curried
const curriedGreeter = (time) => {
  return (name) => `Good ${time}, ${name}`;
};
const greetAfternoon = curriedGreeter('afternoon');
greetAfternoon('John'); //Good afternoon, John
greetAfternoon('Jane'); //Good afternoon, Jane

Pipe on the other hand allows many functions to be called in series on a single argument, in its most basic form:

const pipe = (...args) => {
  return args.reduce((func, arg) => {
    return (...args) => arg(func);
  });
};

So while both involve returning functions to be called in the future the means and the end are entirely different. While piping functions can be a convenience currying is in fact very very practical and commonly used in creating utility functions in libraries. One example I have used often as of late is the connect function in Redux’s React wrapper.

P.S. es6 love:

const pipe = (...args) => args.reduce((func, arg) => (...args) => arg(func)