c66526d3c61bc9267d5aaba6b569b2c5f89be230
[lambda.git] / week3.mdwn
1 ##Computing the length of a list##
2
3 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:
4
5 >       the empty list has length 0
6
7 >       any non-empty list has length 1 + (the length of its tail)
8
9 In OCaml, you'd define that like this:
10
11         let rec get_length = fun lst ->
12                 if lst == [] then 0 else 1 + get_length (tail lst)
13         in ... (* here you go on to use the function "get_length" *)
14
15 In Scheme you'd define it like this:
16
17         (letrec [(get_length
18                                 (lambda (lst) (if (null? lst) 0 [+ 1 (get_length (cdr lst))] )) )]
19                 ... ; here you go on to use the function "get_length"
20         )
21
22 Some comments on this:
23
24 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)`).
25
26 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.)
27
28 3.      I use `get_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.
29
30 4.      I alternate between `[ ]`s and `( )`s in the Scheme code just to make it more readable. These have no syntactic difference.
31
32
33 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?
34
35 Answer: These work like the `let` expressions we've already seen, except that they let you use the variable `get_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 `get_length`. So our recursively-defined function works the way we'd expect it to. In OCaml:
36
37         let rec get_length = fun lst ->
38                 if lst == [] then 0 else 1 + get_length (tail lst)
39         in get_length [20; 30]
40         (* this evaluates to 2 *)
41
42 In Scheme:
43
44         (letrec [(get_length 
45                                 (lambda (lst) (if (null? lst) 0 [+ 1 (get_length (cdr lst))] )) )]
46                         (get_length (list 20 30)))
47         ; this evaluates to 2
48         
49 If you instead use an ordinary `let` (or `let*`), here's what would happen, in OCaml:
50
51         let get_length = fun lst ->
52                 if lst == [] then 0 else 1 + get_length (tail lst)
53         in get_length [20; 30]
54         (* fails with error "Unbound value length" *)
55
56 Here's Scheme:
57
58         (let* [(get_length 
59                                 (lambda (lst) (if (null? lst) 0 [+ 1 (get_length (cdr lst))] )) )]
60                         (get_length (list 20 30)))
61         ; fails with error "reference to undefined identifier: get_length"
62
63 Why? Because we said that constructions of this form:
64
65         let get_length = A
66                 in B
67
68 really were just another way of saying:
69
70         (\get_length. B) A
71
72 and so the occurrences of `get_length` in A *aren't bound by the `\get_length` that wraps B*. Those occurrences are free.
73
74 We can verify this by wrapping the whole expression in a more outer binding of `get_length` to some other function, say the constant function from any list to the integer 99:
75
76         let get_length = fun lst -> 99
77         in let get_length = fun lst ->
78                         if lst == [] then 0 else 1 + get_length (tail lst)
79         in get_length [20; 30]
80         (* evaluates to 1 + 99 *)
81
82 Here the use of `get_length` in `1 + get_length (tail lst)` can clearly be seen to be bound by the outermost `let`.
83
84 And indeed, if you tried to define `get_length` in the lambda calculus, how would you do it?
85
86         \lst. (isempty lst) zero (add one (get_length (extract-tail lst)))
87
88 We've defined all of `isempty`, `zero`, `add`, `one`, and `extract-tail` in earlier discussion. But what about `get_length`? That's not yet defined! In fact, that's the very formula we're trying here to specify.
89
90 What we really want to do is something like this:
91
92         \lst. (isempty lst) zero (add one (... (extract-tail lst)))
93
94 where this very same formula occupies the `...` position:
95
96         \lst. (isempty lst) zero (add one (
97                 \lst. (isempty lst) zero (add one (... (extract-tail lst)))
98                         (extract-tail lst)))
99
100 but as you can see, we'd still have to plug the formula back into itself again, and again, and again... No dice.
101
102 [At this point, some of you will recall the discussion in the first
103 class concerning the conception of functions as sets of ordered pairs.
104 The problem, as you will recall, was that in the untyped lambda
105 calculus, we wanted a function to be capable of taking itself as an
106 argument.  For instance, we wanted to be able to apply the identity
107 function to itself.  And since the identity function always returns
108 its argument unchanged, the value it should return in that case is
109 itself:
110
111     (\x.x)(\x.x) ~~> (\x.x)
112
113 If we conceive of a function as a set of ordered pairs, we would start
114 off like this:
115
116     1 -> 1
117     2 -> 2
118     3 -> 3
119     ...
120     [1 -> 1, 2 -> 2, 3 -> 3, ..., [1 -> 1, 2 -> 2, 3 -> 3, ..., 
121
122 Eventually, we would get to the point where we want to say what the
123 identity function itself gets mapped to.  But in order to say that, we
124 need to write down the identity function in the argument position as a
125 set of ordered pairs.  The need to insert a copy of the entire
126 function definition inside of a copy of the entire function definition
127 inside of... is the same problem as the need to insert a complete
128 graph of the identity function inside of the graph for the identity function.]
129
130 So how could we do it? And how do OCaml and Scheme manage to do it, with their `let rec` and `letrec`?
131
132 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.
133
134 2.      If you tried this in Scheme:
135
136                 (define get_length 
137                                 (lambda (lst) (if (null? lst) 0 [+ 1 (get_length (cdr lst))] )) )
138                 
139                 (get_length (list 20 30))
140
141         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.
142
143 3.      In fact, it *is* possible to define the `get_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 `get_length`:
144
145                 \lst. lst (\x sofar. successor sofar) zero
146
147         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.
148
149 We can use similar techniques to define many recursive operations on lists and numbers. The reason we can do this is that our "version 3," fold-based implementation of lists, and Church's implementations of numbers, have a internal structure that *mirrors* the common recursive operations we'd use lists and numbers for.
150
151 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.
152
153 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.
154
155 ##However...##
156
157 Some computable functions are just not definable in this way. We can't, for example, define a function that tells us, for whatever function `f` we supply it, what is the smallest integer `x` where `f x` is `true`.
158
159 Neither do the resources we've so far developed suffice to define the 
160 [[!wikipedia Ackermann function]]:
161
162         A(m,n) =
163                 | when m == 0 -> n + 1
164                 | else when n == 0 -> A(m-1,1)
165                 | else -> A(m-1, A(m,n-1))
166
167         A(0,y) = y+1
168         A(1,y) = 2+(y+3) - 3
169         A(2,y) = 2(y+3) - 3
170         A(3,y) = 2^(y+3) - 3
171         A(4,y) = 2^(2^(2^...2)) [where there are y+3 2s] - 3
172         ...
173
174 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.
175
176 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.
177
178 ##How to do recursion with lower-case omega##
179
180 Recall our initial, abortive attempt above to define the `get_length` function in the lambda calculus. We said "What we really want to do is something like this:
181
182         \lst. (isempty lst) zero (add one (... (extract-tail lst)))
183
184 where this very same formula occupies the `...` position."
185
186 We are not going to exactly that, at least not yet. But we are going to do something close to it.
187
188 Consider a formula of the following form (don't worry yet about exactly how we'll fill the `...`s):
189
190         \h \lst. (isempty lst) zero (add one (... (extract-tail lst)))
191
192 Call that formula `H`. Now what would happen if we applied `H` to itself? Then we'd get back:
193
194         \lst. (isempty lst) zero (add one (... (extract-tail lst)))
195
196 where any occurrences of `h` inside the `...` were substituted with `H`. Call this `F`. `F` looks pretty close to what we're after: a function that takes a list and returns zero if it's empty, and so on. And `F` is the result of applying `H` to itself. But now inside `F`, the occurrences of `h` are substituted with the very formula `H` we started with. So if we want to get `F` again, all we have to do is apply `h` to itself---since as we said, the self-application of `H` is how we created `F` in the first place.
197
198 So, the way `F` should be completed is:
199
200         \lst. (isempty lst) zero (add one ((h h) (extract-tail lst)))
201
202 and our original `H` is:
203
204         \h \lst. (isempty lst) zero (add one ((h h) (extract-tail lst)))
205
206 The self-application of `H` will give us `F` with `H` substituted in for its free variable `h`.
207
208 Instead of writing out a long formula twice, we could write:
209
210         (\x. x x) LONG-FORMULA
211
212 and the initial `(\x. x x)` is just what we earlier called the <code>&omega;</code> combinator (lower-case omega, not the non-terminating <code>&Omega;</code>). So the self-application of `H` can be written:
213
214 <pre><code>&omega; (\h \lst. (isempty lst) zero (add one ((h h) (extract-tail lst))))</code></pre>
215
216 and this will indeed implement the recursive function we couldn't earlier figure out how to define.
217
218 In broad brush-strokes, `H` is half of the `get_length` function we're seeking, and `H` has the form:
219
220         \h other-arguments. ... (h h) ...
221
222 We get the whole `get_length` function by applying `H` to itself. Then `h` is replaced by the half `H`, and when we later apply `h` to itself, we re-create the whole `get_length` again.
223
224 ##Neat! Can I make it easier to use?##
225
226 Suppose you wanted to wrap this up in a pretty interface, so that the programmer didn't need to write `(h h)` but could just write `g` for some function `g`. How could you do it?
227
228 Now the `F`-like expression we'd be aiming for---call it `F*`---would look like this:
229
230         \lst. (isempty lst) zero (add one (g (extract-tail lst)))
231
232 or, abbreviating:
233
234         \lst. ...g...
235
236 Here we have just a single `g` instead of `(h h)`. We'd want `F*` to be the result of self-applying some `H*`, and then binding to `g` that very self-application of `H*`. We'd get that if `H*` had the form:
237
238         \h. (\g lst. ...g...) (h h)
239
240 The self-application of `H*` would be:
241
242         (\h. (\g lst. ...g...) (h h)) (\h. (\g lst. ...g...) (h h))
243
244 or:
245
246         (\f. (\h. f (h h)) (\h. f (h h))) (\g lst. ...g...)
247
248 The left-hand side of this is known as **the Y-combinator** and so this could be written more compactly as:
249
250         Y (\g lst. ...g...)
251
252 or, replacing the abbreviated bits:
253
254         Y (\g lst. (isempty lst) zero (add one (g (extract-tail lst))))
255
256 So this is another way to implement the recursive function we couldn't earlier figure out how to define.
257
258
259 ##Generalizing##
260
261 Let's step back and fill in some theory to help us understand why these tricks work.
262
263 In general, we call a **fixed point** of a function f any value *x* such that f <em>x</em> is equivalent to *x*. For example, what is a fixed point of the function from natural numbers to their squares? What is a fixed point of the successor function?
264
265 In the lambda calculus, we say a fixed point of an expression `f` is any formula `X` such that:
266
267         X <~~> f X
268
269 What is a fixed point of the identity combinator I?
270
271 What is a fixed point of the false combinator, KI?
272
273 It's a theorem of the lambda calculus that every formula has a fixed point. In fact, it will have infinitely many, non-equivalent fixed points. And we don't just know that they exist: for any given formula, we can name many of them.
274
275 Yes, even the formula that you're using the define the successor function will have a fixed point. Isn't that weird? Think about how it might be true.
276
277 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:
278
279         successor make-pair
280
281 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.
282
283 Yes! That's exactly right. And which formula this is will depend on the particular way you've implemented the successor function.
284
285 Moreover, the recipes that enable us to name fixed points for any given formula aren't *guaranteed* to give us *terminating* fixed points. They might give us formulas X such that neither `X` nor `f X` have normal forms. (Indeed, what they give us for the square function isn't any of the Church numerals, but is rather an expression with no normal form.) However, if we take care we can ensure that we *do* get terminating fixed points. And this gives us a principled, fully general strategy for doing recursion. It lets us define even functions like the Ackermann function, which were until now out of our reach. It would also let us define arithmetic and list functions on the "version 1" and "version 2" implementations, where it wasn't always clear how to force the computation to "keep going."
286
287 OK, so how do we make use of this?
288
289 Recall again our initial, abortive attempt above to define the `get_length` function in the lambda calculus. We said "What we really want to do is something like this:
290
291         \lst. (isempty lst) zero (add one (... (extract-tail lst)))
292
293 where this very same formula occupies the `...` position."
294
295 If we could somehow get ahold of this very formula, as an additional argument, then we could take the argument and plug it into the `...` position. Something like this:
296
297         \self (\lst. (isempty lst) zero (add one (self (extract-tail lst))) )
298
299 This is an abstract of the form:
300
301         \self. BODY
302
303 where `BODY` is the expression:
304
305         \lst. (isempty lst) zero (add one (self (extract-tail lst)))
306
307 containing an occurrence of `self`.
308
309 Now consider what would be a fixed point of our expression `\self. BODY`? That would be some expression `X` such that:
310
311         X <~~> (\self.BODY) X
312
313 Beta-reducing the right-hand side, we get:
314
315         X <~~> BODY [self := X]
316
317 Think about what this says. It says if you substitute `X` for `self` in our formula BODY:
318
319         \lst. (isempty lst) zero (add one (X (extract-tail lst)))
320
321 what you get is "equivalent" to (that is, convertible with) X itself. That is, the `X` inside the above expression is equivalent to the whole expression. So the expression *does*, in a sense, contain itself!
322
323 Let's go over that again. If we had a fixed point `X` for our expression `\self. ...self...`, then by the definition of a fixed-point, this has to be true:
324
325         X <~~> (\self. ...self...) X
326
327 but beta-reducing the right-hand side, we get something of the form:
328
329         X <~~> ...X...
330
331 So on the right-hand side we have a complex expression, that contains some occurrences of whatever our fixed-point `X` is, and `X` is convertible with *that very complex, right-hand side expression.*
332
333 So we really *can* define `get_length` in the way we were initially attempting, in the bare lambda calculus, where Scheme and OCaml's souped-up `let rec` constructions aren't primitively available. (In fact, what we're doing here is the natural way to implement `let rec`.)
334
335 This all turns on having a way to generate a fixed-point for our "starting formula":
336
337         \self (\lst. (isempty lst) zero (add one (self (extract-tail lst))) )
338
339 Where do we get it?
340
341 Suppose we have some **fixed-point combinator** 
342 <code>&Psi;</code>. That is, some function that returns, for any expression `f` we give it as argument, a fixed point for `f`. In other words:
343
344 <pre><code>&Psi; f <~~> f (&Psi; f)</code></pre>
345
346 Then applying <code>&Psi;</code> to the "starting formula" displayed above would give us our fixed point `X` for the starting formula:
347
348 <pre><code>&Psi; (\self (\lst. (isempty lst) zero (add one (self (extract-tail lst))) ))</code></pre>
349
350 And this is the fully general strategy for 
351 defining recursive functions in the lambda calculus. You begin with a "body formula":
352
353         ...self...
354
355 containing free occurrences of `self` that you treat as being equivalent to the body formula itself. In the case we're considering, that was:
356
357         \lst. (isempty lst) zero (add one (self (extract-tail lst)))
358
359 You bind the free occurrence of `self` as: `\self. BODY`. And then you generate a fixed point for this larger expression:
360
361 <pre><code>&Psi; (\self. BODY)</code></pre>
362
363 using some fixed-point combinator <code>&Psi;</code>.
364
365 Isn't that cool?
366
367 ##Okay, then give me a fixed-point combinator, already!##
368
369 Many fixed-point combinators have been discovered. (And some fixed-point combinators give us models for building infinitely many more, non-equivalent fixed-point combinators.)
370
371 Two of the simplest:
372
373 <pre><code>&Theta;&prime; &equiv; (\u f. f (\n. u u f n)) (\u f. f (\n. u u f n))
374 Y&prime; &equiv; \f. (\u. f (\n. u u n)) (\u. f (\n. u u n))</code></pre>
375
376 <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.
377
378 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>?
379
380 Indeed you can, getting the simpler:
381
382 <pre><code>&Theta; &equiv; (\u f. f (u u f)) (\u f. f (u u f))
383 Y &equiv; \f. (\u. f (u u)) (\u. f (u u))</code></pre>
384
385 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.
386
387 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:
388
389 <pre><code>&Psi; (\self. \n. self n)</code></pre>
390
391 When you try to evaluate the application of that to some argument `M`, it's going to try to give you back:
392
393         (\n. self n) M
394
395 where `self` is equivalent to the very formula `\n. self n` that contains it. So the evaluation will proceed:
396
397         (\n. self n) M ~~>
398         self M ~~>
399         (\n. self n) M ~~>
400         self M ~~>
401         ...
402
403 You've written an infinite loop!
404
405 However, when we evaluate the application of our:
406
407 <pre><code>&Psi; (\self (\lst. (isempty lst) zero (add one (self (extract-tail lst))) ))</code></pre>
408
409 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:
410
411         \lst. (isempty lst) zero (add one (self (extract-tail lst)))
412
413 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.
414
415 ##Fixed-point Combinators Are a Bit Intoxicating##
416
417 ![tatoo](/y-combinator.jpg)
418
419 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.
420
421 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.
422
423 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:
424
425         \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))
426
427 then this is a fixed-point combinator:
428
429         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
430
431
432 ##Watching Y in action##
433
434 For those of you who like to watch ultra slow-mo movies of bullets
435 piercing apples, here's a stepwise computation of the application of a
436 recursive function.  We'll use a function `sink`, which takes one
437 argument.  If the argument is boolean true (i.e., `\x y.x`), it
438 returns itself (a copy of `sink`); if the argument is boolean false,
439 it returns I.  That is, we want the following behavior:
440
441     sink false ~~> I
442     sink true false ~~> I
443     sink true true false ~~> I
444     sink true true true false ~~> I
445
446 So we make sink = Y (\f b. b f I): 
447
448     1. sink false 
449     2. Y (\fb.bfI) false
450     3. (\f. (\h. f (h h)) (\h. f (h h))) (\fb.bfI) false
451     4. (\h. [\fb.bfI] (h h)) (\h. [\fb.bfI] (h h)) false
452     5. [\fb.bfI] ((\h. [\fb.bsI] (h h))(\h. [\fb.bsI] (h h))) false
453     6. (\b.b[(\h. [\fb.bsI] (h h))(\h. [\fb.bsI] (h h))]I)  false
454     7. false [(\h. [\fb.bsI] (h h))(\h. [\fb.bsI] (h h))] I
455              --------------------------------------------
456     8. I
457
458 So far so good.  The crucial thing to note is that as long as we
459 always reduce the outermost redex first, we never have to get around
460 to computing the underlined redex: because `false` ignores its first
461 argument, we can throw it away unreduced.
462
463 Now we try the next most complex example:
464
465     1. sink true false 
466     2. Y (\fb.bfI) true false
467     3. (\f. (\h. f (h h)) (\h. f (h h))) (\fb.bfI) true false
468     4. (\h. [\fb.bfI] (h h)) (\h. [\fb.bfI] (h h)) true false
469     5. [\fb.bfI] ((\h. [\fb.bsI] (h h))(\h. [\fb.bsI] (h h))) true false
470     6. (\b.b[(\h. [\fb.bsI] (h h))(\h. [\fb.bsI] (h h))]I)  true false
471     7. true [(\h. [\fb.bsI] (h h))(\h. [\fb.bsI] (h h))] I false
472     8. [(\h. [\fb.bsI] (h h))(\h. [\fb.bsI] (h h))] false
473
474 We've now arrived at line (4) of the first computation, so the result
475 is again I.
476
477 You should be able to see that `sink` will consume as many `true`s as
478 we throw at it, then turn into the identity function after it
479 encounters the first `false`. 
480
481 The key to the recursion is that, thanks to Y, the definition of
482 `sink` contains within it the ability to fully regenerate itself as
483 many times as is necessary.  The key to *ending* the recursion is that
484 the behavior of `sink` is sensitive to the nature of the input: if the
485 input is the magic function `false`, the self-regeneration machinery
486 will be discarded, and the recursion will stop.
487