Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional programming in javascript - add(a)(b)(c)

I trying to wrap my head around functional programming in js.

I understand add(3)(5) would be:

function add(x) {
    return function(y) {
        return x + y;
    };
}

How would I change this function so add(3)(5)(7)(8) returns 23 or add(1)(2)(3) returns 6?

like image 545
wwwuser Avatar asked Jul 29 '15 01:07

wwwuser


2 Answers

you can do something like this.

function add(x) {
  return function(y) {
    if (y) {
      return add(x+y);
    }
    return x;
  };
}

Here, you can call as many times as you want.

add(4)();
add(4)(5)(9)();
add(1)(2)(3)....(n)();

Example link

like image 106
Raj Avatar answered Sep 22 '22 21:09

Raj


Without modifying your definition for add, you would need to chain the calls to add to be (add(add(add(3)(5))(7)))(8).

to clarify, this expression breaks down to:

add(3) //returns a function that adds 3
add(3)(5) //returns 8

add(add(3)(5)) // returns a function that adds 8
(add(add(3)(5)))(7) // returns 15

add ((add(add(3)(5)))(7)) //returns function that adds 15
(add(add(add(3)(5))(7)))(8) //returns 23

Breaking it down even further as @zerkms mentioned (and assigning our function definitions to variables) we can see how the chaining of add works:

var add3 = add(3) //returns a function that adds 3
add3(5) //returns 8

var add8 = add(add3(5)) // returns a function that adds 8
add8(7) // returns 15

var add15 = add(add8(7)) //returns function that adds 15
add15(8) //returns 23

By chaining, we are adding on to the result of the previous call to add.

Meaning that if add(3) returns a function that adds 3 and then you add 5 to that number than you can pass that value, 8, into another call to add to make another function that adds 8 to it's argument.

like image 38
Pavan Ravipati Avatar answered Sep 22 '22 21:09

Pavan Ravipati