DEV Community

Discussion on: The Currying Introduction I Wish I Had

Collapse
 
peerreynders profile image
peerreynders

Currying solves a problem that JavaScript doesn't have:

Haskell Programming from First Principles

Each lambda can only bind one parameter and can only accept one argument. Functions that require multiple arguments have multiple, nested heads. When you apply it once and eliminate the first (leftmost) head, the next one is applied and so on. This formulation was originally discovered by Moses Schönfinkel in the 1920s but was later rediscovered and named after Haskell Curry and is commonly called currying.

As such the term "currying" is often misapplied in the context of JavaScript. To quote:

  • Currying always produces nested unary (1-ary) functions. The transformed function is still largely the same as the original.
  • Partial application produces functions of arbitrary arity. The transformed function is different from the original – it needs less arguments.

arity: number of arguments taken by a function.

const multiply = (x, y) => x * y;
const curry = (f) => (x) => (y) => f(x, y);
const partApply = (f, x) => (y) => f(x, y);

// currying `multiply`
const multiplyBy5 = curry(multiply)(5);

// partially applying `multiply`
const multiplyBy7 = partApply(multiply, 7);

console.log(multiplyBy5(5)); // 25
console.log(multiplyBy7(5)); // 35
Enter fullscreen mode Exit fullscreen mode

So partial application seems to be the more general and useful concept.