Skip to content

Instantly share code, notes, and snippets.

@dsaw
Forked from ChrisPenner/factorial.py
Created August 20, 2018 16:49
Show Gist options
  • Save dsaw/267b82df0ae4abb50eeb73dbefeb6526 to your computer and use it in GitHub Desktop.
Save dsaw/267b82df0ae4abb50eeb73dbefeb6526 to your computer and use it in GitHub Desktop.
Tail Recursion in Python without Introspection
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)
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