Php Chinese network (www.php.cn) provides the most comprehensive basic tutorial on programming technology, introducing HTML, CSS, Javascript, Python, Java, Ruby, C, PHP, basic knowledge of MySQL and other programming languages. At the same time, this site also provides a large number of online instances, through which you can better learn programming... Reply content: all recursive calls can be changed to the tail recursion form through CPS transformation, and then the tail recursion can be changed to a loop:
def fact(n): if n == 0: return 1 else: return n * fact(n - 1)id = lambda x: xdef factCPS(n): def f(n, k): if n == 0: return k(1) else: return f(n - 1, lambda x: k(n * x)) return f(n, id)def factNoRec(n): def factory(n, k): return lambda x: k(n * x) k = id while True: if n == 0: return k(1) else: k = factory(n, k) n -= 1def factHolyCrap(n): k = () while True: if n == 0: x = 1 while k: x = k[0] * x k = k[1] return id(x) else: k = (n, k) n -= 1if __name__ == '__main__': print([f(5) for f in [fact, factCPS, factNoRec, factHolyCrap]])
A call stack needs to be maintained during recursion.
If you do not want to recursive the call stack, you can manually maintain the call stack.
The only benefit may be that the limit on the maximum recursive depth is lifted... Add a java sample
public class RecursionEliminationSample { int factorRec(int n) { if (n == 0) return 1; else return n * factorRec(n-1); } int factor(int n) { Function
k = (x) -> x; while(true) { if (n == 0) return k.apply(1); else { final Function
k0 = k; final int n0 = n; k = (x) -> k0.apply(n0 * x); n -= 1; } } }}
Implemented in a loop? You can create a stack to save the status. You only need to understand what the program has put on the stack during recursion, and then use its own stack simulation.
Technically, we can refer to the recursive iteration technology accumulated from the fortran era. Not completely no solution:
Does Python optimize tail recursion?
Recursive iteration technology accumulated by the Times. Then use your own stack simulation ., Theme j