The code in question:
lambda b : (lambda a, b : a(a, b)) (lambda a, b : b * a(a, b-1) if b > 0 else 1, b)
To make it clearer, let me replace variable names a with f, and b with n
.
lambda n : (lambda f, n : f(f, n)) (lambda f, n : n * f(f, n-1) if n > 0 else 1, n)
Recursive Factorial is a function that will call itself, or be applied to itself, something like f(f).
Let us set Factorial(n) to be f(f,n)
and compute as follows:
def func(f, n): # takes a function and a number, return a number.
if n > 0 :
return n * f(f, n-1)
else :
return 1
Translating the above def func into lambda notation:
func is lambda f, n : n * f(f, n-1) if n > 0 else 1
func is then to be applied to itself along with integer n.
Back to beginning statement, Factorial(n) is f(f,n), or f(func,n) when func is applied into f.
def Factorial(n):
# return f (func, n) # next, substitute f and func with their corresponding lambdas.
return (lambda f, n : f(f, n)) (lambda f, n : n * f(f, n-1) if n > 0 else 1, n)
and using lambda instead of def Factorial, the whole thing becomes:
lambda n : (lambda f, n : f(f, n)) (lambda f, n : n * f(f, n-1) if n > 0 else 1, n)