Skip to content

Instantly share code, notes, and snippets.

@Z-Shang
Created September 6, 2018 11:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Z-Shang/87e01ef9f4451752a9bdcd3b5398073c to your computer and use it in GitHub Desktop.
Save Z-Shang/87e01ef9f4451752a9bdcd3b5398073c to your computer and use it in GitHub Desktop.
Working yet naive Tail Call Optimisation (Trampoline) in Python
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)
@thautwarm
Copy link

such a smart girl!

@Z-Shang
Copy link
Author

Z-Shang commented Sep 6, 2018

@thautwarm nyaaaaa

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment