Skip to content

Instantly share code, notes, and snippets.

@sjkillen
Created April 8, 2023 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sjkillen/9bf606f03256bc3f84f20ee51bdcba97 to your computer and use it in GitHub Desktop.
Save sjkillen/9bf606f03256bc3f84f20ee51bdcba97 to your computer and use it in GitHub Desktop.
def factorial(n, accumulator=1):
if n == 1:
return accumulator
return factorial(n - 1, accumulator * n)
try:
factorial(1000)
except RecursionError:
print("TOO MUCH RECURSION!")
def tailcall(fn, *args):
fn = fn(*args)
while callable(fn):
fn = fn()
return fn
from functools import partial
def safe_factorial(n, accumulator=1):
if n == 1:
return accumulator
return partial(safe_factorial, n - 1, accumulator * n)
tailcall(safe_factorial, 20000)# WORKS!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment