To find the best way to do it by revisiting the end, create a class and perform meta programming starting with @. (ref: http://code.activestate.com/recipes/496691/)
tail_recursive.py
class tail_recursive (object):
def __init__(self, func):
self.func = func
self.firstcall = True
self.CONTINUE = object()
def __call__(self, *arguments, **keywords):
if self.firstcall:
func = self.func
CONTINUE = self.CONTINUE
self.firstcall = False
try:
while True:
result = func(*arguments, **keywords)
if result is CONTINUE: # update arguments
arguments, keywords = self.argskwd
else: # last call
return result
finally:
self.firstcall = True
else: # return the arguments of the tail call
self.argskwd = arguments, keywords
return self.CONTINUE
Use this as @tail_recursive. Tatoheba Next:
@tail_recursive
def sum(n, acc=0):
if n == 0:
return acc
else:
return sum(n - 1, acc + n)
@tail_recursive You can move without it. But that stack overflows soon.
Recommended Posts