Python doesn't need Y-Combinator?

An hour later, trying to understand Y-Combinator ... I finally got it, basically, but then I realized that the same thing could be achieved without it ... although I'm not sure how much I fully understand its purpose.

eg. Factorials with Y-Combinator

print (lambda h: (lambda f:f(f))(lambda f: h(lambda n: f(f)(n))))(lambda g: lambda n: n and n * g(n-1) or 1)(input()) 

Factorials, referencing a function in another lambda

 print (lambda f,m:f(f,m))((lambda g,n: n and n * g(g,n-1) or 1),input()) 

Can someone tell me if there is a goal for Y-Combinator in python?

+4
source share
2 answers

The purpose of Y combinator is to demonstrate how to write an arbitrary recursive function using only anonymous functions. But almost every language ever invented allows you to name functions! In other words, it is mainly of academic interest. Of course, you can define factorials much more "naturally" in Python:

 def fac(n): return n * fac(n-1) if n else 1 

The only languages ​​that Y combinator is really useful in practice are Turing tarpit languages ​​such as Unlambda. Even Lisp / Scheme users usually use Y combinator when writing real programs.

+8
source

Python is not based on lambda calculus; when you pose the question this way, it doesn't make much sense. The lambda operator is just a practical function to create an anonymous inplace function:

 >>> list( map(lambda x: x**2, [1, 2, 3, 4, 5]) ) [1, 4, 9, 16, 25] # the same as: >>> def sq(x): ... return x**2 ... >>> list( map(sq, [1, 2, 3, 4, 5]) ) [1, 4, 9, 16, 25] 

It is named that way because it was borrowed from functional languages, but not for computations with combinatorial logic.

+3
source

Source: https://habr.com/ru/post/1397264/


All Articles