add week 12 stuff
[lambda.git] / topics / week3_evaluation_order.mdwn
1 Evaluation Strategies and Normalization
2 =======================================
3
4 In last week's homework, we asked you to reduce various expressions until it wasn't possible to reduce them any further. For two of those expressions, this was impossible to do. One of them was this:
5
6         (\x. x x) (\x. x x)
7
8 As we discuss in other notes for this week, each of the halves of this formula are the combinator `ω`; so this can also be written:
9
10     ω ω
11
12 This compound expression---the self-application of `ω`---is named `Ω`. It has the form of an application of an abstract (`ω`) to an argument (which also happens to be `ω`), so it's a redex and can be reduced. But when we reduce it, we get `ω ω` again. So there's no stage at which this expression has been reduced to a point where it can't be reduced any further. In other words, evaluation of this expression "never terminates." (This is the standard language, however it has the unfortunate connotation that evaluation is a process or operation that must be performed over time. You shouldn't think of it like that. Evaluation of this expression "never terminates" in the way that the decimal expansion of π never terminates. These are static, atemporal facts about their mathematical properties.)
13
14 There are infinitely many formulas in the Lambda Calculus that have this same property. `Ω` is the syntactically simplest of them. In our meta-theory, it's common to assign such formulas a special meaning, <big><code>&perp;</code></big>, pronounced "bottom." When we get to discussing types, you'll see that expressions with this meaning are counted as belonging to every type. To say that a term "is bottom" means that the computation that term represents never terminates, and so the term doesn't evaluate to any orthodox, computed value.
15
16 From a "Fregean" or "weak Kleene" perspective, if any component of an expression fails to be evaluable (to an orthodox, computed value), then the whole expression should be unevaluable as well.
17
18 However, in some such cases it seems *we could* sensibly carry on evaluation. For instance, consider:
19
20     (\x. y) (ω ω)
21
22 Should we count this as unevaluable, because the reduction of `(ω ω)` never terminates? Or should we count it as evaluating to `y`?
23
24 This question highlights that there are different choices to make about how evaluation or computation proceeds. It's helpful to think of three questions in this neighborhood:
25
26 >       Q1. When arguments are complex, as `(ω ω)` is, do we reduce them before substituting them into the abstracts to which they are arguments (`(\x. y)`, in the expression displayed above), or later?
27
28 >       Q2. Are we allowed to reduce inside abstracts? That is, can we reduce:
29
30 >               (\x y. x z) (\x. x)
31
32 >       only this far:
33
34 >               \y. (\x. x) z
35
36 >       or can we continue reducing to:
37
38 >               \y. z
39
40 >       Q3. Are we allowed to "eta-reduce"? That is, can we reduce expressions of the form:
41
42 >               \x. M x
43
44 >       where x does not occur free in `M`, to `M`?
45
46 With regard to Q3, it should be intuitively clear that `\x. M x` and
47 `M` will behave the same with respect to any arguments they are
48 given. It can also be proven that no other functions can behave
49 differently with respect to them (that is, no function can interact differently with further arguments depending on whether it has been applied to `M` versus `\x. M x`).  However, the logical system you get when eta-reduction is added to the proof theory is importantly different from the one where only beta-reduction is permitted.
50
51 If we answer Q2 by permitting reduction inside abstracts, and we also permit eta-reduction, then where none of <code>y<sub>1</sub>, ..., y<sub>n</sub></code> occur free in `M`, this:
52
53 <pre><code>\x y<sub>1</sub>...y<sub>n</sub>. M y<sub>1</sub>...y<sub>n</sub></code></pre>
54
55 will eta-reduce by n steps to:
56
57         \x. M
58
59 When we add eta-reduction to our proof system, we end up reconstruing the meaning of `~~>`, and `<~~>`, and "normal form" (we will discuss this below), all of these in terms that permit eta-reduction as well. Sometimes these expressions will be annotated to indicate whether only beta-reduction is allowed (<code>~~><sub>&beta;</sub></code>) or whether both beta- and eta-reduction is allowed (<code>~~><sub>&beta;&eta;</sub></code>).
60
61 The logical system you get when eta-reduction is added to the proof system has the following property:
62
63 >       if `M`, `N` are normal forms with no free variables, then `M ≡ N` iff `M` and `N` behave the same with respect to every possible sequence of arguments.
64
65 This implies that, when `M` and `N` are (closed normal forms that are) syntactically distinct, there will always be some sequences of arguments <code>L<sub>1</sub>, ..., L<sub>n</sub></code> such that:
66
67 <pre><code>M L<sub>1</sub> ... L<sub>n</sub> x y ~~> x
68 N L<sub>1</sub> ... L<sub>n</sub> x y ~~> y
69 </code></pre>
70
71 So closed beta-plus-eta-normal forms will be syntactically different iff they yield different values for some arguments. That is, iff their extensions differ.
72
73 So the proof theory with eta-reduction added is called "extensional," because its notion of normal form makes syntactic identity of closed normal forms coincide with extensional equivalence.
74
75 See Hindley and Seldin, Chapters 7-8 and 14, for discussion of what should count as capturing the "extensionality" of these systems, and some outstanding issues.
76
77
78 The evaluation strategy which answers Q1 by saying "reduce arguments first" is known as **call-by-value**. The evaluation strategy which answers Q1 by saying "substitute arguments in unreduced" is known as **call-by-name** or **call-by-need** (in the absence of side-effects, the difference between these has only to do with efficiency, not semantics).
79
80 When one has a call-by-value strategy that *also* permits reduction to continue inside unapplied abstracts, that's known as "applicative order" reduction. When one has a call-by-name strategy that permits reduction inside abstracts, that's known as "normal order" reduction. Consider an expression of the form:
81
82         ((A B) (C D)) (E F)
83
84 Its syntax has the following tree:
85
86           ((A B) (C D)) (E F)
87                    /     \
88                   /       \
89         ((A B) (C D))  \
90                 /\        (E F)
91            /  \        /\
92           /    \      E  F
93         (A B) (C D)
94          /\    /\
95         /  \  /  \
96         A   B C   D
97
98 Applicative order evaluation does what's called a "post-order traversal" of the tree: that is, we always go down when we can, first to the left, and we process a node only after processing all its children. So `(C D)` gets processed before `((A B) (C D))` does, and `(E F)` gets processed before `((A B) (C D)) (E F)` does.
99
100 Normal order evaluation, on the other hand, will substitute the expression `(C D)` into the abstract that `(A B)` evaluates to, without first trying to compute what `(C D)` evaluates to. That computation may be done later.
101
102 With normal-order evaluation (or call-by-name more generally), if we have an expression like:
103
104         (\x. y) (C D)
105
106 the computation of `(C D)` won't ever have to be performed. Instead, `(\x. y) (C D)` reduces directly to `y`. This is so even if `(C D)` is the non-evaluable `(ω ω)`!
107
108 Call-by-name evaluation is often called "lazy." Call-by-value evaluation is also often called "eager" or "strict". In some contexts, these terms all have subtly different technical meanings. But those differences are hard to identify in the first place, plus mostly the terms are used in a way that doesn't adhere carefully to such subtleties. One association it may be helpful for you to remember is between the term "strict" and what we above called the "Fregean" or "weak Kleene" perspective: if any argument of a function is non-evaluable or non-normalizing, so too should be the application of the function to that argument.
109
110 Most programming languages, including Scheme and OCaml, default to using the strict/call-by-value evaluation strategy. (But they *don't* permit evaluation to continue inside unappplied functions.) There are techniques for making these languages perform lazy/call-by-name evaluation, when necessary. But by default, arguments will always be evaluated *before* being bound to the parameters (the `\x`s) of a function.
111
112 When functions take more than one argument at a time, as is the norm with Scheme, a further question arises: whether the multiple arguments should be evaluated left-to-right, or right-to-left, or is nothing guaranteed about what order they are evaluated in? Different languages make different choices about this.
113
114 Some functional programming languages, such as Haskell, default to using the lazy/call-by-name evaluation strategy. There are techniques for making Haskell perform strict/call-by-value evaluation, when necessary.
115
116 The Lambda Calculus can be evaluated either way. You have to decide what the rules shall be.
117
118 As we'll see later in the seminar, there are techniques by which we can specify --- in an order-independent way --- that a computation should be evaluated in call-by-value order; and also techniques for specifying call-by-name order. If you liked, you could even have a nested hierarchy, where blocks at each level were forced to be evaluated in alternating ways.
119
120 Call-by-value and call-by-name evaluation have different pros and cons.
121
122 One important advantage of normal-order evaluation in particular is
123 that it can compute orthodox values for `(\x. y) (ω ω)`.  
124
125 To see how normal-order evaluation delivers a normal
126 form, consider all conceivable evaluation paths of the following term:
127
128 <pre>
129 (\x.I) ((\x.xxx)(\x.xxx))
130  |         \
131  |      (\x.I) ((\x.xxx)(\x.xxx)(\x.xxx))
132  |        /      \
133  |-------+    (\x.I) ((\x.xxx)(\x.xxx)(\x.xxx)(\x.xxx))
134  |              /       \
135  I ------------+         etc.
136 </pre>
137
138 If we start by evaluating the leftmost redex, we're done in one step.
139 If we unwisely start by evaluating the rightmost redex, we arrive at a
140 term that still has two redexes.  Once again, we have a choice: either
141 reduce the leftmost redex, in which case we're done.  Or reduce the
142 rightmost redex, creating an even longer term.  Clearly, in this
143 situation, we want to prioritize reducing the leftmost redex in order
144 to arrive at a stable result more quickly.
145
146 Indeed, it's provable for the untyped Lambda Calculus that if there's *any* reduction path that delivers a value for a given expression, the normal-order evaluation strategy will terminate with that value.
147
148 An expression is said to be in **normal form** when it's not possible to perform any more reductions (not even inside abstracts).
149 There's a sense in which you *can't get anything more out of* `ω ω`, but it's not in normal form because it still has the form of a redex.
150
151 A computational system is said to be **confluent**, or to have the **Church-Rosser** or **diamond** property, if, whenever there are multiple possible evaluation paths, those that terminate always terminate in the same value. In such a system, the choice of which sub-expressions to evaluate first will only matter if some of them but not others might lead down a non-terminating path.
152
153 The diamond property is named after the shape of diagrams like the following:
154
155 <pre>
156                      ((\x.x) ((\y.z) y))
157                        /        \
158                       /          \
159                      /            \
160                     /              \
161                   ((\y.z) y)   ((\x.x) z)
162                       \             /
163                        \           /
164                         \         /
165                          \       /
166                           \     /
167                            \   /
168                              z
169 </pre>
170
171 Because the starting term contains more than one redex, we can imagine
172 reducing the leftmost redex first (the left branch of the diagram) or
173 else the rightmost redex (the right branch of the diagram).  But
174 because the Lambda Calculus is confluent, no matter which lambda you
175 choose to target for reduction first, you end up at the same place.
176 It's like traveling in (much of) Manhattan: if you walk uptown first and then
177 head east, you end up in the same place as if you walk east and then
178 head uptown.
179
180 As we mentioned, the untyped Lambda Calculus is confluent. So long as a computation terminates, it always terminates in the same way. It doesn't matter which order the sub-expressions are evaluated in.
181
182 A computational system is said to be **strongly normalizing** if *every* permitted evaluation path is guaranteed to terminate. The untyped Lambda Calculus is *not* strongly normalizing: `ω ω` doesn't terminate by any evaluation path; and `(\x. y) (ω ω)` terminates only by some evaluation paths but not by others.
183
184 But the untyped Lambda Calculus enjoys some compensation for this weakness. It's Turing Complete! It can represent any computation we know how to describe. (That's the cash value of being Turing Complete, not the rigorous definition. There is a rigorous definition. However, we don't know how to rigorously define "any computation we know how to describe.") And in fact, it's been proven that you can't have both. If a computational system is Turing Complete, it cannot be strongly normalizing.
185
186 A computational system is said to be **weakly normalizing** if there's always guaranteed to be *at least one* evaluation path that terminates. The untyped Lambda Calculus is not weakly normalizing either, as we've seen.
187
188 The *simply-typed* lambda calculus that linguists traditionally work with, on the other hand, is strongly normalizing. (And as a result, is not Turing Complete.) It has expressive power (concerning types) that the untyped Lambda Calculus does not natively possess, but it is also unable to represent some (terminating!) computations that the untyped Lambda Calculus can represent.
189
190 (Interestingly, since the untyped Lambda Calculus *is* Turing Complete, any algorithmic manipulations we can do the simply-typed (or any other) lambda calculus can in principle be *encoded in* operations in the untyped Lambda Calculus. It then becomes an interesting question what we could mean, when we want to say things like "This typed lambda calculus has an expressive power not (natively) present in the untyped Lambda Calculus.")
191
192 Other more-powerful type systems we'll look at in the course will also fail to be Turing Complete, though they will turn out to be pretty powerful.
193
194 Further reading:
195
196 *       [[!wikipedia Evaluation strategy]]
197 *       [[!wikipedia Eager evaluation]]
198 *       [[!wikipedia Lazy evaluation]]
199 *       [[!wikipedia Strict programming language]]<p>
200 *       [[!wikipedia Church-Rosser theorem]]
201 *       [[!wikipedia Normalization property]]
202 *       [[!wikipedia Turing Completeness]]
203
204
205 Decidability
206 ============
207
208 The question whether two formulas are syntactically equal is "decidable": we can construct a computation that's guaranteed to always give us the correct answer.
209
210 What about the question whether two formulas are convertible? Well, to answer that, we just need to reduce them to normal form, if possible, and check whether the results are syntactically equal. The crux is that "if possible." Some computations can't be reduced to normal form. Their evaluation paths never terminate. And if we just kept trying blindly to reduce them, our computation of what they're convertible to would also never terminate.
211
212 So it'd be handy to have some way to check in advance whether a formula has a normal form: whether there's any evaluation path for it that terminates.
213
214 Is it possible to do that? Sure, sometimes. For instance, check whether the formula is syntactically equal to `Ω`. If it is, it never terminates.
215
216 But is there any method for doing this in general---for telling, of any given computation, whether that computation would terminate? Unfortunately, there is not. Church proved this in 1936; Turing also essentially proved it at the same time. Geoff Pullum gives a very reader-friendly outline of Turing's proof here:
217
218 *       [Scooping the Loop Snooper](http://www.cl.cam.ac.uk/teaching/0910/CompTheory/scooping.pdf), a proof of the undecidability of the halting problem in the style of Dr Seuss by Geoffrey K. Pullum
219
220 Interestingly, Church also set up an association between the Lambda Calculus and first-order predicate logic, such that, for arbitrary lambda formulas `M` and `N`, some formula would be provable in predicate logic iff `M` and `N` were convertible. So since the right-hand side is not decidable, questions of provability in first-order predicate logic must not be decidable either. This was the first proof of the undecidability of first-order predicate logic.
221
222 ## Efficiency
223
224 Which evaluation strategy you adopt has implications not only for
225 decidability and termination, but for efficiency.  (Later in the
226 course, it will have implications for the order in which side effects
227 occur.)
228
229 <pre>
230                      ((\x.w) ((\y.z) y))
231                         \           \
232                          \   ((\x.w) z)
233                           \       /
234                            \     /
235                             \   /
236                              \ /
237                               w
238 </pre>
239
240 If a function discards its argument, as `\x.w` does, it makes sense to
241 prioritize redexes in which that function serves as the head, rather
242 than wasting effort reducing the argument only to have the result of
243 all that work thrown away.  So in this situation, the strategy of
244 "always reduce the leftmost reducible lambda" is more efficient.
245
246 But:
247
248 <pre>
249                         ((\x.xx)((\y.y) z))
250                           /       \
251      (((\y.y) z)((\y.y) z)         ((\x.xx) z)
252         /         |                  /
253        /          (((\y.y)z)z)      /
254       /              |             /
255      /               |            /
256     /                |           /
257     (z ((\y.y)z))    |          /
258          \           |         /
259           -----------.---------
260                      |
261                      zz
262 </pre>
263
264 This time, the leftmost function `\x.xx` copies its argument.
265 If we reduce the rightmost lambda first (rightmost branch of the
266 diagram), the argument is already simplified before we do the
267 copying.  We arrive at the normal form (i.e., the form that cannot be
268 further reduced) in two steps.
269
270 But if we reduce the rightmost lambda first (the two leftmost branches
271 of the diagram), we copy the argument before it has been evaluated.
272 In effect, when we copy the unreduced argument, we double the amount
273 of work we need to do to deal with that argument.
274
275 So when the function copies its argument, the "always reduce the
276 rightmost reducible lambda" is more efficient.
277
278 So evaluation strategies have a strong effect on how many reduction
279 steps it takes to arrive at a stopping point (e.g., normal form).
280
281 ## Side-effects
282
283 In the systems we're currently working in, there are no side-effects. (Though the possibility of non-terminating computations like `ω ω` has some similarities to side-effects.)
284
285 When we later consider systems where the evaluation of some expressions *does* have side-effects, then the choice of evaluation strategy will make a big difference to which side-effects occur, and in what order.