Merge branch 'working'
[lambda.git] / topics / week2_lambda_intro.mdwn
1 # Introduction to the Lambda Calculus #
2
3 We often talk about "*the* Lambda Calculus", as if there were just
4 one; but in fact, there are many, many variations.  The one we will
5 start with, and will explore in some detail, is often called "the pure"
6 or "the untyped" Lambda Calculus. Actually, there are many variations even under that heading. But all of the variations share a strong family
7 resemblance, so what we learn now will apply to all of them.
8
9 > Fussy note: calling this the "pure" Lambda Calculus is entrenched terminology,
10 but it coheres imperfectly with other uses of "pure" we'll encounter. There are
11 three respects in which the lambda calculus we'll be presenting might claim to
12 deserve the name "pure": (1) it has no pre-defined constants and a very spare
13 syntax; (2) it has no types; (3) it has no side-effects, and is insensitive to
14 the order of evaluation.
15
16 > Sense (3) corresponds most closely to the other uses of "pure" you'll
17 see in the surrounding literature. With respect to this point, it may be true that the Lambda Calculus has no side effects. (Let's revisit that assumption
18 at the end of term.) But as we'll see next week, it is *not* true that it's insensitive to the order of evaluation. So if that's what we mean by "pure", this lambda calculus isn't as pure as you might hope to get. Some *typed* lambda calculi will turn out to be more pure in that respect.
19
20 > But this lambda calculus is at least "pure" in sense (2). At least, it
21 doesn't *explicitly talk about* any types. Some prefer to say that the
22 Lambda Calculus *does* have types implicitly, it's just that
23 there's only one type, so that every expression is a member of
24 that one type. If you say that, you have to say that functions from
25 this type to this type also belong to this type. Which is weird... In
26 fact, though, such types are studied, under the name "recursive
27 types." More about these later in the seminar.
28
29 > Well, at least this lambda calculus is "pure" in sense (1). As we'll
30 see next week, though, there are some computational formal systems
31 whose syntax is *even more* spare, in that they don't even have variables.
32 So if that's what mean by "pure", again this lambda calculus isn't as pure
33 as you might hope to get.
34
35 > Still, if you say you're talking about "the pure" Lambda Calculus,
36 or "the untyped" Lambda Calculus, or even just "the" Lambda Calculus, this
37 is the system that people will understand you to be referring to.
38
39 ## Syntax ##
40
41 Here is its syntax:
42
43 <blockquote>
44 <strong>Variables</strong>: <code>x</code>, <code>y</code>, <code>z</code> ...
45 </blockquote>
46
47 Each variable is an expression. For any variable `a` and (possibly complex) expressions `M` and `N`, the following are also expressions:
48
49 <blockquote>
50 <strong>Abstract</strong>: <code>(&lambda;a M)</code>
51 </blockquote>
52
53 We'll tend to write <code>(&lambda;a M)</code> as just `(\a M)`, so we
54 don't have to write out the markup code for the
55 <code>&lambda;</code>. You can yourself write <code>(&lambda;a
56 M)</code> or `(\a M)` or `(lambda a M)`.
57
58 <blockquote>
59 <strong>Application</strong>: <code>(M N)</code>
60 </blockquote>
61
62 Expressions in the lambda calculus are called "terms".  Here is the
63 syntax of the lambda calculus given in the form of a context-free
64 grammar:
65
66 > T --> Var  
67 > T --> ( &lambda; Var T)  
68 > T --> ( T T )  
69 > Var --> x  
70 > Var --> y  
71 > Var --> z  
72 > ...
73
74 Very, very simple.
75
76 Sometimes the first two production rules are further distinguished, and those
77 are called more specifically "value terms". Whereas Applications (terms of the
78 form `(M N)`) are terms but not value terms.
79
80 Examples of terms:
81
82     x
83     (y x)
84     (x x)
85     (\x y)
86     (\x x)
87     (\x (\y x))
88     (x (\x x))
89     ((\x (x x)) (\x (x x)))
90
91
92 ## Beta-Reduction ##
93
94 The lambda calculus has an associated proof theory. For now, we can regard the
95 proof theory as having just one rule, called the rule of **beta-reduction** or
96 "beta-contraction". Suppose you have some expression of the form:
97
98     ((\a M) N)
99
100 This is an application whose first element is an abstract.  This
101 compound form is called a **redex**, meaning it's a "beta-reducible
102 expression." `(\a M)` is called the **head** of the redex; `N` is
103 called the **argument**, and `M` is called the **body**.
104
105 The rule of beta-reduction permits a transition from that expression to the following:
106
107 > <code>M</code> [<code>a</code> <-- <code>N</code>]
108
109 What this means is just `M`, with any *free occurrences* inside `M` of
110 the variable `a` replaced with the term `N` (--- "without capture", which
111 we'll explain in the [[advanced notes|week2_lambda_advanced]]).
112
113 What is a free occurrence?
114
115 > Any occurrence of a variable `a` is **bound** in T when T has the form `(\a N)`.
116
117 > An occurrence of a variable `a` is **bound** in T when T has the form `(\b
118 N)` --- that is, with a *different* variable `b` --- just in case that
119 occurrence of `a` is bound in the subexpression `N`.
120
121 > When T has the form `(M N)`, any occurrences of `a` that are bound in the
122 subexpression `M` are also bound in T, and so too any occurrences of `a` that
123 are bound in the subexpression `N`.
124
125 > An occurrence of a variable is **free** if it's not bound.
126
127 For instance consider the following term `T`:
128
129     (x (\x (\y (x (y z)))))
130
131 The first occurrence of `x` in T is free.  The `\x` we won't regard as
132 containing an occurrence of `x`. The next occurrence of `x` occurs
133 within a form `(\x (\y ...))` that begins with `\x`, so it is bound as well. The
134 occurrence of `y` is bound; and the occurrence of `z` is free.
135
136 To read further:
137
138 * [[!wikipedia Free variables and bound variables]]
139
140 Here's an example of beta-reduction:
141
142     ((\x (y x)) z)
143
144 beta-reduces to:
145
146     (y z)
147
148 We'll write that like this:
149
150     ((\x (y x)) z) ~~> (y z)
151
152 Different authors use different terminology and notation. Some authors use the term
153 "contraction" for a single reduction step, and reserve the term
154 "reduction" for the reflexive transitive closure of that, that is, for
155 zero or more reduction steps. Informally, it seems easiest to us to
156 say "reduction" for one or more reduction steps. So when we write:
157
158     M ~~> N
159
160 we'll mean that you can get from `M` to `N` by one or more reduction
161 steps.
162
163 When `M` and `N` are such that there is some common term (perhaps just one
164 of those two, or perhaps a third term) that they both reduce to,
165 we'll say that `M` and `N` are **beta-convertible**. We'll write that
166 like this:
167
168     M <~~> N
169
170 More details about the notation and metatheory of
171 the lambda calculus are in [[this week's advanced notes|topics/week2_lambda_advanced]].
172
173
174 ## Shorthand ##
175
176 The grammar we gave for the lambda calculus leads to some
177 verbosity. There are several informal conventions in widespread use,
178 which enable the language to be written more compactly. (If you like,
179 you could instead articulate a formal grammar which incorporates these
180 additional conventions. Instead of showing it to you, we'll leave it
181 as an exercise for those so inclined.)
182
183
184 **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:
185
186     (\x (x y))
187
188 as:
189
190     \x (x y)
191
192 but you should include the parentheses in:
193
194     (\x (x y)) z
195
196 and:
197
198     z (\x (x y))
199
200
201 **Dot notation** Dot means "Insert a left parenthesis here, and the matching right parenthesis as far to the right as possible without creating unbalanced parentheses---so long as doing so would enclose an application or abstract not already wrapped in parentheses." Thus:
202
203     \x (\y (x y))
204
205 can be abbreviated as:
206
207     \x (\y. x y)
208
209 and that as:
210
211     \x. \y. x y
212
213 This:
214
215     \x. \y. (x y) x
216
217 abbreviates:
218
219     \x (\y ((x y) x))
220
221 This on the other hand:
222
223     (\x. \y. (x y)) x
224
225 abbreviates:
226
227     ((\x (\y (x y))) x)
228
229 The outermost parentheses were added because we have an application. `(\x. \y.
230 ...)` became `(\x (\y. ...))` because of the rule for dots. We didn't
231 insert any parentheses around the inner body of `\y. (x y)` because they were
232 already there. That is, in expressions of the form `\y. (...)`, the dot abbreviates
233 nothing. It's harmless to write such a dot, though, and it can be conceptually
234 helpful especially in light of the next convention.
235
236 Similarly, we permit `\x. x`, which is shorthand for `\x x`, not for `\x (x)`, which
237 our syntax forbids. (The [[lambda evaluator|/code/lambda_evaluator]] however tolerates such expressions.)
238
239
240 **Merging lambdas** An expression of the form `(\x (\y M))`, or equivalently, `(\x. \y. M)`, can be abbreviated as:
241
242     (\x y. M)
243
244 Similarly, `(\x (\y (\z M)))` can be abbreviated as:
245
246     (\x y z. M)
247
248
249 ## Lambda terms represent functions ##
250
251 Let's pause and consider the following fundamental question: what is a
252 function?  One popular answer is that a function can be represented by
253 a set of ordered pairs.  This set is called the **graph** of the
254 function.  If the ordered pair `(a, b)` is a member of the graph of `f`,
255 that means that `f` maps the argument `a` to the value `b`.  In
256 symbols, `f: a` &mapsto; `b`, or `f (a) == b`.
257
258 In order to count as a *function* (rather
259 than as merely a more general *relation*), we require that the graph not contain two
260 (distinct) ordered pairs with the same first element.  That is, in
261 order to count as a proper function, each argument must correspond to
262 a unique result.
263
264 The lambda calculus seems to be wonderfully well-suited for
265 representing functions.  In fact, the untyped
266 lambda calculus is Turing Complete (see [[!wikipedia Turing completeness]]):
267 all (recursively computable) functions can be represented by lambda
268 terms. Which, by most people's lights, means that all functions we can "effectively decide" ---
269 that is, always apply in a mechanical way without requiring any ingenuity or insight, and be guaranteed of a correct answer after some finite number of steps ---
270 can be represented by lambda terms. As we'll see, though, it will be fun
271 (that is, not straightforward) unpacking how these things can be so "represented."
272
273 For some lambda terms, it is easy to see what function they represent:
274
275 > `(\x x)` represents the identity function: given any argument `M`, this function
276 simply returns `M`: `((\x x) M) ~~> M`.
277
278 > `(\x (x x))` duplicates its argument (applies it to itself):
279 `((\x (x x)) M) ~~> (M M)` <!-- **M** or &omega;; W is \uv.uvv, L is \uv.u(vv) -->
280
281 > `(\x (\y (y x)))` reorders its two arguments:
282 `(((\x  (\y (y x))) M) N) ~~> (N M)` <!-- **T**; C is \uvx.uxv -->
283
284 > `(\x (\y x))` throws away its second argument:
285 `(((\x (\y x)) M) N) ~~> M` <!-- **K** -->
286
287 and so on.  In order to get an intuitive feel for the power of the
288 lambda calculus, note that duplicating, reordering, and deleting
289 elements is all that it takes to simulate the behavior of a general
290 word processing program.  That means that if we had a big enough
291 lambda term, it could take a representation of *Emma* as input and
292 produce *Hamlet* as a result.
293
294 Some of these functions are so useful that we'll give them special
295 names.  In particular, we'll call the identity function `(\x x)`
296 **I**, and the function `(\x (\y x))` **K** (for "konstant": <code><b>K</b> x</code> is
297 a "constant function" that accepts any second argument `y` and ignores
298 it, always returning `x`).
299
300 It is easy to see that distinct lambda expressions can represent the same
301 function, considered as a mapping from input to outputs. Obviously:
302
303     (\x x)
304
305 and:
306
307     (\z z)
308
309 both represent the same function, the identity function. However, we said
310 [[in the advanced notes|week2_lambda_advanced]] that we would be regarding these expressions as
311 synactically equivalent, so they aren't yet really examples of *distinct*
312 lambda expressions representing a single function. However, all three of these
313 are distinct lambda expressions:
314
315     (\y x. y x) (\z z)
316
317     (\x. (\z z) x)
318
319     (\z z)
320
321 yet when applied to any argument `M`, all of these will always return `M`. So they
322 have the same extension. It's also true, though you may not yet be in a
323 position to see, that no other function can differentiate between them when
324 they're supplied as an argument to it. However, these expressions are all
325 syntactically distinct.
326
327 The first two expressions are (beta-)*convertible*: in particular the first
328 reduces to the second via a single instance of beta reduction. So they
329 can be regarded as proof-theoretically equivalent even though they're
330 not syntactically identical. However, the proof theory we've given so
331 far doesn't permit you to reduce the second expression to the
332 third. So these lambda expressions are non-equivalent.
333
334 In other words, we have here different (non-equivalent) lambda terms with the
335 same extension. This introduces some tension between the popular way of
336 thinking of functions as represented by (identical to?) their graphs or
337 extensions, and the idea that lambda terms express functions. Well, perhaps the
338 lambda terms are just a finer-grained way of expressing functions than
339 extensions are?
340
341 As we'll see, though, there are even further sources of
342 tension between the idea of functions-as-extensions and the idea of functions
343 embodied in the lambda calculus.
344
345
346 1.  One reason is that that general
347 mathematical conception permits many *uncomputable* functions, but the
348 lambda calculus can't express those.
349
350 2.  More problematically, lambda terms express "functions" that can *take themselves* as arguments.  If we wanted to represent that set-theoretically, and
351 identified functions with their extensions, then we'd have to have some
352 extension that contained (an ordered pair containing) itself as a member. Which
353 we're not allowed to do in mainstream set-theory.  But in the lambda calculus
354 this is permitted and common --- and in fact will turn out to be indispensable.
355
356     Here are some simple examples. We can apply the identity function to itself:
357
358         (\x x) (\x x)
359
360    This is a redex that reduces to the identity function (of course).
361
362    We can apply the **K** function to another argument and itself:
363
364    > <code><b>K</b> z <b>K</b></code>
365
366     That is:
367
368         (\x (\y x)) z (\x (\y x))
369
370     That reduces to just `z`.
371
372 3.  As we'll see in coming weeks, some lambda terms will turn out to be
373 impossible to associate with any extension. This is related to the previous point.
374
375
376 In fact it *does* turn out to be possible to represent the Lambda Calculus
377 set-theoretically. But not in the straightforward way that identifies
378 functions with their graphs. For years, it wasn't known whether it would be possible to do this. But then
379 [[!wikipedia Dana Scott]] figured out how to do it in late 1969, that is,
380 he formulated the first "denotational semantics" for this Lambda Calculus.
381 Scott himself had expected that this wouldn't be possible to do. He argued
382 for its unlikelihood in a paper he wrote only a month before the discovery.
383
384 (You can find an exposition of Scott's semantics in Chapters 15 and 16 of the
385 Hindley &amp; Seldin book we recommended, and an exposition of some simpler
386 models that have since been discovered in Chapter 5 of the Hankin book, and
387 Section 16F of Hindley &amp; Seldin. But realistically, you really ought to
388 wait a while and get more familiar with these systems before you'll be at all
389 ready to engage with those ideas.)
390
391 We've characterized the rule of beta-reduction as a kind of "proof theory" for
392 the Lambda Calculus. In fact, the usual proof theory is expressed in terms of
393 *convertibility* rather than in terms of reduction; but it's natural to
394 understand reduction as being the conceptually more fundamental notion. And
395 there are some proof theories for this system that are expressed in terms of
396 reduction.
397
398 To use a linguistic analogy, you can think of what we're calling
399 "proof theory" as a kind of syntactic transformation. The
400 sentences *John saw Mary* and *Mary was seen by John* are not
401 syntactically identical, yet (on some theories) one can be derived
402 from the other. The key element in the analogy is that this kind of
403 syntactic derivation is supposed to preserve meaning, so that the two
404 sentences mean (roughly) the same thing.
405
406 There's an extension of the proof-theory we've presented so far which
407 does permit a further move of just that sort. It would permit us to
408 also count these functions:
409
410     (\x. (\z z) x)
411
412     (\z z)
413
414 as equivalent. This additional move is called **eta-reduction**. It's
415 crucial to eta-reduction that the outermost variable binding in the
416 abstract we begin with (here, `\x`) be of a variable that occurs free
417 exactly once in the body of that abstract, and that that free occurrence be the rightmost outermost constituent.
418
419 The expression:
420
421     (\x (\y (y x))
422
423 can't be eta-reduced, because the rightmost outermost constituent is not `x` but `(\y (y x)`.
424
425 In the extended proof theory/theories we get be permitting eta-reduction/conversion as well as beta-reduction, *all computable functions with the same
426 extension do turn out to be equivalent*, that is, convertible.
427
428 However, we still shouldn't assume we're working with functions
429 traditionally conceived as just sets of ordered pairs, for the other
430 reasons sketched above.
431
432
433 ## The analogy with `let` ##
434
435 In our basic functional programming language, we used `let`
436 expressions to assign values to variables.  For instance,
437
438     let x match 2
439     in (x, x)
440
441 evaluates to the ordered pair `(2, 2)`.  It may be helpful to think of
442 a redex in the lambda calculus as a particular sort of `let`
443 construction.
444
445     ((\x BODY) ARG)
446
447 is analogous to
448
449     let x match ARG
450     in BODY
451
452 This analogy should be treated with caution.  For one thing, our `letrec`
453 allowed us to define recursive functions in which the name `x` appeared within
454 `ARG`, but we wanted it there to be bound to the very same `ARG`.  We're not
455 ready to deal with recursive functions in the lambda calculus yet.
456
457 For another, we defined `let` in terms of *values*: we said that the variable
458 `x` was bound to whatever *value* `ARG` *evaluated to*. At this point, it's
459 not clear what the values are in the lambda calculus. We only have expressions.
460 (Though there was a suggestive remark earlier about some of the expressions but
461 not others being called "value terms".)
462
463 So perhaps we should translate `((\x BODY) ARG)` in purely syntactic terms,
464 like: "let `x` be replaced by `ARG` in `BODY`"?
465
466 Most problematically, in the lambda
467 calculus, an abstract such as `(\x (x x))` is perfectly well-formed
468 and coherent, but it is not possible to write a `let` expression that
469 does not have an `ARG`. That would be like:
470
471 &nbsp;&nbsp;&nbsp;&nbsp;`let x match` *missing*  
472 &nbsp;&nbsp;&nbsp;&nbsp;`in x x`
473
474 Nevertheless, the correspondence is close enough that it can guide our
475 intuition.
476