4

在尝试了解 Y-Combinator 一个小时后......我终于明白了,但后来我意识到没有它也可以实现同样的事情......虽然我不确定我是否完全理解它的目的。

例如。使用 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())

通过引用另一个 lambda 中的函数来实现阶乘

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

谁能告诉我 Y-Combinator 在 python 中是否有目的?

4

2 回答 2

8

The purpose of the Y combinator is to demonstrate how to write an arbitrary recursive function using only anonymous functions. But almost every language ever invented allows named 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 in which the Y combinator is actually useful in practice are the "Turing tarpit" languages, like Unlambda. Not even Lisp/Scheme users will typically use the Y combinator when writing real programs.

于 2012-02-19T09:19:53.573 回答
3

Python is not based on Lambda calculus; when you put the question this way it does not make much sense. The lambda statement is simply a practical feature to create an anonymous function inplace:

>>> 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 this way because it was borrowed from functional languages, but it is not for computing with combinatory logic.

于 2012-02-19T09:21:25.510 回答