Recursions in Python 3.8

In Python 3.8 we can finally write short recursive functions:

>>> (fac := lambda n: (1 if n<2 else n*fac(n-1)))
<function <lambda> at 0x000001AFD258D550>
>>> fac(4)
24

In the same way we can define the notorious fixed point combinator

>>> (Y:= lambda f: lambda *args: f(Y(f))(*args))
<function <lambda> at 0x000001AFD257E0D0>
>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))  # fac in non recursive form
>>> Y(fac)(4)
24

Life is good again!

Leave a Reply