Created
April 25, 2015 13:51
-
-
Save entwanne/42050b38a35597f21601 to your computer and use it in GitHub Desktop.
Python tail-recursive
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 tail_rec: | |
inside = False | |
def __init__(self, func): | |
self.func = func | |
def __call__(self, *args, **kwargs): | |
if tail_rec.inside: | |
self.args = args | |
self.kwargs = kwargs | |
return self | |
try: | |
tail_rec.inside = True | |
r = self.func(*args, **kwargs) | |
while isinstance(r, tail_rec): | |
r = r.func(*r.args, **r.kwargs) | |
return r | |
finally: | |
tail_rec.inside = False | |
@tail_rec | |
def factorielle(n, acc=1): | |
if not n: | |
return acc | |
return factorielle(n - 1, acc * n) | |
print(factorielle(5000)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment