Last active
March 17, 2019 12:41
-
-
Save xPapla/94509008bb58d391e22f24bb15497d5d to your computer and use it in GitHub Desktop.
Turbo recursion, tail call optimization https://code.activestate.com/recipes/474088/
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
class TailRecurseException(BaseException): | |
def __init__(self, args, kwargs): | |
self.args = args | |
self.kwargs = kwargs | |
def tail_call_optimized(g): | |
""" | |
This function decorates a function with tail call | |
optimization. It does this by throwing an exception | |
if it is it's own grandparent, and catching such | |
exceptions to fake the tail call optimization. | |
This function fails if the decorated | |
function recurses in a non-tail context. | |
""" | |
def func(*args, **kwargs): | |
f = sys._getframe() | |
if f.f_back and f.f_back.f_back \ | |
and f.f_back.f_back.f_code == f.f_code: | |
raise TailRecurseException(args, kwargs) | |
else: | |
while True: | |
try: | |
return g(*args, **kwargs) | |
except TailRecurseException as e: | |
args = e.args | |
kwargs = e.kwargs | |
func.__doc__ = g.__doc__ | |
return func | |
@tail_call_optimized | |
def fibonacci(x): |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment