Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Currying in ES6

| Comments

As a ritual, let us start with an image of hot curry! :

Indiandishes by kspoddar

Breaking down a function that receives multiple arguments into a series of functions that receives part of the arguments is termed as currying a function.

Moses Schönfinkel introduced it and later was implemented by Haskell Curry, hence it's famous as curry.

Say we have a function : f::(x, y) -> z when curried we get curry(f) :: x -> y -> z.

In ES6 with the help of arrow functions and spread operators we can implement curry like:

1
let curry1 = f => (a) => f(a);
1
let curry2 = f => (...a) => (...b) => f(...a, ...b);
1
let curry3 = f => (...a) => (...b) => (...c) => f(...a, ...b, ...c);
1
let curry4 = f => (...a) => (...b) => (...c) => (...d) => f(...a, ...b, ...c, ...d);

Well, now you might be thinking of curryN or nCurry which would be like:

1
2
3
4
5
6
7
8
9
10
11
12
let nCurry = n =>
  (f, ...args) =>  {
        return function(...nargs) {
            let combinedArgs = args.concat(nargs);
            if (combinedArgs.length < n) {
              combinedArgs.unshift(f);
              return _curry.apply(null, largs);
            } else {
              return f.apply(null, largs);
            }
        };
  };

And can be used like:

1
2
3
4
5
6
7
8
nCurry(n)(f);

/*
Example:

nucrry(6)(fn); // Would give the curried version of `fn` that takes 6 args.

*/

Simpler example:

1
2
3
4
5
6
7
function listify(a,b,c,d) {
  return [a,b,c,d];
}

var listifyCurry = ncurry(4)(listify);

console.log(listifyCurry(1)(2)(3)(4)); [1,2,3,4]

Hope you enjoyed your curry! ;)

Comments