Created
December 2, 2014 22:14
-
-
Save r14c/1350861c19bae9156de6 to your computer and use it in GitHub Desktop.
Tail Recursion Decorator
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
# -*- coding: utf-8 -*- | |
class tail_recursive(object): | |
""" | |
Based on comments on this active state recipe: <http://code.activestate.com/recipes/496691/> | |
""" | |
def __init__(self, func): | |
self.func = func | |
self.firstcall = True | |
self.CONTINUE = object() | |
def __call__(self, *args, **kwd): | |
if self.firstcall: | |
func = self.func | |
CONTINUE = self.CONTINUE | |
self.firstcall = False | |
try: | |
while True: | |
result = func(*args, **kwd) | |
if result is CONTINUE: # update arguments | |
args, kwd = self.argskwd | |
else: # last call | |
return result | |
finally: | |
self.firstcall = True | |
else: # return the arguments of the tail call | |
self.argskwd = args, kwd | |
return self.CONTINUE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment