Skip to content

Instantly share code, notes, and snippets.

@karansag
Created May 28, 2014 00:47
Show Gist options
  • Save karansag/17d2cd13a6074a67b286 to your computer and use it in GitHub Desktop.
Save karansag/17d2cd13a6074a67b286 to your computer and use it in GitHub Desktop.
Python Trampolining
def trampoline(f):
def _wrapped(*args, **kwargs):
x = f(*args, **kwargs)
while callable(x):
x = x()
return x
return _wrapped
def factorial(n, total=1):
return total if n == 0 else factorial(n - 1, total * n)
def thunk_factorial(n, total=1):
def ret_func(*args, **kwargs):
return total if n == 0 else thunk_factorial(n - 1, total * n)
return ret_func
print "trampolined 1000!: {}".format(trampoline(thunk_factorial)(1000))
try:
print "regular 1000!: {}".format(factorial(1000))
except RuntimeError, e:
print "regular 1000! ran into exception: {}".format(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment