3 ms·
http://blog.moertel.com/ http://blog.moertel.com/ does a decent job of explaining some practical aspects for de-recursivying, but I'll give you a basic explanat
by thethirdone 10y ago
http://blog.moertel.com/ http://blog.moertel.com/ does a decent job of explaining some practical aspects for de-recursivying, but I'll give you a basic explanation of that plus a more theoretical answer showing that any computatble function can be written using only while loops and a stack.
Practical:
If we right all of are programs and tail-recursive (returning a recursive call or constant at the end of the prgram) programs they are easy to transform into simple while loops with no stack. The idea is instead of calling another function just restart the current one with the updated arguments.
EX:
f(n,x)=f(n-1,x+1)
f(0,x)=x
goes to
while(n > 0){
n--;
x++
}
Other techniques such as trampolining and continuation passing style also help translate recursive functions into iterative ones.
Theorectical:
Think about Brainfuck or Turing machines, these computing frameworks can compute any computable function using only what amounts to while loops and infinite memory.
Given then that we can produce arbitrary control flow using only while loops, we can reproduce how recursive calls are computed in computers with stack frames (provided by our stack).