4215a4ae8710166057bd538aa6381f4110fe6982
[lambda.git] / topics / _week4_fixed_point_combinator.mdwn
1 [[!toc levels=2]]
2
3 ~~~~
4
5 **Chris:** I'll be working on this page heavily until 11--11:30 or so. Sorry not to do it last night, I crashed.
6
7 ξ
8 Θ′
9
10 ~~~~
11
12 #Recursion: fixed points in the Lambda Calculus#
13
14 Sometimes when you type in a web search, Google will suggest
15 alternatives.  For instance, if you type in "Lingusitics", it will ask
16 you "Did you mean Linguistics?".  But the engineers at Google have
17 added some playfulness to the system.  For instance, if you search for
18 "anagram", Google asks you "Did you mean: nag a ram?"  And if you
19 [search for "recursion"](http://www.google.com/search?q=recursion), Google asks: "Did you mean: recursion?"
20
21 ##What is the "rec" part of "letrec" doing?##
22
23 How could we compute the length of a list? Without worrying yet about what Lambda Calculus encoding we're using for the list, the basic idea is to define this recursively:
24
25 >   the empty list has length 0
26
27 >   any non-empty list has length 1 + (the length of its tail)
28
29 In OCaml, you'd define that like this:
30
31     let rec length = fun xs ->
32                        if xs = [] then 0 else 1 + length (tail xs)
33     in ... (* here you go on to use the function "length" *)
34
35 In Scheme you'd define it like this:
36
37     (letrec [(length  (lambda (xs)
38                         (if (null? xs) 0
39                                        (+ 1 (length (cdr xs))) )))]
40             ... ; here you go on to use the function "length"
41     )
42
43 Some comments on this:
44
45 1. `null?` is Scheme's way of saying `empty?`. That is, `(null? xs)` returns true (which Scheme writes as `#t`) iff `xs` is the empty list (which Scheme writes as `'()` or `(list)`).
46
47 2. `cdr` is function that gets the tail of a Scheme list. (By definition, it's the function for getting the second member of a [[dotted pair|week3_unit#imp]]. As we discussed in notes for last week, it just turns out to return the tail of a list because of the particular way Scheme implements lists.)
48
49 3.  We alternate between `[ ]`s and `( )`s in the Scheme code just to make it more readable. These have no syntactic difference.
50
51
52 The main question for us to dwell on here is: What are the `let rec` in the OCaml code and the `letrec` in the Scheme code?
53
54 Answer: These work a lot like `let` expressions, except that they let you use the variable `length` *inside* the body of the function being bound to it---with the understanding that it will there be bound to *the same function* that you're *then* in the process of binding `length` to. So our recursively-defined function works the way we'd expect it to. Here is OCaml:
55
56     let rec length = fun xs ->
57                        if xs = [] then 0 else 1 + length (tail xs)
58     in length [20; 30]
59     (* this evaluates to 2 *)
60
61 Here is Scheme:
62
63     (letrec [(length (lambda (xs)
64                        (if (null? xs) 0
65                                       (+ 1 (length (cdr xs))) )))]
66       (length (list 20 30)))
67     ; this evaluates to 2
68
69 If you instead use an ordinary `let` (or `let*`), here's what would happen, in OCaml:
70
71     let length = fun xs ->
72                    if xs = [] then 0 else 1 + length (tail xs)
73     in length [20; 30]
74     (* fails with error "Unbound value length" *)
75
76 Here's Scheme:
77
78     (let* [(length (lambda (xs)
79                      (if (null? xs) 0
80                                     (+ 1 (length (cdr xs))) )))]
81       (length (list 20 30)))
82     ; fails with error "reference to undefined identifier: length"
83
84 Why? Because we said that constructions of this form:
85
86     let
87       length match/= A
88     in B
89
90 really were just another way of saying:
91
92     (\length. B) A
93
94 and so the occurrences of `length` in A *aren't bound by the `\length` that wraps B*. Those occurrences are free.
95
96 We can verify this by wrapping the whole expression in a more outer binding of `length` to some other function, say the constant function from any list to the integer `99`:
97
98     let length = fun xs -> 99
99     in let length = fun xs ->
100                       if xs = [] then 0 else 1 + length (tail xs)
101     in length [20; 30]
102     (* evaluates to 1 + 99 *)
103
104 Here the use of `length` in `1 + length (tail xs)` can clearly be seen to be bound by the outermost `let`.
105
106 And indeed, if you tried to define `length` in the Lambda Calculus, how would you do it?
107
108     \xs. (empty? xs) 0 (succ (length (tail xs)))
109
110 We've defined all of `empty?`, `0`, `succ`, and `tail` in earlier discussion. But what about `length`? That's not yet defined! In fact, that's the very formula we're trying here to specify.
111
112 What we really want to do is something like this:
113
114     \xs. (empty? xs) 0 (succ (... (tail xs)))
115
116 where this very same formula occupies the `...` position:
117
118     \xs. (empty? xs) 0 (succ (\xs. (empty? xs) 0 (succ (... (tail xs)))
119                                    (tail xs)))
120
121 but as you can see, we'd still have to plug the formula back into itself again, and again, and again... No dice.
122
123 So how could we do it? And how do OCaml and Scheme manage to do it, with their `let rec` and `letrec`?
124
125 1.  OCaml and Scheme do it using a trick. Well, not a trick. Actually an impressive, conceptually deep technique, which we haven't yet developed. Since we want to build up all the techniques we're using by hand, then, we shouldn't permit ourselves to rely on `let rec` or `letrec` until we thoroughly understand what's going on under the hood.
126
127 2.  If you tried this in Scheme:
128
129         (define length (lambda (xs)
130                          (if (null? xs) 0
131                                         (+ 1 (length (cdr xs))) )))
132         
133         (length (list 20 30))
134
135     You'd find that it works! This is because `define` in Scheme is really shorthand for `letrec`, not for plain `let` or `let*`. So we should regard this as cheating, too.
136
137 3.  In fact, it *is* possible to define the `length` function in the Lambda Calculus despite these obstacles, without yet knowing how to implement `letrec` in general. We've already seen how to do it, using our right-fold (or left-fold) encoding for lists, and exploiting their internal structure. Those encodings take a function and a seed value and returns the result of folding that function over the list, with that seed value. So we could use this as a definition of `length`:
138
139         \xs. xs (\x sofar. succ sofar) 0
140
141     What's happening here? We start with the value `0`, then we apply the function `\x sofar. succ sofar` to the two arguments <code>x<sub>n</sub></code> and `0`, where <code>x<sub>n</sub></code> is the last element of the list. This gives us `succ 0`, or `1`. That's the value we've accumulated "so far." Then we go apply the function `\x sofar. succ sofar` to the two arguments <code>x<sub>n-1</sub></code> and the value `1` that we've accumulated "so far." This gives us `two`. We continue until we get to the start of the list. The value we've then built up "so far" will be the length of the list.
142
143 We can use similar techniques to define many recursive operations on
144 lists and numbers. The reason we can do this is that our
145 fold-based encoding of lists, and Church's encodings of
146 numbers, have a internal structure that *mirrors* the common recursive
147 operations we'd use lists and numbers for.  In a sense, the recursive
148 structure of the `length` operation is built into the data
149 structure we are using to represent the list.  The non-recursive
150 definition of length, above, exploits this embedding of the recursion into
151 the data type.
152
153 This is one of the themes of the course: using data structures to
154 encode the state of some recursive operation.  See our discussions later this semester of the
155 [[zipper]] technique, and [[defunctionalization]].
156
157 As we've seen, it does take some ingenuity to define functions like `tail` or `pred` for these encodings. However it can be done. (And it's not *that* difficult.) Given those functions, we can go on to define other functions like numeric equality, subtraction, and so on, just by exploiting the structure already present in our encodings of lists and numbers.
158
159 With sufficient ingenuity, a great many functions can be defined in the same way. For example, the factorial function is straightforward. The function which returns the nth term in the Fibonacci series is a bit more difficult, but also achievable.
160
161 ##Some functions require full-fledged recursive definitions##
162
163 However, some computable functions are just not definable in this
164 way. We can't, for example, define a function that tells us, for
165 whatever function `f` we supply it, what is the smallest natural number `x`
166 where `f x` is `true` (even if `f` itself is a function we do already know how to define).
167
168 Neither do the resources we've so far developed suffice to define the
169 [[!wikipedia Ackermann function]]. In OCaml:
170
171     let rec A = fun (m,n) ->
172       if      m = 0 then n + 1
173       else if n = 0 then A(m-1,1)
174       else               A(m-1, A(m,n-1));;
175
176     A(0,y) = y+1
177     A(1,y) = 2+(y+3) - 3
178     A(2,y) = 2(y+3) - 3
179     A(3,y) = 2^(y+3) - 3
180     A(4,y) = 2^(2^(2^...2)) (* where there are y+3 2s *) - 3
181     ...
182
183 Many simpler functions always *could* be defined using the resources we've so far developed, although those definitions won't always be very efficient or easily intelligible.
184
185 But functions like the Ackermann function require us to develop a more general technique for doing recursion---and having developed it, it will often be easier to use it even in the cases where, in principle, we didn't have to.
186
187 ##Using fixed-point combinators to define recursive functions##
188
189 ###Fixed points###
190
191 In mathematics, a **fixed point** of a function `f` is any value `ξ`
192 such that `f ξ` is equivalent to `ξ`. For example,
193 consider the squaring function `square` that maps natural numbers to their squares.
194 `square 2 = 4`, so `2` is not a fixed point.  But `square 1 = 1`, so `1` is a
195 fixed point of the squaring function. (Can you think of another?)
196
197 There are many beautiful theorems guaranteeing the existence of a
198 fixed point for various classes of interesting functions.  For
199 instance, imagine that you are looking at a map of Manhattan, and you
200 are standing somewhere in Manhattan.  Then the [[!wikipedia Brouwer
201 fixed-point theorem]] guarantees that there is a spot on the map that is
202 directly above the corresponding spot in Manhattan.  It's the spot
203 where the blue you-are-here dot should be.
204
205 Whether a function has a fixed point depends on the domain of arguments
206 it is defined for.  For instance, consider the successor function `succ`
207 that maps each natural number to its successor.  If we limit our
208 attention to the natural numbers, then this function has no fixed
209 point.  (See the discussion below concerning a way of understanding
210 the successor function on which it *does* have a fixed point.)
211
212 In the Lambda Calculus, we say a fixed point of a term `f` is any term `ξ` such that:
213
214     ξ <~~> f ξ
215
216 This is a bit different than the general mathematical definition, in that here we're saying it is *terms* that are fixed points, not *values*. We like to think that some lambda terms represent values, such as our term `\f z. z` representing the numerical value zero (and also the truth-value false, and also the empty list... on the other hand, we never did explicitly agree that those three values are all the same thing, did we?). But some terms in the Lambda Calculus don't even have a normal form. We don't want to count them as values. But the way we're proposing to use the notion of a fixed point here, they too are allowed to be fixed points, and to have fixed points of their own.
217
218 Note that `M <~~> N` doesn't entail that `M` and `N` have a normal form (though if they do, they will have the same normal form). It just requires that there be some term that they both reduce to. It may be that that term itself never stops being reducible.
219
220 You should be able to immediately provide a fixed point of the
221 identity combinator `I`.  In fact, you should be able to provide a
222 whole bunch of distinct fixed points.
223
224 With a little thought, you should be able to provide a fixed point of
225 the false combinator, `KI`.  Here's how to find it: recall that `KI`
226 throws away its first argument, and always returns `I`.  Therefore, if
227 we give it `I` as an argument, it will throw away the argument, and
228 return `I`.  So `KII` ~~> `I`, which is all it takes for `I` to qualify as a
229 fixed point of `KI`.
230
231 What about `K`?  Does it have a fixed point?  You might not think so,
232 after trying on paper for a while.
233
234 However, it's a theorem of the Lambda Calculus that *every* lambda term has
235 a fixed point. Even bare variables like `x`! In fact, they will have infinitely many, non-equivalent
236 fixed points. And we don't just know that they exist: for any given
237 formula, we can explicit define many of them.
238
239 As we've mentioned, even the formula that you're using the define
240 the successor function will have a fixed point. Isn't that weird? There's some `ξ` such that it is equivalent to `succ ξ`?
241 Think about how it might be true.  We'll return to this point below.
242
243
244 ###How fixed points help define recursive functions###
245
246 Recall our initial, abortive attempt above to define the `length` function in the Lambda Calculus. We said "What we really want to do is something like this:
247
248     \xs. if empty? xs then 0 else succ (... (tail xs))
249
250 where this very same formula occupies the `...` position."
251
252 Imagine replacing the `...` with some expression `LENGTH` that computes the
253 length function. Then we have
254
255     \xs. if empty? xs then 0 else succ (LENGTH (tail xs))
256
257 At this point, we have a definition of the length function, though
258 it's not complete, since we don't know what value to use for the
259 symbol `LENGTH`.  Technically, it has the status of an unbound
260 variable.
261
262 Imagine now binding the mysterious variable, and calling the resulting
263 function `h`:
264
265     h ≡ \length \xs. if empty? xs then 0 else succ (length (tail xs))
266
267 Now we have no unbound variables, and we have complete non-recursive
268 definitions of each of the other symbols.
269
270 So `h` takes an argument, and returns a function that accurately
271 computes the length of a list---as long as the argument we supply is
272 already the length function we are trying to define.  (Dehydrated
273 water: to reconstitute, just add water!)
274
275 Here is where the discussion of fixed points becomes relevant.  Saying
276 that `h` is looking for an argument (call it `LENGTH`) that has the same
277 behavior as the result of applying `h` to `LENGTH` is just another way of
278 saying that we are looking for a fixed point for `h`.
279
280     h LENGTH <~~> LENGTH
281
282 Replacing `h` with its definition, we have
283
284     (\xs. if empty? xs then 0 else succ (LENGTH (tail xs))) <~~> LENGTH
285
286 If we can find a value for `LENGTH` that satisfies this constraint, we'll
287 have a function we can use to compute the length of an arbitrary list.
288 All we have to do is find a fixed point for `h`.
289
290 The strategy we will present will turn out to be a general way of
291 finding a fixed point for any lambda term.
292
293
294 ##Deriving Y, a fixed point combinator##
295
296 How shall we begin?  Well, we need to find an argument to supply to
297 `h`.  The argument has to be a function that computes the length of a
298 list.  The function `h` is *almost* a function that computes the
299 length of a list.  Let's try applying `h` to itself.  It won't quite
300 work, but examining the way in which it fails will lead to a solution.
301
302     h h <~~> \xs. if empty? xs then 0 else 1 + h (tail xs)
303
304 The problem is that in the subexpression `h (tail list)`, we've
305 applied `h` to a list, but `h` expects as its first argument the
306 length function.
307
308 So let's adjust h, calling the adjusted function H:
309
310     H = \h \xs. if empty? xs then 0 else 1 + ((h h) (tail xs))
311
312 This is the key creative step.  Instead of applying `h` to a list, we
313 apply it first to itself.  After applying `h` to an argument, it's
314 ready to apply to a list, so we've solved the problem just noted.
315 We're not done yet, of course; we don't yet know what argument to give
316 to `H` that will behave in the desired way.
317
318 So let's reason about `H`.  What exactly is H expecting as its first
319 argument?  Based on the excerpt `(h h) (tail l)`, it appears that
320 `H`'s argument, `h`, should be a function that is ready to take itself
321 as an argument, and that returns a function that takes a list as an
322 argument.  `H` itself fits the bill:
323
324     H H <~~> (\h \xs. if empty? xs then 0 else 1 + ((h h) (tail xs))) H
325         <~~> \xs. if empty? xs then 0 else 1 + ((H H) (tail xs))
326         ≡ \xs. if empty? xs then 0 else 1 + ((\xs. if empty? xs then 0 else 1 + ((H H) (tail xs))) (tail xs))
327         <~~> \xs. if empty? xs then 0
328                     else 1 + (if empty? (tail xs) then 0 else 1 + ((H H) (tail (tail xs))))
329
330 We're in business!
331
332 How does the recursion work?
333 We've defined `H` in such a way that `H H` turns out to be the length function.
334 In order to evaluate `H H`, we substitute `H` into the body of the
335 lambda term.  Inside the lambda term, once the substitution has
336 occurred, we are once again faced with evaluating `H H`.  And so on.
337
338 We've got the potentially infinite regress we desired, defined in terms of a
339 finite lambda term with no undefined symbols.
340
341 Since `H H` turns out to be the length function, we can think of `H`
342 by itself as half of the length function (which is why we called it
343 `H`, of course).  Can you think up a recursion strategy that involves
344 "dividing" the recursive function into equal thirds `T`, such that the
345 length function <~~> T T T?
346
347 We've starting with a particular recursive definition, and arrived at
348 a fixed point for that definition.
349 What's the general recipe?
350
351 1.   Start with any recursive definition `h` that takes itself as an arg: `h ≡ \fn ... fn ...`
352 2.   Next, define `H ≡ \f . h (f f)` 
353 3.   Then compute `H H ≡ ((\f . h (f f)) (\f . h (f f)))`
354 4.   That's the fixed point, the recursive function we're trying to define
355
356 So here is a general method for taking an arbitrary h-style recursive function
357 and returning a fixed point for that function:
358
359      Y ≡ \h. ((\f.h(ff))(\f.h(ff)))
360
361 Test:
362
363     Yh ≡ ((\f.h(ff))(\f.h(ff)))
364        <~~> h((\f.h(ff))(\f.h(ff)))
365        ≡ h(Yh)
366
367 That is, Yh is a fixed point for h.
368
369 Works!
370
371 Let's do one more example to illustrate.  We'll do `K`, since we
372 wondered above whether it had a fixed point.
373
374 Before we begin, we can reason a bit about what the fixed point must
375 be like.  We're looking for a fixed point for `K`, i.e., `\xy.x`.  `K`
376 ignores its second argument.  That means that no matter what we give
377 `K` as its first argument, the result will ignore the next argument
378 (that is, `KX` ignores its first argument, no matter what `X` is).  So
379 if `KX <~~> X`, `X` had also better ignore its first argument.  But we
380 also have `KX ≡ (\xy.x)X ~~> \y.X`.  This means that if `X` ignores
381 its first argument, then `\y.X` will ignore its first two arguments.
382 So once again, if `KX <~~> X`, `X` also had better ignore at least its
383 first two arguments.  Repeating this reasoning, we realize that `X`
384 must be a function that ignores an infinite series of arguments.  
385 Our expectation, then, is that our recipe for finding fixed points
386 will build us a function that somehow manages to ignore an infinite
387 series of arguments.
388
389     h ≡ \xy.x
390     H ≡ \f.h(ff) ≡ \f.(\xy.x)(ff) ~~> \fy.ff
391     H H ≡ (\fy.ff)(\fy.ff) ~~> \y.(\fy.ff)(\fy.ff)
392
393 Let's check that it is in fact a fixed point:
394
395     K(H H) ≡ (\xy.x)((\fy.ff)(\fy.ff)
396            ~~> \y.(\fy.ff)(\fy.ff)
397
398 Yep, `H H` and `K(H H)` both reduce to the same term.  
399
400 To see what this fixed point does, let's reduce it a bit more:
401
402     H H ≡ (\fy.ff)(\fy.ff)
403         ~~> \y.(\fy.ff)(\fy.ff)
404         ~~> \yy.(\fy.ff)(\fy.ff)
405         ~~> \yyy.(\fy.ff)(\fy.ff)
406     
407 Sure enough, this fixed point ignores an endless, infinite series of
408 arguments.  It's a write-only memory, a black hole.
409
410 Now that we have one fixed point, we can find others, for instance,
411
412     (\fy.fff)(\fy.fff) 
413     ~~> \y.(\fy.fff)(\fy.fff)(\fy.fff)
414     ~~> \yy.(\fy.fff)(\fy.fff)(\fy.fff)(\fy.fff)
415     ~~> \yyy.(\fy.fff)(\fy.fff)(\fy.fff)(\fy.fff)(\fy.fff)
416
417 Continuing in this way, you can now find an infinite number of fixed
418 points, all of which have the crucial property of ignoring an infinite
419 series of arguments.
420
421 ##What is a fixed point for the successor function?##
422
423 As we've seen, the recipe just given for finding a fixed point worked
424 great for our `h`, which we wrote as a definition for the length
425 function.  But the recipe doesn't make any assumptions about the
426 internal structure of the function it works with.  That means it can
427 find a fixed point for literally any function whatsoever.
428
429 In particular, what could the fixed point for the
430 successor function possibly be like?
431
432 Well, you might think, only some of the formulas that we might give to the `succ` as arguments would really represent numbers. If we said something like:
433
434     succ pair
435
436 who knows what we'd get back? Perhaps there's some non-number-representing formula such that when we feed it to `succ` as an argument, we get the same formula back.
437
438 Yes! That's exactly right. And which formula this is will depend on the particular way you've implemented the succ function.
439
440 One (by now obvious) upshot is that the recipes that enable us to name
441 fixed points for any given formula aren't *guaranteed* to give us
442 *terminating* fixed points. They might give us formulas X such that
443 neither `X` nor `f X` have normal forms. (Indeed, what they give us
444 for the square function isn't any of the Church numerals, but is
445 rather an expression with no normal form.) However, if we take care we
446 can ensure that we *do* get terminating fixed points. And this gives
447 us a principled, fully general strategy for doing recursion. It lets
448 us define even functions like the Ackermann function, which were until
449 now out of our reach. It would also let us define arithmetic and list
450 functions on the "version 1" and "version 2" encodings, where it
451 wasn't always clear how to force the computation to "keep going."
452
453 ###Varieties of fixed-point combinators###
454
455 OK, so how do we make use of this?
456
457 Many fixed-point combinators have been discovered. (And some
458 fixed-point combinators give us models for building infinitely many
459 more, non-equivalent fixed-point combinators.)
460
461 Two of the simplest:
462
463     Θ′ ≡ (\u f. f (\n. u u f n)) (\u f. f (\n. u u f n))
464     Y′ ≡ \f. (\u. f (\n. u u n)) (\u. f (\n. u u n))
465
466 Applying either of these to a term `f` gives a fixed point `ξ` for `f`, meaning that `f ξ` <~~> `ξ`. `Θ′` has the advantage that `f (Θ′ f)` really *reduces to* `Θ′ f`. Whereas `f (Y′ f)` is only *convertible with* `Y′ f`; that is, there's a common formula they both reduce to. For most purposes, though, either will do.
467
468 You may notice that both of these formulas have eta-redexes inside them: why can't we simplify the two `\n. u u f n` inside `Θ′` to just `u u f`? And similarly for `Y′`?
469
470 Indeed you can, getting the simpler:
471
472     Θ ≡ (\u f. f (u u f)) (\u f. f (u u f))
473     Y ≡ \f. (\u. f (u u)) (\u. f (u u))
474
475 I stated the more complex formulas for the following reason: in a language whose evaluation order is *call-by-value*, the evaluation of `Θ (\self. BODY)` and `Y (\self. BODY)` will in general not terminate. But evaluation of the eta-unreduced primed versions will.
476
477 Of course, if you define your `\self. BODY` stupidly, your formula will never terminate. For example, it doesn't matter what fixed point combinator you use for `Ψ` in:
478
479     Ψ (\self. \n. self n)
480
481 When you try to evaluate the application of that to some argument `M`, it's going to try to give you back:
482
483     (\n. self n) M
484
485 where `self` is equivalent to the very formula `\n. self n` that contains it. So the evaluation will proceed:
486
487     (\n. self n) M ~~>
488     self M <~~>
489     (\n. self n) M ~~>
490     self M <~~>
491     ...
492
493 You've written an infinite loop!
494
495 However, when we evaluate the application of our:
496
497     Ψ (\self (\xs. (empty? xs) 0 (succ (self (tail xs))) ))
498
499 to some list `L`, we're not going to go into an infinite evaluation loop of that sort. At each cycle, we're going to be evaluating the application of:
500
501     \xs. (empty? xs) 0 (succ (self (tail xs)))
502
503 to *the tail* of the list we were evaluating its application to at the previous stage. Assuming our lists are finite (and the encodings we're using don't permit otherwise), at some point one will get a list whose tail is empty, and then the evaluation of that formula to that tail will return `0`. So the recursion eventually bottoms out in a base value.
504
505 ##Fixed-point Combinators Are a Bit Intoxicating##
506
507 ![tatoo](/y-combinator-fixed.jpg)
508
509 There's a tendency for people to say "Y-combinator" to refer to fixed-point combinators generally. We'll probably fall into that usage ourselves. Speaking correctly, though, the Y-combinator is only one of many fixed-point combinators.
510
511 I used `Ψ` above to stand in for an arbitrary fixed-point combinator. I don't know of any broad conventions for this. But this seems a useful one.
512
513 As we said, there are many other fixed-point combinators as well. For example, Jan Willem Klop pointed out that if we define `L` to be:
514
515     \a b c d e f g h i j k l m n o p q s t u v w x y z r. (r (t h i s i s a f i x e d p o i n t c o m b i n a t o r))
516
517 then this is a fixed-point combinator:
518
519     L L L L L L L L L L L L L L L L L L L L L L L L L L
520
521
522 ##Watching Y in action##
523
524 For those of you who like to watch ultra slow-mo movies of bullets
525 piercing apples, here's a stepwise computation of the application of a
526 recursive function.  We'll use a function `sink`, which takes one
527 argument.  If the argument is boolean true (i.e., `\x y.x`), it
528 returns itself (a copy of `sink`); if the argument is boolean false
529 (`\x y. y`), it returns `I`.  That is, we want the following behavior:
530
531     sink false ~~> I
532     sink true false ~~> I
533     sink true true false ~~> I
534     sink true true true false ~~> I
535
536 So we make `sink = Y (\f b. b f I)`:
537
538     1. sink false
539     2. Y (\fb.bfI) false
540     3. (\f. (\h. f (h h)) (\h. f (h h))) (\fb.bfI) false
541     4. (\h. [\fb.bfI] (h h)) (\h. [\fb.bfI] (h h)) false
542     5. [\fb.bfI] ((\h. [\fb.bsI] (h h))(\h. [\fb.bsI] (h h))) false
543     6. (\b.b[(\h. [\fb.bsI] (h h))(\h. [\fb.bsI] (h h))]I)  false
544     7. false [(\h. [\fb.bsI] (h h))(\h. [\fb.bsI] (h h))] I
545              --------------------------------------------
546     8. I
547
548 So far so good.  The crucial thing to note is that as long as we
549 always reduce the outermost redex first, we never have to get around
550 to computing the underlined redex: because `false` ignores its first
551 argument, we can throw it away unreduced.
552
553 Now we try the next most complex example:
554
555     1. sink true false
556     2. Y (\fb.bfI) true false
557     3. (\f. (\h. f (h h)) (\h. f (h h))) (\fb.bfI) true false
558     4. (\h. [\fb.bfI] (h h)) (\h. [\fb.bfI] (h h)) true false
559     5. [\fb.bfI] ((\h. [\fb.bsI] (h h))(\h. [\fb.bsI] (h h))) true false
560     6. (\b.b[(\h. [\fb.bsI] (h h))(\h. [\fb.bsI] (h h))]I)  true false
561     7. true [(\h. [\fb.bsI] (h h))(\h. [\fb.bsI] (h h))] I false
562     8. [(\h. [\fb.bsI] (h h))(\h. [\fb.bsI] (h h))] false
563
564 We've now arrived at line (4) of the first computation, so the result
565 is again I.
566
567 You should be able to see that `sink` will consume as many `true`s as
568 we throw at it, then turn into the identity function after it
569 encounters the first `false`.
570
571 The key to the recursion is that, thanks to `Y`, the definition of
572 `sink` contains within it the ability to fully regenerate itself as
573 many times as is necessary.  The key to *ending* the recursion is that
574 the behavior of `sink` is sensitive to the nature of the input: if the
575 input is the magic function `false`, the self-regeneration machinery
576 will be discarded, and the recursion will stop.
577
578 That's about as simple as recursion gets.
579
580 ##Application to the truth teller/liar paradoxes##
581
582 ###Base cases, and their lack###
583
584 As any functional programmer quickly learns, writing a recursive
585 function divides into two tasks: figuring out how to handle the
586 recursive case, and remembering to insert a base case.  The
587 interesting and enjoyable part is figuring out the recursive pattern,
588 but the base case cannot be ignored, since leaving out the base case
589 creates a program that runs forever.  For instance, consider computing
590 a factorial: `n!` is `n * (n-1) * (n-2) * ... * 1`.  The recursive
591 case says that the factorial of a number `n` is `n` times the
592 factorial of `n-1`.  But if we leave out the base case, we get
593
594     3! = 3 * 2! = 3 * 2 * 1! = 3 * 2 * 1 * 0! = 3 * 2 * 1 * 0 * -1! ...
595
596 That's why it's crucial to declare that `0!` = `1`, in which case the
597 recursive rule does not apply.  In our terms,
598
599     fact = Y (\fact n. zero? n 1 (fact (predecessor n)))
600
601 If `n` is `0`, `fact` reduces to `1`, without computing the recursive case.
602
603 Curry originally called `Y` the "paradoxical" combinator, and discussed
604 it in connection with certain well-known paradoxes from the philosophy
605 literature.  The truth-teller paradox has the flavor of a recursive
606 function without a base case:
607
608 (1)    This sentence is true.
609
610 If we assume that the complex demonstrative "this sentence" can refer
611 to (1), then the proposition expressed by (1) will be true just in
612 case the thing referred to by *this sentence* is true.  Thus (1) will
613 be true just in case (1) is true, and (1) is true just in case (1) is
614 true, and so on.  If (1) is true, then (1) is true; but if (1) is not
615 true, then (1) is not true.
616
617 Without pretending to give a serious analysis of the paradox, let's
618 assume that sentences can have for their meaning boolean functions
619 like the ones we have been working with here.  Then the sentence *John
620 is John* might denote the function `\x y. x`, our `true`.
621
622 <!-- Jim says: I haven't yet followed the next chunk to my satisfaction -->
623
624 Then (1) denotes a function from whatever the referent of *this
625 sentence* is to a boolean.  So (1) denotes `\f. f true false`, where
626 the argument `f` is the referent of *this sentence*.  Of course, if
627 `f` is a boolean, `f true false <~~> f`, so for our purposes, we can
628 assume that (1) denotes the identity function `I`.
629
630 If we use (1) in a context in which *this sentence* refers to the
631 sentence in which the demonstrative occurs, then we must find a
632 meaning `m` such that `I m = I`.  But since in this context `m` is the
633 same as the meaning `I`, so we have `m = I m`.  In other words, `m` is
634 a fixed point for the denotation of the sentence (when used in the
635 appropriate context).
636
637 That means that in a context in which *this sentence* refers to the
638 sentence in which it occurs, the sentence denotes a fixed point for
639 the identity function.  Here's a fixed point for the identity
640 function:
641
642     Y I ≡
643     (\f. (\h. f (h h)) (\h. f (h h))) I ~~>
644     (\h. I (h h)) (\h. I (h h))) ~~>
645     (\h. (h h)) (\h. (h h))) ≡
646     ω ω
647     Ω
648
649 Oh.  Well!  That feels right.  The meaning of *This sentence is true*
650 in a context in which *this sentence* refers to the sentence in which
651 it occurs is `Ω`, our prototypical infinite loop...
652
653 What about the liar paradox?
654
655 (2)  This sentence is false.
656
657 Used in a context in which *this sentence* refers to the utterance of
658 (2) in which it occurs, (2) will denote a fixed point for `\f.neg f`,
659 or `\f l r. f r l`, which is the `C` combinator.  So in such a
660 context, (2) might denote
661
662      Y C
663      (\f. (\h. f (h h)) (\h. f (h h))) I
664      (\h. C (h h)) (\h. C (h h)))
665      C ((\h. C (h h)) (\h. C (h h)))
666      C (C ((\h. C (h h))(\h. C (h h))))
667      C (C (C ((\h. C (h h))(\h. C (h h)))))
668      ...
669
670 And infinite sequence of `C`s, each one negating the remainder of the
671 sequence.  Yep, that feels like a reasonable representation of the
672 liar paradox.
673
674 See Barwise and Etchemendy's 1987 OUP book, [The Liar: an essay on
675 truth and circularity](http://tinyurl.com/2db62bk) for an approach
676 that is similar, but expressed in terms of non-well-founded sets
677 rather than recursive functions.
678
679 ##However...##
680
681 You should be cautious about feeling too comfortable with
682 these results.  Thinking again of the truth-teller paradox, yes,
683 `Ω` is *a* fixed point for `I`, and perhaps it has
684 some privileged status among all the fixed points for `I`, being the
685 one delivered by `Y` and all (though it is not obvious why `Y` should have
686 any special status, versus other fixed point combinators).
687
688 But one could ask: look, literally every formula is a fixed point for
689 `I`, since
690
691     X <~~> I X
692
693 for any choice of `X` whatsoever.
694
695 So the `Y` combinator is only guaranteed to give us one fixed point out
696 of infinitely many---and not always the intuitively most useful
697 one. (For instance, the squaring function has `0` as a fixed point,
698 since `0 * 0 = 0`, and `1` as a fixed point, since `1 * 1 = 1`, but `Y
699 (\x. mul x x)` doesn't give us `0` or `1`.) So with respect to the
700 truth-teller paradox, why in the reasoning we've
701 just gone through should we be reaching for just this fixed point at
702 just this juncture?
703
704 One obstacle to thinking this through is the fact that a sentence
705 normally has only two truth values.  We might consider instead a noun
706 phrase such as
707
708 (3)  the entity that this noun phrase refers to
709
710 The reference of (3) depends on the reference of the embedded noun
711 phrase *this noun phrase*.  It's easy to see that any object is a
712 fixed point for this referential function: if this pen cap is the
713 referent of *this noun phrase*, then it is the referent of (3), and so
714 for any object.
715
716 The chameleon nature of (3), by the way (a description that is equally
717 good at describing any object), makes it particularly well suited as a
718 gloss on pronouns such as *it*.  In the system of
719 [Jacobson 1999](http://www.springerlink.com/content/j706674r4w217jj5/),
720 pronouns denote (you guessed it!) identity functions...
721
722 Ultimately, in the context of this course, these paradoxes are more
723 useful as a way of gaining leverage on the concepts of fixed points
724 and recursion, rather than the other way around.