Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional JavaScript: Closure & Recursion. Why does this fail?

desired functionality:

mult(3);
 //(x) => 3 * mult(x)
mult(3)(4);
 //(x) => 3 * (4 * mult(x))
mult(3)(4)();
//12

attempt:

function mult(x){
    if(x === undefined){
        return 1;
    }else{
        return (y => x * mult(y));
    }
}

result:

mult(3)
//y => x * mult(y)
//looks pretty good

mult(3)()
//3
//exactly what I want so far. 

mult(3)(4)()
//Uncaught TypeError: mult(...)(...) is not a function

sure enough,

mult(3)(4)
//NaN

Yet mult(3) looks good and typeof mult(3) === "function".

What gives? Can I not be this fancy in JS? Any why not?

like image 445
Paul Avatar asked Jan 20 '26 04:01

Paul


1 Answers

In

mult(3)(4)

mult(3) yields y => 3 * mult(y).

Thus

(y => 3 * mult(y))(4)

becomes

3 * mult(4)

mult(4) yields y => 4 * mult(y).

3 * (y => 4 * mult(y))

is nonsense because you're trying to multiply 3 by a function. This is why you're getting NaN here, and NaN can't itself be further applied.


Possible solution:

function mkmult(acc) {
    return x =>
        x === undefined
            ? acc
            : mkmult(acc * x);
}

const mult = mkmult(1);

console.log(mult(3)());
console.log(mult(3)(4)());
console.log(mult(3)(4)(5)());
like image 97
melpomene Avatar answered Jan 21 '26 16:01

melpomene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!