-1

I want to implement a function which can accept any number of chained calls, like.

add(1)(2); // 3
add(1)(2)(3); // 6
add(1)(2)(3)(4); // 10

If I implement it like following, it will only accept 1st call.

function add(n){
  return function add_impl(a)
  {
   return n + a;
  };
}

And I need to write it like following to get 2nd call accepted.

function add(n){
  return function add_impl(a)
  {
   return function add_impl2(b)
   {
     return n + a + b;
   }
  }
}

I want to make this generic, so that any number of arguments can be passed.

g-217
  • 2,069
  • 18
  • 33
  • I think you might need at least another `()` at the end to finally calculate it - but in any case this is generally known as "currying". – Jamiec Jul 18 '17 at 09:09
  • I can hardly see this making any sense. An `add` function that takes a variable number of arguments might be practical - but this, rather not. – CBroe Jul 18 '17 at 09:09
  • function pass through arguments add(1,2,3,4) – Sudharsan S Jul 18 '17 at 09:10
  • @gjha Just use Y-combinator, which is fixed point combinator. In this case function will able to call function itself by Y-point. – Vladislav Ihost Jul 18 '17 at 09:11
  • @gjha It's same that Church numbers. You can easely google it and full implementation for calculation, based on Church numbers. – Vladislav Ihost Jul 18 '17 at 09:12

2 Answers2

2

You could do this but you'd still need an empty () at the end to let the function know that your calculations are done.

var a = 0;
function add(n) {
  if (arguments.length) {
    a += n;
    return add;
  }
  return a;
}

var x = add(2)(3)(4)(5);
console.log(x());
H77
  • 5,859
  • 2
  • 26
  • 39
0

You can do it like this,

int foo(int... args) {
    int total = 0;
    for (int arg : args) {
        total = total + arg;
    }
    return total;
}
Sameera.San
  • 67
  • 2
  • 15