edc3359d66015d9a0547d02ba7b35c644ff726cf
[lambda.git] / zipper-lists-continuations.mdwn
1 Today we're going to encounter continuations.  We're going to come at
2 them from three different directions, and each time we're going to end
3 up at the same place: a particular monad, which we'll call the
4 continuation monad.
5
6 The three approches are:
7
8 [[!toc]]
9
10 Rethinking the list monad
11 -------------------------
12
13 To construct a monad, the key element is to settle on a type
14 constructor, and the monad naturally follows from that.  We'll remind
15 you of some examples of how monads follow from the type constructor in
16 a moment.  This will involve some review of familair material, but
17 it's worth doing for two reasons: it will set up a pattern for the new
18 discussion further below, and it will tie together some previously
19 unconnected elements of the course (more specifically, version 3 lists
20 and monads).
21
22 For instance, take the **Reader Monad**.  Once we decide that the type
23 constructor is
24
25     type 'a reader = env -> 'a
26
27 then the choice of unit and bind is natural:
28
29     let r_unit (a : 'a) : 'a reader = fun (e : env) -> a
30
31 Since the type of an `'a reader` is `env -> 'a` (by definition),
32 the type of the `r_unit` function is `'a -> env -> 'a`, which is a
33 specific case of the type of the *K* combinator.  It makes sense
34 that *K* is the unit for the reader monad.
35
36 Since the type of the `bind` operator is required to be
37
38     r_bind : ('a reader) -> ('a -> 'b reader) -> ('b reader)
39
40 We can reason our way to the correct `bind` function as follows. We start by declaring the type:
41
42     let r_bind (u : 'a reader) (f : 'a -> 'b reader) : ('b reader) =
43
44 Now we have to open up the `u` box and get out the `'a` object in order to
45 feed it to `f`.  Since `u` is a function from environments to
46 objects of type `'a`, the way we open a box in this monad is
47 by applying it to an environment:
48
49         ... f (u e) ...
50
51 This subexpression types to `'b reader`, which is good.  The only
52 problem is that we invented an environment `e` that we didn't already have ,
53 so we have to abstract over that variable to balance the books:
54
55         fun e -> f (u e) ...
56
57 This types to `env -> 'b reader`, but we want to end up with `env ->
58 'b`.  Once again, the easiest way to turn a `'b reader` into a `'b` is to apply it to an environment.  So we end up as follows:
59
60     r_bind (u : 'a reader) (f : 'a -> 'b reader) : ('b reader) =
61                 f (u e) e         
62
63 And we're done. This gives us a bind function of the right type. We can then check whether, in combination with the unit function we chose, it satisfies the monad laws, and behaves in the way we intend. And it does.
64
65 [The bind we cite here is a condensed version of the careful `let a = u e in ...`
66 constructions we provided in earlier lectures.  We use the condensed
67 version here in order to emphasize similarities of structure across
68 monads.]
69
70 The **State Monad** is similar.  Once we've decided to use the following type constructor:
71
72     type 'a state = store -> ('a, store)
73
74 Then our unit is naturally:
75
76     let s_unit (x : 'a) : ('a state) = fun (s : store) -> (x, s)
77
78 And we can reason our way to the bind function in a way similar to the reasoning given above. First, we need to apply `f` to the contents of the `u` box:
79
80     let s_bind (u : 'a state) (f : 'a -> 'b state) : 'b state = 
81                 ... f (...) ...
82
83 But unlocking the `u` box is a little more complicated.  As before, we
84 need to posit a state `s` that we can apply `u` to.  Once we do so,
85 however, we won't have an `'a`, we'll have a pair whose first element
86 is an `'a`.  So we have to unpack the pair:
87
88         ... let (a, s') = u s in ... (f a) ...
89
90 Abstracting over the `s` and adjusting the types gives the result:
91
92         let s_bind (u : 'a state) (f : 'a -> 'b state) : 'b state = 
93                 fun (s : store) -> let (a, s') = u s in f a s'
94
95 The **Option/Maybe Monad** doesn't follow the same pattern so closely, so we
96 won't pause to explore it here, though conceptually its unit and bind
97 follow just as naturally from its type constructor.
98
99 Our other familiar monad is the **List Monad**, which we were told
100 looks like this:
101
102     type 'a list = ['a];;
103     l_unit (x : 'a) = [x];;
104     l_bind u f = List.concat (List.map f u);;
105
106 Recall that `List.map` take a function and a list and returns the
107 result to applying the function to the elements of the list:
108
109     List.map (fun i -> [i;i+1]) [1;2] ~~> [[1; 2]; [2; 3]]
110
111 and List.concat takes a list of lists and erases the embdded list
112 boundaries:
113
114     List.concat [[1; 2]; [2; 3]] ~~> [1; 2; 2; 3]
115
116 And sure enough, 
117
118     l_bind [1;2] (fun i -> [i, i+1]) ~~> [1; 2; 2; 3]
119
120 But where is the reasoning that led us to this unit and bind?
121 And what is the type `['a]`?  Magic.
122
123 So let's indulge ourselves in a completely useless digression and see
124 if we can gain some insight into the details of the List monad.  Let's
125 choose type constructor that we can peer into, using some of the
126 technology we built up so laboriously during the first half of the
127 course.  We're going to use type 3 lists, partly because we know
128 they'll give the result we want, but also because they're the coolest.
129 These were the lists that made lists look like Church numerals with
130 extra bits embdded in them:
131
132     empty list:                fun f z -> z
133     list with one element:     fun f z -> f 1 z
134     list with two elements:    fun f z -> f 2 (f 1 z)
135     list with three elements:  fun f z -> f 3 (f 2 (f 1 z))
136
137 and so on.  To save time, we'll let the OCaml interpreter infer the
138 principle types of these functions (rather than deducing what the
139 types should be):
140
141         # fun f z -> z;;
142         - : 'a -> 'b -> 'b = <fun>
143         # fun f z -> f 1 z;;
144         - : (int -> 'a -> 'b) -> 'a -> 'b = <fun>
145         # fun f z -> f 2 (f 1 z);;
146         - : (int -> 'a -> 'a) -> 'a -> 'a = <fun>
147         # fun f z -> f 3 (f 2 (f 1 z))
148         - : (int -> 'a -> 'a) -> 'a -> 'a = <fun>
149
150 We can see what the consistent, general principle types are at the end, so we
151 can stop. These types should remind you of the simply-typed lambda calculus
152 types for Church numerals (`(o -> o) -> o -> o`) with one extra bit thrown in
153 (in this case, an int).
154
155 So here's our type constructor for our hand-rolled lists:
156
157     type 'b list' = (int -> 'b -> 'b) -> 'b -> 'b
158
159 Generalizing to lists that contain any kind of element (not just
160 ints), we have
161
162     type ('a, 'b) list' = ('a -> 'b -> 'b) -> 'b -> 'b
163
164 So an `('a, 'b) list'` is a list containing elements of type `'a`,
165 where `'b` is the type of some part of the plumbing.  This is more
166 general than an ordinary OCaml list, but we'll see how to map them
167 into OCaml lists soon.  We don't need to fully grasp the role of the `'b`'s
168 in order to proceed to build a monad:
169
170     l'_unit (x : 'a) : ('a, 'b) list = fun x -> fun f z -> f x z
171
172 No problem.  Arriving at bind is a little more complicated, but
173 exactly the same principles apply, you just have to be careful and
174 systematic about it.
175
176     l'_bind (u : ('a,'b) list') (f : 'a -> ('c, 'd) list') : ('c, 'd) list'  = ...
177
178 Unpacking the types gives:
179
180     l'_bind (u : ('a -> 'b -> 'b) -> 'b -> 'b)
181             (f : 'a -> ('c -> 'd -> 'd) -> 'd -> 'd)
182             : ('c -> 'd -> 'd) -> 'd -> 'd = ...
183
184 But it's a rookie mistake to quail before complicated types. You should
185 be no more intimiated by complex types than by a linguistic tree with
186 deeply embedded branches: complex structure created by repeated
187 application of simple rules.
188
189 As usual, we need to unpack the `u` box.  Examine the type of `u`.
190 This time, `u` will only deliver up its contents if we give `u` as an
191 argument a function expecting an `'a` and a `'b`. `u` will fold that function over its type `'a` members, and that's how we'll get the `'a`s we need. Thus:
192
193         ... u (fun (a : 'a) (b : 'b) -> ... f a ... ) ...
194
195 In order for `u` to have the kind of argument it needs, the `... (f a) ...` has to evaluate to a result of type `'b`. The easiest way to do this is to collapse (or "unify") the types `'b` and `'d`, with the result that `f a` will have type `('c -> 'b -> 'b) -> 'b -> 'b`. Let's postulate an argument `k` of type `('c -> 'b -> 'b)` and supply it to `(f a)`:
196
197         ... u (fun (a : 'a) (b : 'b) -> ... f a k ... ) ...
198
199 Now we have an argument `b` of type `'b`, so we can supply that to `(f a) k`, getting a result of type `'b`, as we need:
200
201         ... u (fun (a : 'a) (b : 'b) -> f a k b) ...
202
203 Now, we've used a `k` that we pulled out of nowhere, so we need to abstract over it:
204
205         fun (k : 'c -> 'b -> 'b) -> u (fun (a : 'a) (b : 'b) -> f a k b)
206
207 This whole expression has type `('c -> 'b -> 'b) -> 'b -> 'b`, which is exactly the type of a `('c, 'b) list'`. So we can hypothesize that we our bind is:
208
209     l'_bind (u : ('a -> 'b -> 'b) -> 'b -> 'b)
210             (f : 'a -> ('c -> 'b -> 'b) -> 'b -> 'b)
211             : ('c -> 'b -> 'b) -> 'b -> 'b = 
212       fun k -> u (fun a b -> f a k b)
213
214 That is a function of the right type for our bind, but to check whether it works, we have to verify it (with the unit we chose) against the monad laws, and reason whether it will have the right behavior.
215
216 Here's a way to persuade yourself that it will have the right behavior. First, it will be handy to eta-expand our `fun k -> u (fun a b -> f a k b)` to:
217
218       fun k z -> u (fun a b -> f a k b) z
219
220 Now let's think about what this does. It's a wrapper around `u`. In order to behave as the list which is the result of mapping `f` over each element of `u`, and then joining (`concat`ing) the results, this wrapper would have to accept arguments `k` and `z` and fold them in just the same way that the list which is the result of mapping `f` and then joining the results would fold them. Will it?
221
222 ... MORE...
223
224
225 Our theory is that this monad should be capable of exactly
226 replicating the behavior of the standard List monad.  Let's test:
227
228
229     l_bind [1;2] (fun i -> [i, i+1]) ~~> [1; 2; 2; 3]
230
231     l'_bind (fun f z -> f 1 (f 2 z)) 
232             (fun i -> fun f z -> f i (f (i+1) z)) ~~> <fun>
233
234 Sigh.  OCaml won't show us our own list.  So we have to choose an `f`
235 and a `z` that will turn our hand-crafted lists into standard OCaml
236 lists, so that they will print out.
237
238         # let cons h t = h :: t;;  (* OCaml is stupid about :: *)
239         # l'_bind (fun f z -> f 1 (f 2 z)) 
240                           (fun i -> fun f z -> f i (f (i+1) z)) cons [];;
241         - : int list = [1; 2; 2; 3]
242
243 Ta da!
244
245 To bad this digression, though it ties together various
246 elements of the course, has *no relevance whatsoever* to the topic of
247 continuations...
248
249 Montague's PTQ treatment of DPs as generalized quantifiers
250 ----------------------------------------------------------
251
252 We've hinted that Montague's treatment of DPs as generalized
253 quantifiers embodies the spirit of continuations (see de Groote 2001,
254 Barker 2002 for lengthy discussion).  Let's see why.  
255
256 First, we'll need a type constructor.  As you probably know, 
257 Montague replaced individual-denoting determiner phrases (with type `e`)
258 with generalized quantifiers (with [extensional] type `(e -> t) -> t`.
259 In particular, the denotation of a proper name like *John*, which
260 might originally denote a object `j` of type `e`, came to denote a
261 generalized quantifier `fun pred -> pred j` of type `(e -> t) -> t`.
262 Let's write a general function that will map individuals into their
263 corresponding generalized quantifier:
264
265    gqize (x : e) = fun (p : e -> t) -> p x
266
267 This function wraps up an individual in a fancy box.  That is to say,
268 we are in the presence of a monad.  The type constructor, the unit and
269 the bind follow naturally.  We've done this enough times that we won't
270 belabor the construction of the bind function, the derivation is
271 similar to the List monad just given:
272
273         type 'a continuation = ('a -> 'b) -> 'b
274         c_unit (x : 'a) = fun (p : 'a -> 'b) -> p x
275         c_bind (u : ('a -> 'b) -> 'b) (f : 'a -> ('c -> 'd) -> 'd) : ('c -> 'd) -> 'd =
276           fun (k : 'a -> 'b) -> u (fun (x : 'a) -> f x k)
277
278 How similar is it to the List monad?  Let's examine the type
279 constructor and the terms from the list monad derived above:
280
281     type ('a, 'b) list' = ('a -> 'b -> 'b) -> 'b -> 'b
282     l'_unit x = fun f -> f x                 
283     l'_bind u f = fun k -> u (fun x -> f x k)
284
285 (We performed a sneaky but valid eta reduction in the unit term.)
286
287 The unit and the bind for the Montague continuation monad and the
288 homemade List monad are the same terms!  In other words, the behavior
289 of the List monad and the behavior of the continuations monad are
290 parallel in a deep sense.  To emphasize the parallel, we can
291 instantiate the type of the list' monad using the OCaml list type:
292
293     type 'a c_list = ('a -> 'a list) -> 'a list
294
295 Have we really discovered that lists are secretly continuations?  Or
296 have we merely found a way of simulating lists using list
297 continuations?  Both perspectives are valid, and we can use our
298 intuitions about the list monad to understand continuations, and vice
299 versa (not to mention our intuitions about primitive recursion in
300 Church numerals too).  The connections will be expecially relevant
301 when we consider indefinites and Hamblin semantics on the linguistic
302 side, and non-determinism on the list monad side.
303
304 Refunctionalizing zippers
305 -------------------------
306