should be more-or-less ready
[lambda.git] / exercises / assignment7_answers.mdwn
1 [[!toc]]
2
3 ## Evaluation order in Combinatory Logic
4
5 1. Give a term that the lazy evaluators (either [[the Haskell
6 evaluator|code/ski_evaluator.hs]], or the lazy version of [[the OCaml
7 evaluator|code/ski_evaluator.ml]]) do not evaluate all the way to a
8 normal form, that is, that contains a redex somewhere inside of it after
9 it has been reduced.
10
11     ANSWER
12
13 2. One of the [[criteria we established for classifying reduction
14 strategies|topics/week3_evaluation_order]] strategies is whether they
15 reduce subterms hidden under lambdas.  That is, for a term like
16 `(\x y. x z) (\x. x)`, do we reduce to `\y.(\x.x) z` and stop, or do
17 we reduce further to `\y.z`?  Explain what the corresponding question
18 would be for CL. Using the eager version of the OCaml CL evaluator (`reduce_try2`),
19 prove that the evaluator does reduce terms inside of at least
20 some "functional" CL terms.  Then provide a modified evaluator
21 that does not perform reductions in those positions. (Just give the
22 modified version of your recursive reduction function.)
23
24     ANSWER
25
26
27 ## Evaluation in the untyped lambda calculus: substitute-and-repeat
28
29 Having sketched the issues with a discussion of Combinatory Logic,
30 we're going to begin to construct an evaluator for a simple language
31 that includes lambda abstraction.  In this problem set, we're going to
32 work through the issues twice: once with a function that does
33 substitution in the obvious way, and keeps reducing-and-repeating until
34 there are no more eligible redexes. You'll see it's somewhat
35 complicated.  The complications come from the need to worry about
36 variable capture. (Seeing these complications should give you an
37 inkling of why we presented the evaluation order discussion using
38 Combinatory Logic, since we don't need to worry about variables in
39 CL.)
40
41 We're not going to ask you to write the entire program yourself.
42 Instead, we're going to give you almost the complete program, with a few gaps
43 in it that you have to complete. You have to understand enough to
44 add the last pieces to make the program function.
45
46 You can find the skeleton code [[here|/code/untyped_evaluator.ml]].
47
48 The first place you need to add code is in the `free_in` function. You already
49 wrote such a function [[in a previous homework|exercises/assignment5-6#occurs_free]], so this
50 part should be easy. The intended behavior is for the function to return results
51 like this:
52
53     # free_in "x" (App (Lambda("x, Var "x"), Var "x"));;
54     - : bool = true
55
56 The second place you need to add code is in the `reduce_head_once` function. As we
57 explain in the code comments, this is similar to the `reduce_if_redex` function in the
58 combinatory logic interpreters. Three of the clauses near the end of this function are incomplete.
59
60 As we explain in the code comments, this interpreter uses an eager/call-by-value reduction
61 strategy. What are its other evaluation order properties? Does it perform beta-reduction
62 underneath lambdas? Does it perform eta-reduction?
63
64 COMPLETED CODE (for this problem and next) IS AVAILABLE [[HERE|/code/untyped_evaluator_complete.ml]].
65
66
67 ## Evaluation in the untyped lambda calculus: environments
68
69 The previous interpreter strategy is nice because it corresponds so closely to the
70 reduction rules we give when specifying our lambda calculus. (Including
71 specifying evaluation order, which redexes it's allowed to reduce, and
72 so on.) But keeping track of free and bound variables, computing fresh
73 variables when needed, that's all a pain.
74
75 Here's a better strategy. Instead of keeping all of the information
76 about which variables have been bound or are still free implicitly
77 inside of the terms, we'll keep a separate scorecard, which we will call an "environment".  This is a
78 familiar strategy for philosophers of language and for linguists,
79 since it amounts to evaluating terms relative to an assignment
80 function. The difference between the substitute-and-repeat approach
81 above, and this approach, is one huge step towards monads.
82
83 The skeleton code for this is at the [[same link as before|/code/untyped_evaluator.ml]].
84 This part of the exercise is the "VB" part of that code.
85
86 COMPLETED CODE IS AVAILABLE [[HERE|/code/untyped_evaluator_complete.ml]] (same link as above).
87
88
89 You'll see that in the `eval` function, a new kind of value `Closure (ident) (term) (env)`
90 is used. What's that about?
91
92 [[Read about Closures here.|/topics/week7_environments_and_closures]]
93
94
95 So that's what's going on with those `Closure`s. In the simple code we gave you to work with, we just made these another clause in the `term` datatype. That's really not correct. `Closure`s aren't terms. The syntax for our language doesn't have any constituents that get parsed into `Closure`s. `Closure`s are only created *during the course of evaluating terms*: specifically, when a variable gets bound to an abstract, which may itself contain variables that are locally free (not bound by the abstract itself). So really we should have two datatypes, one for terms, and another for the *results* (sometimes called "values") that terms can evaluate to. `Closure`s are results, but they aren't terms. (In later weeks, we will see more examples of results that aren't terms, but can only be generated during the course of a computation.) `App`s are terms, but not results. If we had primitive numbers or other constants in our language, they might be both terms and results. In the fuller code from which your homework is simplified, this is how the types are in fact defined. But it makes things more complicated. So to keep things simple for the homework, we just pretended like `Closure`s were a new, exotic kind of `term`.
96
97 In any case, now you know what's going on with the `Closure`s, and you should be able to complete the missing pieces of the `eval` function in the code skeleton linked above.
98
99 If you've completed all the missing parts correctly (there are six gaps for the previous stage of the homework, and two gaps for this stage), then you should be able to compile the code skeleton, and use it as described in the comments at the start of the code.
100
101
102 ## Fuller interpreter
103
104 We've also prepared [[a fuller version of the interpreter, that has user-friendly input
105 and printing of results|/topics/week7_untyped_evaluator]]. It
106 will be easiest for you to understand that code if you've
107 completed the gaps in the simplified skeleton linked above.
108
109 There's nothing you need to do with this; it's just for you to play with. If you're interested,
110 you can compare the code you completed for the previous two segments of the homework
111 to the (only moderately more complex) code in the `engine.ml` file of this fuller program.
112
113 ## Monads
114
115 Mappables (functors), MapNables (applicative functors), and Monads
116 (composables) are ways of lifting computations from unboxed types into
117 boxed types.  Here, a "boxed type" is a type function with one unsaturated
118 hole (which may have several occurrences, as in `(α,α) tree`). We can think of the box type
119 as a function from a type to a type.
120
121 Recall that a monad requires a singleton function <code>⇧ (\* mid \*) : P-> <u>P</u></code>, and a
122 composition operator like <code>&gt;=&gt; : (P-><u>Q</u>) -> (Q-><u>R</u>) -> (P-><u>R</u>)</code>.
123
124 As we said in the notes, we'll move freely back and forth between using `>=>` and using `<=<` (aka `mcomp`), which
125 is just `>=>` with its arguments flipped. `<=<` has the virtue that it corresponds more
126 closely to the ordinary mathematical symbol `○`. But `>=>` has the virtue
127 that its types flow more naturally from left to right.
128
129 Anyway, `mid`/`⇧` and (let's say) `<=<` have to obey the Monad Laws:
130
131     ⇧ <=< k == k
132     k <=< ⇧ == k 
133     j <=< (k <=< l) == (j <=< k) <=< l
134
135 For example, the Identity monad has the identity function `I` for `⇧`
136 and ordinary function composition `○` for `<=<`.  It is easy to prove
137 that the laws hold for any terms `j`, `k`, and `l` whose types are
138 suitable for `⇧` and `<=<`:
139
140     ⇧ <=< k == I ○ k == \p. I (k p) ~~> \p. k p ~~> k
141     k <=< ⇧ == k ○ I == \p. k (I p) ~~> \p. k p ~~> k
142
143     (j <=< k) <=< l == (\p. j (k p)) ○ l == \q. (\p. j (k p)) (l q) ~~> \q. j (k (l q))
144     j <=< (k <=< l) == j ○ (k ○ l) == j ○ (\p. k (l p)) == \q. j ((\p. k (l p)) q) ~~> \q. j (k (l q))
145
146 1.  On a number of occasions, we've used the Option/Maybe type to make our
147 conceptual world neat and tidy (for instance, think of [[our discussion
148 of Kaplan's Plexy|topics/week6_plexy]]).  As we learned in class, there is a natural monad
149 for the Option type. Using the vocabulary of OCaml, let's say that
150 `'a option` is the type of a boxed `'a`, whatever type `'a` is.
151 More specifically,
152
153         type 'a option = None | Some 'a
154
155     (If you have trouble keeping straight what is the OCaml terminology for this and what is the Haskell terminology, don't worry, we do too.)
156
157     Now the obvious singleton for the Option monad is `\p. Some p`.  Give
158 (or reconstruct) either of the composition operators `>=>` or `<=<`.
159 Show that your composition operator obeys the Monad Laws.
160
161     ANSWER
162
163 2.  Do the same with lists.  That is, given an arbitrary type
164 `'a`, let the boxed type be `['a]` or `'a list`, that is, lists of values of type `'a`.  The `⇧`
165 is the singleton function `\p. [p]`, and the composition operator is:
166
167         let (>=>) (j : 'a -> 'b list) (k : 'b -> 'c list) : 'a -> 'c list =
168           fun a -> List.flatten (List.map k (j a))
169
170     For example:
171
172         let j a = [a; a+1];;
173         let k b = [b*b; b+b];;
174         (j >=> k) 7
175         (* which OCaml evaluates to:
176         - : int list = [49; 14; 64; 16]
177         *)
178
179     Show that these obey the Monad Laws.
180
181     ANSWER