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)))
 at 0x000001AFD258D550>;
>>> fac(4)

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

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

Life is good again!

This entry was posted in General. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *