Re:Functional Python Programming
by linkdd on Friday June 09, 2023 @10:29AM
(#36258340)
For tail recursion, you can use this snippet of code:
Of course, it will be slow because it relies on exceptions :P
[ Parent
| on HN ]
You can do a similar thing (that's around 2-3x faster) with a trampoline:
def factorial(n):
res = fac(n)
while callable(res):
res = res()
return res
def fac(n, acc=1):
if n == 1:
return acc
else:
return lambda: fac(n-1, n*acc)