Created
May 28, 2014 00:47
-
-
Save karansag/17d2cd13a6074a67b286 to your computer and use it in GitHub Desktop.
Python Trampolining
This file contains hidden or 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
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