d393be1d1c7fc4e683d04b7bd577e658cbfcbd2f
[lambda.git] / topics / _week2_lambda_calculus_intro.mdwn
1 Basics of Lambda Calculus
2 =========================
3
4 We often talk about "*the* Lambda Calculus", as if there were just
5 one; but in fact, there are many, many variations.  The one we will
6 start with, and that we will explore in some detail, is the "pure"
7 Lambda Calculus.  And actually, there are many variations even in the
8 pure Lambda Calculus.  But all of the variations share a strong family
9 resemblance, so what we learn now will apply to all of them.
10
11 The lambda calculus we'll be focusing on for the first part of the
12 course has no types. Some prefer to say it does have types, it's just
13 that there's only one type, so that every expression is a member of
14 that one type.  If you say that, you have to say that functions from
15 this type to this type also belong to this type. Which is weird... In
16 fact, though, such types are studied, under the name "recursive
17 types." More about these later in the seminar.
18
19 Here is its syntax:
20
21 <blockquote>
22 <strong>Variables</strong>: <code>x</code>, <code>y</code>, <code>z</code>...
23 </blockquote>
24
25 Each variable is an expression. For any expressions M and N and variable a, the following are also expressions:
26
27 <blockquote>
28 <strong>Abstract</strong>: <code>(&lambda;a M)</code>
29 </blockquote>
30
31 We'll tend to write <code>(&lambda;a M)</code> as just `(\a M)`, so we
32 don't have to write out the markup code for the
33 <code>&lambda;</code>. You can yourself write <code>(&lambda;a
34 M)</code> or `(\a M)` or `(lambda a M)`.
35
36 <blockquote>
37 <strong>Application</strong>: <code>(M N)</code>
38 </blockquote>
39
40 Expressions in the lambda calculus are called "terms".  Here is the
41 syntax of the lambda calculus given in the form of a context-free
42 grammar:
43
44     T --> ( T T )
45     T --> ( lambda Var T)
46     Var --> x
47     Var --> y
48     Var --> z
49     ...
50
51 Very, very simple.
52
53 Examples of terms:
54
55         x
56         (y x)
57         (x x)
58         (\x y)
59         (\x x)
60         (\x (\y x))
61         (x (\x x))
62         ((\x (x x)) (\x (x x)))
63
64 The lambda calculus has an associated proof theory. For now, we can regard the
65 proof theory as having just one rule, called the rule of **beta-reduction** or
66 "beta-contraction". Suppose you have some expression of the form:
67
68         ((\a M) N)
69
70 This is an application whose first element is an abstract.  This
71 compound form is called a **redex**, meaning it's a "beta-reducible
72 expression." `(\a M)` is called the **head** of the redex; `N` is
73 called the **argument**, and `M` is called the **body**.
74
75 The rule of beta-reduction permits a transition from that expression to the following:
76
77         M [a <-- N]
78
79 What this means is just `M`, with any *free occurrences* inside `M` of
80 the variable `a` replaced with the term `N`.
81
82 What is a free occurrence?
83
84 >       An occurrence of a variable `a` is **bound** in T if T has the form `(\a N)`.
85
86 >       If T has the form `(M N)`, any occurrences of `a` that are bound in `M` are also bound in T, and so too any occurrences of `a` that are bound in `N`.
87
88 >       An occurrence of a variable is **free** if it's not bound.
89
90 For instance:
91
92 >       T is defined to be `(x (\x (\y (x (y z)))))`
93
94 The first occurrence of `x` in T is free.  The `\x` we won't regard as
95 containing an occurrence of `x`. The next occurrence of `x` occurs
96 within a form that begins with `\x`, so it is bound as well. The
97 occurrence of `y` is bound; and the occurrence of `z` is free.
98
99 Note that the definition of *bound* is carefully crafted to guarantee
100 that in an expression like `(\a (x a))`, both occurrences of `a` count
101 as bound.
102
103 To read further:
104
105 *       [[!wikipedia Free variables and bound variables]]
106
107 Here's an example of beta-reduction:
108
109         ((\x (y x)) z)
110
111 beta-reduces to:
112
113         (y z)
114
115 We'll write that like this:
116
117         ((\x (y x)) z) ~~> (y z)
118
119 Different authors use different notations. Some authors use the term
120 "contraction" for a single reduction step, and reserve the term
121 "reduction" for the reflexive transitive closure of that, that is, for
122 zero or more reduction steps. Informally, it seems easiest to us to
123 say "reduction" for one or more reduction steps. So when we write:
124
125         M ~~> N
126
127 We'll mean that you can get from M to N by one or more reduction
128 steps. 
129
130 There are many more details about the notation and the metatheory of
131 the lambda calculus here:
132
133 *      [[topics/_week2_lambda_calculus_fine_points.mdwn]]
134
135
136 Shorthand
137 ---------
138
139 The grammar we gave for the lambda calculus leads to some
140 verbosity. There are several informal conventions in widespread use,
141 which enable the language to be written more compactly. (If you like,
142 you could instead articulate a formal grammar which incorporates these
143 additional conventions. Instead of showing it to you, we'll leave it
144 as an exercise for those so inclined.)
145
146
147 **Parentheses** Outermost parentheses around applications can be dropped. Moreover, applications will associate to the left, so `M N P` will be understood as `((M N) P)`. Finally, you can drop parentheses around abstracts, but not when they're part of an application. So you can abbreviate:
148
149         (\x (x y))
150
151 as:
152
153         \x (x y)
154
155 but you should include the parentheses in:
156
157         (\x (x y)) z
158
159 and:
160
161         z (\x (x y))
162
163
164 **Dot notation** Dot means "put a left paren here, and put the right
165 paren as far the right as possible without creating unbalanced
166 parentheses". So:
167
168         \x (\y (x y))
169
170 can be abbreviated as:
171
172         \x (\y. x y)
173
174 and that as:
175
176         \x. \y. x y
177
178 This:
179
180         \x. \y. (x y) x
181
182 abbreviates:
183
184         \x (\y ((x y) x))
185
186 This on the other hand:
187
188         (\x. \y. (x y)) x
189
190 abbreviates:
191
192         ((\x (\y (x y))) x)
193
194
195 **Merging lambdas** An expression of the form `(\x (\y M))`, or equivalently, `(\x. \y. M)`, can be abbreviated as:
196
197         (\x y. M)
198
199 Similarly, `(\x (\y (\z M)))` can be abbreviated as:
200
201         (\x y z. M)
202
203
204 Lambda terms represent functions
205 --------------------------------
206
207 Let's pause and consider the following fundamental question: what is a
208 function?  One popular answer is that a function can be represented by
209 a set of ordered pairs.  This set is called the **graph** of the
210 funtion.  If the ordered pair `(a,b)` is a member of the graph if `f`,
211 that means that `f` maps the argument `a` to the value `b`.  In
212 symbols, `f a == b`.  
213
214 There is a requirement that in order to count as a function (rather
215 than as merely a more general relation), the graph cannot contain two
216 (distinct) ordered pairs with the same first element.  That is, in
217 order to count as a proper function, each argument must correspond to
218 a unique result.
219
220 The essential usefullness of the lambda calculus is that it is
221 wonderfully suited to representing functions.  In fact, the untyped
222 lambda calculus is Turing Complete (see [[!wikipedia Turing Completeness]]):
223 all (recursively computable) functions can be represented by lambda
224 terms.  (As we'll see, much of the fun will be in unpacking the word
225 "represented".)
226
227 For some lambda terms, it is easy to see what function they represent:
228
229 >       `(\x x)` represents the identity function: given any argument `M`, this function
230 simply returns `M`: `((\x x) M) ~~> M`.
231
232 >       `(\x (x x))` duplicates its argument:
233 `((\x (x x)) M) ~~> (M M)`
234
235 >       `(\x (\y (y x)))` reorders its two arguments:
236 `(((\x  (\y (y x))) M) N) ~~> (N M)`
237
238 >       `(\x (\y x))` throws away its second argument:
239 `(((\x (\y x)) M) N) ~~> M`
240
241 and so on.  In order to get an intuitive feel for the power of the
242 lambda calculus, note that duplicating, reordering, and deleting
243 elements is all that it takes to simulate the behavior of a general
244 word processing program.  That means that if we had a big enough
245 lambda term, it could take a representation of *Emma* as input and
246 produce *Hamlet* as a result. 
247
248 Some of these functions are so useful that we'll give them special
249 names.  In particular, we'll call the identity function `(\x.x)`
250 **I**, and the function `(\x\y.x)` **K**.
251
252 It is easy to see that distinct lambda expressions can represent the same
253 function, considered as a mapping from input to outputs. Obviously:
254
255         (\x x)
256
257 and:
258
259         (\z z)
260
261 both represent the same function, the identity function. However, we said above that we would be regarding these expressions as synactically equivalent, so they aren't yet really examples of *distinct* lambda expressions representing a single function. However, all three of these are distinct lambda expressions:
262
263         (\y x. y x) (\z z)
264
265         (\x. (\z z) x)
266
267         (\z z)
268
269 yet when applied to any argument M, all of these will always return M. So they have the same extension. It's also true, though you may not yet be in a position to see, that no other function can differentiate between them when they're supplied as an argument to it. However, these expressions are all syntactically distinct.
270
271 The first two expressions are *convertible*: in particular the first
272 reduces to the second via a single instance of beta reduction. So they
273 can be regarded as proof-theoretically equivalent even though they're
274 not syntactically identical. However, the proof theory we've given so
275 far doesn't permit you to reduce the second expression to the
276 third. So these lambda expressions are non-equivalent.
277
278 To use a linguistic analogy, you can think of what we're calling
279 "proof theory" as a kind of syntactic transformation.  That is, the
280 sentences *John saw Mary* and *Mary was seen by John* are not
281 syntactically identical, yet (on some theories) one can be derived
282 from the other.  The key element in the analogy is that this kind of
283 syntactic derivation is supposed to preserve meaning, so that the two
284 sentence mean (roughly) the same thing.
285
286 There's an extension of the proof-theory we've presented so far which
287 does permit this further move. And in that extended proof theory, all
288 computable functions with the same extension do turn out to be
289 equivalent (convertible). However, at that point, we still wouldn't be
290 working with the traditional mathematical notion of a function as a
291 set of ordered pairs. One reason is that the fully general
292 mathematical notion permits many uncomputable functions, but the
293 lambda calculus is capable of expressing only computable functions. A
294 second reason is that the full mathematical notion prohibits
295 functions from applying to themselves, but in the lambda calculus,
296 it is permitted for a function to take itself as an argument (for
297 instance, there is nothing wrong with applying the identity function
298 to itself, thus: `(\x x)(\x x)`.  This is a redex that reduces to the
299 identity function (of course).
300
301
302 The analogy with `let`
303 ----------------------
304
305 In our basic functional programming language, we used `let`
306 expressions to assign values to variables.  For instance, 
307
308     let x match 2
309     in (x, x) 
310
311 evaluates to the ordered pair (2, 2).  It may be helpful to think of
312 a redex in the lambda calculus as a particular sort of `let`
313 construction.
314
315     ((\x M) N) is analogous to
316
317     let x match N 
318     in M
319
320 This analogy should be treated with caution.  For one thing, our
321 `letrec` allowed us to define recursive functions in which the name of
322 the function appeared within the expression `N`; we're not ready to
323 deal with recursive functions in the lambda calculus yet.  For
324 another, we defined `let` in terms of values, and at this point, the
325 lambda calculus doesn't have values, it only has other expressions.
326 So it might be better to translate `((\x M) N)` as `let x be replaced
327 by N in M`, or some such.  Most problematically, in the lambda
328 calculus, an abstract such as `(\x (x x))` is perfectly well-formed
329 and coherent, but it is not possible to write a `let` expression that
330 does not have an argument (here, `N`) explicitly present.
331
332 Nevertheless, the correspondence is close enough that it can spur
333 intuition.
334
335
336 Booleans and pairs
337 ==================
338
339 So if the lambda calculus can represent any computable function, we
340 need to do some work to show how to represent some of the functions
341 we've become acquainted with.  We'll start with the `if ... then
342 ... else...` construction.
343
344     if M then N else L
345
346 For a boolean expression `M`, this complex expression evaluates to `N`
347 if `M` evaluates to `'true`, and to `L` if `M` evaluations to `'false.
348 So in order to simulate and `if` clause in the lambda calculus, we
349 need to settle on a way to represent `'true` and `'false`.
350
351 We could simply add the constants `'true` and `'false` to the
352 language, since it makes sense to add constants to the lambda
353 calculus.  However, that would also require complicating the
354 interpretation of the language; at the very least, we would need more
355 than just beta reduction as our engine of computation.  In the spirit
356 of computational minimalism, let's see how far we can get with the
357 pure lambda calculus, without any special constants.
358
359 So we'll need to get rid of the parts of the `if` statement that are
360 just syntactic window-dressing.  That is, we'll need to get rid of the
361 `if`, the `then`, and the `else`:
362
363     M  N  L
364
365 Recall that our convention is that values associate left to right, so
366 this series of terms is evaluated as
367
368     ((M N) L)
369
370 If this expression is supposed to have the meaning of `if M then N
371 else L`, then we need to find a value for `'true` such that when it is
372 substituted in place of `M`, the expression evaluates to `N`.  The
373 function we're looking for takes two arguments: first `N`, then `L`,
374 throws away `L`, and returns `N`.  
375
376 We've already seen such a function.  We called it **K**: `(\x\y.x)`.
377 Let's test:
378
379     ((K M) L) == (((\x\y.x) M) L) ~~> ((\y.M) L) ~~> M
380
381 Sucess!  In the same spirit, `'false` will be **KI**:
382
383     (((K I) M) L) == ((((\x\y.x)(\x.x)) M) L) 
384                      ~~> (((\y.(\x.x)) M) L)
385                      ~~> ((\x.x) L)
386                      ~~> L
387
388 So have seen our first major representation in the lambda calculus:
389 "true" is represented by **K**, and "false" is represented by **KI**.
390 We'll be building up a lot of representations in the weeks to come,
391 and they will all maintain the discipline that if a expression is
392 meant to be interpreted as a truth value (i.e., as a Boolean), it will
393 evaluate to (an expression that is alpha-beta-eta equivalent to) **K**
394 or **KI**.
395
396 Our definition of these is reviewed in [[Assignment 2|topics/assignment2]].
397
398 It's possible to do the assignment without using a Scheme interpreter, however
399 you should take this opportunity to [get Scheme installed on your
400 computer](/how_to_get_the_programming_languages_running_on_your_computer), and
401 [get started learning Scheme](/learning_scheme). It will help you test out
402 proposed answers to the assignment.
403
404
405 There's also a (slow, bare-bones, but perfectly adequate) version of Scheme available for online use at <http://tryscheme.sourceforge.net/>.
406