->combinatory
[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 "assume a left paren here, and the matching right
202 paren as far to the right as possible without creating unbalanced
203 parentheses". So:
204
205     \x (\y (x y))
206
207 can be abbreviated as:
208
209     \x (\y. x y)
210
211 and that as:
212
213     \x. \y. x y
214
215 This:
216
217     \x. \y. (x y) x
218
219 abbreviates:
220
221     \x (\y ((x y) x))
222
223 This on the other hand:
224
225     (\x. \y. (x y)) x
226
227 abbreviates:
228
229     ((\x (\y (x y))) x)
230
231 The outermost parentheses were added because we have an application. `(\x. \y.
232 ...)` became `(\x (\y. ...))` because of the rule for dots. We didn't have to
233 insert any parentheses around the inner body of `\y. (x y)` because they were
234 already there. That is, in expressions of the form `\y. (...)`, the dot abbreviates
235 nothing. It's harmless to write such a dot, though, and it can be conceptually
236 helpful especially in light of the next convention...
237
238
239 **Merging lambdas** An expression of the form `(\x (\y M))`, or equivalently, `(\x. \y. M)`, can be abbreviated as:
240
241     (\x y. M)
242
243 Similarly, `(\x (\y (\z M)))` can be abbreviated as:
244
245     (\x y z. M)
246
247
248 ## Lambda terms represent functions ##
249
250 Let's pause and consider the following fundamental question: what is a
251 function?  One popular answer is that a function can be represented by
252 a set of ordered pairs.  This set is called the **graph** of the
253 function.  If the ordered pair `(a, b)` is a member of the graph of `f`,
254 that means that `f` maps the argument `a` to the value `b`.  In
255 symbols, `f: a` &mapsto; `b`, or `f (a) == b`.
256
257 In order to count as a *function* (rather
258 than as merely a more general *relation*), we require that the graph not contain two
259 (distinct) ordered pairs with the same first element.  That is, in
260 order to count as a proper function, each argument must correspond to
261 a unique result.
262
263 The lambda calculus seems to be wonderfully well-suited for
264 representing functions.  In fact, the untyped
265 lambda calculus is Turing Complete (see [[!wikipedia Turing completeness]]):
266 all (recursively computable) functions can be represented by lambda
267 terms. Which, by most people's lights, means that all functions we can "effectively decide" ---
268 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 ---
269 can be represented by lambda terms. As we'll see, though, it will be fun
270 (that is, not straightforward) unpacking how these things can be so "represented."
271
272 For some lambda terms, it is easy to see what function they represent:
273
274 > `(\x x)` represents the identity function: given any argument `M`, this function
275 simply returns `M`: `((\x x) M) ~~> M`.
276
277 > `(\x (x x))` duplicates its argument (applies it to itself):
278 `((\x (x x)) M) ~~> (M M)` <!-- **M** or &omega;; W is \uv.uvv, L is \uv.u(vv) -->
279
280 > `(\x (\y (y x)))` reorders its two arguments:
281 `(((\x  (\y (y x))) M) N) ~~> (N M)` <!-- **T**; C is \uvx.uxv -->
282
283 > `(\x (\y x))` throws away its second argument:
284 `(((\x (\y x)) M) N) ~~> M` <!-- **K** -->
285
286 and so on.  In order to get an intuitive feel for the power of the
287 lambda calculus, note that duplicating, reordering, and deleting
288 elements is all that it takes to simulate the behavior of a general
289 word processing program.  That means that if we had a big enough
290 lambda term, it could take a representation of *Emma* as input and
291 produce *Hamlet* as a result.
292
293 Some of these functions are so useful that we'll give them special
294 names.  In particular, we'll call the identity function `(\x x)`
295 **I**, and the function `(\x (\y x))` **K** (for "konstant": <code><b>K</b> x</code> is
296 a "constant function" that accepts any second argument `y` and ignores
297 it, always returning `x`).
298
299 It is easy to see that distinct lambda expressions can represent the same
300 function, considered as a mapping from input to outputs. Obviously:
301
302     (\x x)
303
304 and:
305
306     (\z z)
307
308 both represent the same function, the identity function. However, we said
309 [[in the advanced notes|week2_lambda_advanced]] that we would be regarding these expressions as
310 synactically equivalent, so they aren't yet really examples of *distinct*
311 lambda expressions representing a single function. However, all three of these
312 are distinct lambda expressions:
313
314     (\y x. y x) (\z z)
315
316     (\x. (\z z) x)
317
318     (\z z)
319
320 yet when applied to any argument `M`, all of these will always return `M`. So they
321 have the same extension. It's also true, though you may not yet be in a
322 position to see, that no other function can differentiate between them when
323 they're supplied as an argument to it. However, these expressions are all
324 syntactically distinct.
325
326 The first two expressions are (beta-)*convertible*: in particular the first
327 reduces to the second via a single instance of beta reduction. So they
328 can be regarded as proof-theoretically equivalent even though they're
329 not syntactically identical. However, the proof theory we've given so
330 far doesn't permit you to reduce the second expression to the
331 third. So these lambda expressions are non-equivalent.
332
333 In other words, we have here different (non-equivalent) lambda terms with the
334 same extension. This introduces some tension between the popular way of
335 thinking of functions as represented by (identical to?) their graphs or
336 extensions, and the idea that lambda terms express functions. Well, perhaps the
337 lambda terms are just a finer-grained way of expressing functions than
338 extensions are?
339
340 As we'll see, though, there are even further sources of
341 tension between the idea of functions-as-extensions and the idea of functions
342 embodied in the lambda calculus.
343
344
345 1.  One reason is that that general
346 mathematical conception permits many *uncomputable* functions, but the
347 lambda calculus can't express those.
348
349 2.  More problematically, lambda terms express "functions" that can *take themselves* as arguments.  If we wanted to represent that set-theoretically, and
350 identified functions with their extensions, then we'd have to have some
351 extension that contained (an ordered pair containing) itself as a member. Which
352 we're not allowed to do in mainstream set-theory.  But in the lambda calculus
353 this is permitted and common --- and in fact will turn out to be indispensable.
354
355     Here are some simple examples. We can apply the identity function to itself:
356
357         (\x x) (\x x)
358
359    This is a redex that reduces to the identity function (of course).
360
361    We can apply the **K** function to another argument and itself:
362
363    > <code><b>K</b> z <b>K</b></code>
364
365     That is:
366
367         (\x (\y x)) z (\x (\y x))
368
369     That reduces to just `z`.
370
371 3.  As we'll see in coming weeks, some lambda terms will turn out to be
372 impossible to associate with any extension. This is related to the previous point.
373
374
375 In fact it *does* turn out to be possible to represent the Lambda Calculus
376 set-theoretically. But not in the straightforward way that identifies
377 functions with their graphs. For years, it wasn't known whether it would be possible to do this. But then
378 [[!wikipedia Dana Scott]] figured out how to do it in late 1969, that is,
379 he formulated the first "denotational semantics" for this Lambda Calculus.
380 Scott himself had expected that this wouldn't be possible to do. He argued
381 for its unlikelihood in a paper he wrote only a month before the discovery.
382
383 (You can find an exposition of Scott's semantics in Chapters 15 and 16 of the
384 Hindley &amp; Seldin book we recommended, and an exposition of some simpler
385 models that have since been discovered in Chapter 5 of the Hankin book, and
386 Section 16F of Hindley &amp; Seldin. But realistically, you really ought to
387 wait a while and get more familiar with these systems before you'll be at all
388 ready to engage with those ideas.)
389
390 We've characterized the rule of beta-reduction as a kind of "proof theory" for
391 the Lambda Calculus. In fact, the usual proof theory is expressed in terms of
392 *convertibility* rather than in terms of reduction; but it's natural to
393 understand reduction as being the conceptually more fundamental notion. And
394 there are some proof theories for this system that are expressed in terms of
395 reduction.
396
397 To use a linguistic analogy, you can think of what we're calling
398 "proof theory" as a kind of syntactic transformation. The
399 sentences *John saw Mary* and *Mary was seen by John* are not
400 syntactically identical, yet (on some theories) one can be derived
401 from the other. The key element in the analogy is that this kind of
402 syntactic derivation is supposed to preserve meaning, so that the two
403 sentences mean (roughly) the same thing.
404
405 There's an extension of the proof-theory we've presented so far which
406 does permit a further move of just that sort. It would permit us to
407 also count these functions:
408
409     (\x. (\z z) x)
410
411     (\z z)
412
413 as equivalent. This additional move is called **eta-reduction**. It's
414 crucial to eta-reduction that the outermost variable binding in the
415 abstract we begin with (here, `\x`) be of a variable that occurs free
416 exactly once in the body of that abstract, and that that free occurrence be the rightmost outermost constituent.
417
418 The expression:
419
420     (\x (\y (y x))
421
422 can't be eta-reduced, because the rightmost outermost constituent is not `x` but `(\y (y x)`.
423
424 In the extended proof theory/theories we get be permitting eta-reduction/conversion as well as beta-reduction, *all computable functions with the same
425 extension do turn out to be equivalent*, that is, convertible.
426
427 However, we still shouldn't assume we're working with functions
428 traditionally conceived as just sets of ordered pairs, for the other
429 reasons sketched above.
430
431
432 ## The analogy with `let` ##
433
434 In our basic functional programming language, we used `let`
435 expressions to assign values to variables.  For instance,
436
437     let x match 2
438     in (x, x)
439
440 evaluates to the ordered pair `(2, 2)`.  It may be helpful to think of
441 a redex in the lambda calculus as a particular sort of `let`
442 construction.
443
444     ((\x BODY) ARG)
445
446 is analogous to
447
448     let x match ARG
449     in BODY
450
451 This analogy should be treated with caution.  For one thing, our `letrec`
452 allowed us to define recursive functions in which the name `x` appeared within
453 `ARG`, but we wanted it there to be bound to the very same `ARG`.  We're not
454 ready to deal with recursive functions in the lambda calculus yet.
455
456 For another, we defined `let` in terms of *values*: we said that the variable
457 `x` was bound to whatever *value* `ARG` *evaluated to*. At this point, it's
458 not clear what the values are in the lambda calculus. We only have expressions.
459 (Though there was a suggestive remark earlier about some of the expressions but
460 not others being called "value terms".)
461
462 So perhaps we should translate `((\x BODY) ARG)` in purely syntactic terms,
463 like: "let `x` be replaced by `ARG` in `BODY`"?
464
465 Most problematically, in the lambda
466 calculus, an abstract such as `(\x (x x))` is perfectly well-formed
467 and coherent, but it is not possible to write a `let` expression that
468 does not have an `ARG`. That would be like:
469
470 &nbsp;&nbsp;&nbsp;&nbsp;`let x match` *missing*  
471 &nbsp;&nbsp;&nbsp;&nbsp;`in x x`
472
473 Nevertheless, the correspondence is close enough that it can guide our
474 intuition.
475