Are 'currying' and 'composition' the same concept in Javascript? Are 'currying' and 'composition' the same concept in Javascript? javascript javascript

Are 'currying' and 'composition' the same concept in Javascript?


@Omarjmh's answer is good but the compose example is overwhelmingly complex for a learner, in my opinion

Are they the same concept?

No.

First, currying is translating a function that takes multiple arguments into a sequence of functions, each accepting one argument.

// not curriedconst add = (x,y) => x + y;add(2,3); // => 5// curriedconst add = x => y => x + y;add(2)(3); // => 5

Notice the distinct way in which a curried function is applied, one argument at a time.


Second, function composition is the combination of two functions into one, that when applied, returns the result of the chained functions.

const compose = f => g => x => f(g(x));compose (x => x * 4) (x => x + 3) (2);// (2 + 3) * 4// => 20

The two concepts are closely related as they play well with one another. Generic function composition works with unary functions (functions that take one argument) and curried functions also only accept one argument (per application).

// curried add functionconst add = x => y => y + x;// curried multiplication functionconst mult = x => y => y * x;// create a composition// notice we only apply 2 of comp's 3 parameters// notice we only apply 1 of mult's 2 parameters// notice we only apply 1 of add's 2 parameterslet add10ThenMultiplyBy3 = compose (mult(3)) (add(10));// apply the composition to 4add10ThenMultiplyBy3(4); //=> 42// apply the composition to 5add10ThenMultiplyBy3(5); //=> 45 


Composition and currying are used to create functions. Composition and currying differ in the way they create new functions (by applying args vs chaining).

Compose:

Compose should return a function that is the composition of a list of functions of arbitrary length. Each function is called on the return value of the function that follows. You can think of compose as moving right to left through its arguments.

Example:

var compose = function(funcs) {  funcs = Array.prototype.slice.call(arguments, 0);  return function(arg) {    return funcs.reduceRight(function (a, b) {      a = a === null ? a = b(arg) : a = b(a);      return a;    }, null);  };};var sayHi = function(name){ return 'hi: ' + name;};var makeLouder = function(statement) { return statement.toUpperCase() + '!';};var hello = compose(sayHi, makeLouder);l(hello('Johhny')); //=> 'hi: JOHNNY!'

Currying:

Currying is a way of constructing functions that allows partial application of a function’s arguments.

Example:

var addOne = add(1);var addTwo = add(2);var addOneToFive = addOne(5);var addTwoToFive = addTwo(5);l(addOneToFive); //6l(addTwoToFive); //7

JSBin with the above examples:https://jsbin.com/jibuje/edit?js,console