3 ms·
Not pretty, but it does the trick. Kinda. Or at least it won't destroy the stack if you recurse too deep. from collections import namedtuple TailCall = na
by bulatb 13y ago
Not pretty, but it does the trick. Kinda. Or at least it won't destroy the stack if you recurse too deep.
from collections import namedtuple
TailCall = namedtuple('TailCall', ['function', 'args'])
def tail_recurse(fn, args):
next_call = fn(*args)
while isinstance(next_call, TailCall):
next_call = next_call.function(*next_call.args)
return next_call
def count_to_4(start):
"""Dummy tail-recursive function"""
if start == 4:
return 4
else:
return TailCall(count_to_4, [start + 1])
print tail_recurse(count_to_4, [-6])
- deleted 13y ago[deleted]