3d336f6e796b72ecac7757bd919cdf7341ee2538
[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 alternate between `[ ]`s and `( )`s in the Scheme code just to make it more readable. These have no syntactic difference.
29
30 What is the `let rec` in the OCaml code and the `letrec` in the Scheme code? 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:
31
32         let rec get_length = fun lst ->
33                 if lst == [] then 0 else 1 + get_length (tail lst)
34         in get_length [20; 30]
35         (* this evaluates to 2 *)
36
37 In Scheme:
38
39         (letrec [(get_length 
40                                 (lambda (lst) (if (null? lst) 0 [+ 1 (get_length (cdr lst))] )) )]
41                         (get_length (list 20 30)))
42         ; this evaluates to 2
43         
44 If you instead use an ordinary `let` (or `let*`), here's what would happen, in OCaml:
45
46         let get_length = fun lst ->
47                 if lst == [] then 0 else 1 + get_length (tail lst)
48         in get_length [20; 30]
49         (* fails with error "Unbound value length" *)
50
51 Here's Scheme:
52
53         (let* [(get_length 
54                                 (lambda (lst) (if (null? lst) 0 [+ 1 (get_length (cdr lst))] )) )]
55                         (get_length (list 20 30)))
56         ; fails with error "reference to undefined identifier: get_length"
57
58 Why? Because we said that constructions of this form:
59
60         let get_length = A
61                 in B
62
63 really were just another way of saying:
64
65         (\get_length. B) A
66
67 and so the occurrences of `get_length` in A *aren't bound by the `\get_length` that wraps B*. Those occurrences are free.
68
69 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:
70
71         let get_length = fun lst -> 99
72         in let get_length = fun lst ->
73                         if lst == [] then 0 else 1 + get_length (tail lst)
74         in get_length [20; 30]
75         (* evaluates to 1 + 99 *)
76
77 Here the use of `get_length` in `1 + get_length (tail lst)` can clearly be seen to be bound by the outermost `let`.
78
79 And indeed, if you tried to define `get_length` in the lambda calculus, how would you do it?
80
81         \lst. (isempty lst) zero (add one (get-length (extract-tail lst)))
82
83 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.
84
85 What we really want to do is something like this:
86
87         \lst. (isempty lst) zero (add one (... (extract-tail lst)))
88
89 where this very same formula occupies the `...` position:
90
91         \lst. (isempty lst) zero (add one (
92                 \lst. (isempty lst) zero (add one (... (extract-tail lst)))
93                         (extract-tail lst)))
94
95 but as you can see, we'd still have to plug the formula back into itself again, and again, and again... No dice.
96
97 So how could we do it? And how do OCaml and Scheme manage to do it, with their `let rec` and `letrec`?
98
99 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.
100
101 2.      If you tried this in Scheme:
102
103                 (define get_length 
104                                 (lambda (lst) (if (null? lst) 0 [+ 1 (get_length (cdr lst))] )) )
105                 
106                 (get_length (list 20 30))
107
108         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.
109
110 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`:
111
112                 \lst. lst (\x sofar. successor sofar) zero
113
114         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.
115
116 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.
117
118 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.
119
120 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.
121
122 ##However...##
123
124 Some computable functions are just not definable in this way. The simplest function that *simply cannot* be defined using the resources we've so far developed is the Ackermann function:
125
126         A(m,n) =
127                 | when m == 0 -> n + 1
128                 | else when n == 0 -> A(m-1,1)
129                 | else -> A(m-1, A(m,n-1))
130
131         A(0,y) = y+1
132         A(1,y) = y+2
133         A(2,y) = 2y + 3
134         A(3,y) = 2^(y+3) -3
135         A(4,y) = 2^(2^(2^...2)) [where there are y+3 2s] - 3
136         ...
137
138 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.
139
140 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.
141
142 ##How to do recursion with lower-case omega##
143
144 ...
145
146 ##Generalizing##
147
148 In general, a **fixed point** of a function f is a 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?
149
150 In the lambda calculus, we say a fixed point of an expression `f` is any formula `X` such that:
151
152         X <~~> f X
153
154 What is a fixed point of the identity combinator I?
155
156 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.
157
158 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.
159
160 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:
161
162         successor make-pair
163
164 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.
165
166 Yes! That's exactly right. And which formula this is will depend on the particular way you've implemented the successor function.
167
168 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 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."
169
170 [Explain in terms of an arbitrary fixed point combinator &Psi;.]
171
172 [Give some examples: first, versions of Y and &Theta; usable with call-by-value. Then do the internal eta-reductions and say these work for call-by-name only.]
173
174 [Explain how what we've done relates to the version using lower-case &omega;.]
175
176