Did you ever wonder how Y works and how anyone could ever have thought of it? In this article, I explain not only how it works, but how someone could have invented it in the first place. I'll use Scheme notation because when functions passed as arguments are applied, Y is easier to understand.
Y's goal is to provide a mechanism to write self-referential progra ms without any special built-in means. Scheme has several mechanisms for writing such programs, including global function definitions and letrec. One way you can write the factorial function in Scheme is:
(define fact (lambda (n) (if (< n 2) 1 (* n (fact (- n 1))))))
This function works because a global variable, fact, has its value set to the value of the lambda expression. When the variable fact in the body of the function is evaluated to determine which function to invoke, the value is found in the global variable. Using a global variable as a function name can be rather unpleasant because it relies on a global, and thus vulnerable, resource -- that is, the global variable space.
The Scheme self-reference form letrec usually is implemented using a side effect; it is easier to reason about programming languages and programs that have no side effects. Therefore, it is of theoretical interest to establish the ability to write recursive functions without using side effects. A program that uses letrec is:
(letrec ((f (lambda (n) (if (< n 2) 1 (* n (f (- n1))))))) (f 10))
This program computes 10!. The reference inside the lambda express ion is to the binding of f, as established by the letrec.
You can implement letrec using let and set!:
(letrec ((f (lambda ...))) ...)
which is equivalent to:
(let ((f <undefined>)) (set! f (lambda ...)) ...)
All references to f in the lambda expression are to the value of the lambda expression.
Y takes a function describing another recursive or self-referential function and returns another function that implements the recursive function. Y is used to compute 10! with:
(let ((f (y (lambda (n) (lambda (n) (if (< n 2) 1 (* n (h (- n 1))))) )))))) (f 10))
The function passed as an argument to Y takes a function as an argument and returns a function that looks like the factorial function we want to define. That is, the function passed to Y is (lambda (h) ...). The body of this function looks like the factorial function, except that where we would expect a recursive call to the factorial function, h is called instead. Y arranges for an appropriate value to be supplied as the value of h.