by JepZ · 9y ago · 0 comments
function a(){
if(/* Termination Condition */){
return /* Special Element */
} else {
/* Recursion: e.g. a + a */
return a() + a()
}
}
Since that day I love recursions.Contrasted with tree-recursion where the code is often so pithy that its correctness is obvious (assuming you understand recursion).
function f(n,acc) {
if(n == 0) return acc;
else return f(n-1,acc*n);
}
function fact(n) {
return f(n,acc);
}
That's exactly the structure the OP suggested and in this case won't use O(d) space if tail-call elimination is available in the language. Now, if the accumulator is growing a list result like map or some tree traversal, sure. It'll use O(d) memory. But so will the iterative equivalent.