So one of the common examples of tail recursion I see is:
function factorial(x) {
if (x <= 0) {
return 1;
} else {
return x * factorial(x-1); // (A)
}
}
An it's optimized for Tail call with:
function factorial(n) {
return facRec(n, 1);
}
function facRec(x, acc) {
if (x <= 1) {
return acc;
} else {
return facRec(x-1, x*acc); // (A)
}
}
I get this. But my question is: Why isn't the *
in this case a function that could be optimized on?
Couldn't I rewrite the top as
function factorial(x) {
if (x <= 0) {
return 1;
} else {
return multiply(x, factorial(x-1)); // (A)
}
}
I know this won't work. I think it's just because it's not a true tail recursive call? Would this still be tail optimized though?