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