-
-
Save dsaw/267b82df0ae4abb50eeb73dbefeb6526 to your computer and use it in GitHub Desktop.
Tail Recursion in Python without Introspection
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
from tail_recursion import tail_recursive, recurse | |
# Normal recursion depth maxes out at 980, this one works indefinitely | |
@tail_recursive | |
def factorial(n, accumulator=1): | |
if n == 0: | |
return accumulator | |
recurse(n-1, accumulator=accumulator*n) |
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 Recurse(Exception): | |
def __init__(self, *args, **kwargs): | |
self.args = args | |
self.kwargs = kwargs | |
def recurse(*args, **kwargs): | |
raise Recurse(*args, **kwargs) | |
def tail_recursive(f): | |
def decorated(*args, **kwargs): | |
while True: | |
try: | |
return f(*args, **kwargs) | |
except Recurse as r: | |
args = r.args | |
kwargs = r.kwargs | |
continue | |
return decorated |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment