Y Combinator
The Y combinator lets a function call itself without using its own name. Give it a rule that expects a callback for the recursive call, and it supplies a callback that follows that same rule. The trick is to apply a function to a copy of itself.
Notes
Read the notation
In untyped lambda calculus, means “take an input and return the body .” Writing two terms next to each other means application, so applies to itself. Applying a lambda function substitutes the argument for every occurrence bound by that parameter, renaming bound variables as needed to preserve their meaning. This is called beta reduction.
Follow one unfolding
Fix a rule and call either parenthesized block . Open Function position and Argument position in the explorer. The two blocks have the same form. Predict what goes into both places marked when the left block receives the right block as its argument.
After substituting into the outer function, the expression is . Applying the left block replaces both uses of in its body with the right block, so the result is . The whole application has reappeared as the argument to . Call that application . One unfolding yields , so is a fixed point of under beta equivalence. The Fixed-point identity form shows this as .
Calculate factorial
Let take a callback and return a function of a nonnegative integer .
Set . The fixed-point identity says follows this rule with . At , the recursive branch gives . At zero, the base case returns without calling the callback.
When evaluation order matters
With the classic , evaluating function arguments eagerly unfolds the recursive argument before can use it. A direct port to JavaScript therefore keeps unfolding. The related combinator puts the self-application inside another function so it waits until the recursive call receives an argument.
Sources
- Programming in the λ-calculus (2016)CS 4110, Lecture 16, §2.2. Covers the Y and Z combinators, factorial and evaluation order.
- Practical Foundations for Programming Languages, Chapter 21 — Robert Harper§21.2 gives the fixed-point property and explains self-application.