Unless you’re deeply into theory, you can regard the Y combinator
as a neat trick with functions, like monads.
Monads allow you to chain actions, the Y combinator allows you to
define self-recursive functions.
Python has built-in support for self-recursive functions, so you
can define them without Y:
> def fun():
> print "bla"
> fun()
> fun()
bla
bla
bla
...
fun
is accessible inside fun
itself, so we can easily call it.
But what if Python were different, and fun
weren’t accessible
inside fun
?
> def fun():
> print "bla"
> # what to do here? (cannot call fun!)
The solution is to pass fun
itself as an argument to fun
:
> def fun(arg): # fun receives itself as argument
> print "bla"
> arg(arg) # to recur, fun calls itself, and passes itself along
And Y makes that possible:
> def Y(f):
> f(f)
> Y(fun)
bla
bla
bla
...
All it does it call a function with itself as argument.
(I don’t know if this definition of Y is 100% correct, but I think it’s the general idea.)