Created
September 6, 2018 11:44
-
-
Save Z-Shang/87e01ef9f4451752a9bdcd3b5398073c to your computer and use it in GitHub Desktop.
Working yet naive Tail Call Optimisation (Trampoline) in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import namedtuple | |
TailCall = namedtuple("TailCall", ['fn', 'args', 'kargs']) | |
class tco: | |
def __init__(self, f): | |
self.fn = f | |
def __call__(self, *a, **k): | |
retval = self.fn(*a, **k) | |
while isinstance(retval, TailCall): | |
if isinstance(retval.fn, tco): | |
retval = retval.fn.fn(*retval.args, **retval.kargs) | |
return retval | |
def recur(f, *a, **k): | |
return TailCall(f, a, k) | |
@tco | |
def foo(n): | |
print(n) | |
if n > 0: | |
return recur(bar, n - 1) | |
@tco | |
def bar(n): | |
print(n) | |
if n > 0: | |
return recur(foo, n - 1) | |
foo(10000000000000000000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
such a smart girl!