Sadly, Python is a pretty poor functional language. The core of functional programming is about avoiding mutable states , not much about anonymous functions or passing functions as data. To do proper functional programming in Python, there should be IMO: - a way to enforce non-mutable variables/objects; - non-mutable collections; - proper support for recursion and tail-recursion optimization; - a better syntax for an…
For tail recursion, you can use this snippet of code: class Recurse(Exception): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs class Terminate(Exception): def __init__(self, retval): self.retval = retval def tailrec(func): def wrapper(*args, **kwargs): while True: try: func(*args, **kwargs) except Recurse as r: args = r.args kwargs = r.kwargs except Terminate as t: return t.retval return w…
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)