Created
November 27, 2019 22:05
-
-
Save gatlin/a27e4360b24d45d0fbd8bc30a25adc00 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 cont: | |
def __init__(self, fn): | |
self.fn = fn | |
def __call__(self, *args, **kwargs): | |
return (lambda: self.fn(*args, self, **kwargs)) | |
class tailrec: | |
def __init__(self, fn): | |
self.fn = fn | |
def __call__(self, *args, **kwargs): | |
a = self.fn(*args, cont(self.fn), **kwargs) | |
# count = 0 | |
while callable(a): | |
# print('loop %d' % (count,)) | |
# count = count + 1 | |
a = a() | |
return a | |
@tailrec | |
def factorial_rec(n, acc, k): | |
if n == 1: | |
return acc | |
else: | |
acc = n * acc | |
n = n - 1 | |
return k(n, acc) | |
def factorial(n): | |
return factorial_rec(n, 1) | |
if __name__=='__main__': | |
print(factorial(5)) | |
print(factorial(50)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment