2 ms·
Maybe. Tail recursion optimizes itero-recursive algorithms, turning them into iterative algorithms by eliminating the overhead. Confused? Here are the iterativ
by drostie 15y ago
Maybe. Tail recursion optimizes itero-recursive algorithms, turning them into iterative algorithms by eliminating the overhead.
Confused? Here are the iterative, recursive, and itero-recursive ways of writing the factorial function:
function fact_r(N) {
return N <= 0 ? 1 : N * fact_r(N - 1);
}
function fact_i(N) {
var acc = 1, i;
for (i = 1; i <= N; i += 1) {
acc *= i;
}
return acc;
}
function fact_ir(N, acc) {
acc = acc || 1; // default value of acc
return N <= 0 ? acc : fact_ir(N - 1, N * acc);
}
So the accumulator variable becomes an argument variable which may have to be separately initialized. The key feature which makes something optimized for "tail calls" is that when f(something) wants to recurse, it returns f(something else). In other words, certain conditional logics can happen, but don't leave an operation like the "n " in "n recurse(n - 1)" on the stack or else you can't get rid of the function call. It's not even a special optimization -- basically you can move one line in the compiler a couple steps ahead of where you might have automatically written it, and it suddenly treats iteration and tail-recursion the same.
So that's the difference. If you can understand fact_ir, which does the iterative idea in a recursive syntax, then you can understand tail recursion.