function sum(a){
if(!a) return 0;
return b=>a + sum(b);
}
console.log(sum(2)(3)); // returns a string "ab=>a + sum(b)"
console.log(sum(2)(3)()); // says sum (..)(..) is not a function
Is there a particular reason this is happening?
function sum(a){
if(!a) return 0;
return b=>a + sum(b);
}
console.log(sum(2)(3)); // returns a string "ab=>a + sum(b)"
console.log(sum(2)(3)()); // says sum (..)(..) is not a function
Is there a particular reason this is happening?
When you write:
console.log(sum(2)(3));
this can be re-written to be:
const fn = sum(2);
console.log(fn(3));
If you look at what sum(2)
returns, it will return another function:
return b=>a + sum(b);
You then invoke this function using fn(3)
, you perform:
2 + sum(3)
When you call sum(3)
, you again return the same above function, so you are doing:
2 + function
Since addition doesn't work between a number and a function, JS will try and convert the function to a primitive by calling .valueOf()
on your function. Calling .valueOf()
on a function will return it's string version, hence making 2 + function
perform concatenation between your function and the number 2, giving you:
2b=>a + sum(b)
Your second attempt of sum(2)(3)()
tries to invoke this string, and so you get an error when you try and treat the string as something callable.
You don't need sum(b)
in the return statement, just b
function sum(a){
if(!a) return 0;
return b=>a + b;
}
console.log(sum(2)(3));
If you want indefinite chaining of curried functions, see this question: Variadic curried sum function
Maybe try this:
function sum(a, b){
if(!a) return 0;
if(!b) return a;
return a + b;
}
console.log(sum(2,3));