Created
April 8, 2023 00:59
-
-
Save sjkillen/9bf606f03256bc3f84f20ee51bdcba97 to your computer and use it in GitHub Desktop.
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
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