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