4

After an hour of trying to understand the Y-Combinator... i finally got it, mostly but then i realized that the same thing can be achieved without it... although I'm not sure if i fully understand it's 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 by haveing a reference to the 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 anybody please tell me if there is a purpose for the Y-Combinator in python?

eumiro
  • 207,213
  • 34
  • 299
  • 261
  • 1
    As much as anything, the point is that it trains your mind to think about and recognise patterns of recursion and iteration. That will help you if you have to use higher order functions, and it will help you recognise when they are useful. – Marcin Feb 19 '12 at 09:29

2 Answers2

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.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
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.

hamstergene
  • 24,039
  • 5
  • 57
  • 72