edit
[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 we can deduce the unit and the bind:
28
29     let r_unit (x : 'a) : 'a reader = fun (e : env) -> x
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.  So 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 deduce the correct `bind` function as follows:
41
42     let r_bind (u : 'a reader) (f : 'a -> 'b reader) : ('b reader) =
43
44 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
59 an environment.  So we end up as follows:
60
61     r_bind (u : 'a reader) (f : 'a -> 'b reader) : ('b reader) = f (u e) e         
62
63 And we're done.
64
65 [This bind 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.  We somehow intuit that we want to use
71 the following type constructor:
72
73     type 'a state = store -> ('a, store)
74
75 So our unit is naturally
76
77     let s_unit (x : 'a) : ('a state) = fun (s : store) -> (x, s)
78
79 And we deduce the bind in a way similar to the reasoning given above.
80 First, we need to apply `f` to the contents of the `u` box:
81
82     let s_bind (u : 'a state) (f : 'a -> 'b state) : 'b state = 
83
84 But unlocking the `u` box is a little more complicated.  As before, we
85 need to posit a state `s` that we can apply `u` to.  Once we do so,
86 however, we won't have an `'a`, we'll have a pair whose first element
87 is an `'a`.  So we have to unpack the pair:
88
89         ... let (a, s') = u s in ... (f a) ...
90
91 Abstracting over the `s` and adjusting the types gives the result:
92
93     let s_bind (u : 'a state) (f : 'a -> 'b state) : 'b state = 
94       fun (s : store) -> let (a, s') = u s in f a s'
95
96 The **Option Monad** doesn't follow the same pattern so closely, so we
97 won't pause to explore it here, though conceptually its unit and bind
98 follow just as naturally from its type constructor.
99
100 Our other familiar monad is the **List Monad**, which we were told
101 looks like this:
102
103     type 'a list = ['a];;
104     l_unit (x : 'a) = [x];;
105     l_bind u f = List.concat (List.map f u);;
106
107 Recall that `List.map` take a function and a list and returns the
108 result to applying the function to the elements of the list:
109
110     List.map (fun i -> [i;i+1]) [1;2] ~~> [[1; 2]; [2; 3]]
111
112 and List.concat takes a list of lists and erases the embdded list
113 boundaries:
114
115     List.concat [[1; 2]; [2; 3]] ~~> [1; 2; 2; 3]
116
117 And sure enough, 
118
119     l_bind [1;2] (fun i -> [i, i+1]) ~~> [1; 2; 2; 3]
120
121 But where is the reasoning that led us to this unit and bind?
122 And what is the type `['a]`?  Magic.
123
124 So let's indulge ourselves in a completely useless digression and see
125 if we can gain some insight into the details of the List monad.  Let's
126 choose type constructor that we can peer into, using some of the
127 technology we built up so laboriously during the first half of the
128 course.  We're going to use type 3 lists, partly because we know
129 they'll give the result we want, but also because they're the coolest.
130 These were the lists that made lists look like Church numerals with
131 extra bits embdded in them:
132
133     empty list:                fun f z -> z
134     list with one element:     fun f z -> f 1 z
135     list with two elements:    fun f z -> f 2 (f 1 z)
136     list with three elements:  fun f z -> f 3 (f 2 (f 1 z))
137
138 and so on.  To save time, we'll let the OCaml interpreter infer the
139 principle types of these functions (rather than deducing what the
140 types should be):
141
142 <pre>
143 # fun f z -> z;;
144 - : 'a -> 'b -> 'b = <fun>
145 # fun f z -> f 1 z;;
146 - : (int -> 'a -> 'b) -> 'a -> 'b = <fun>
147 # fun f z -> f 2 (f 1 z);;
148 - : (int -> 'a -> 'a) -> 'a -> 'a = <fun>
149 # fun f z -> f 3 (f 2 (f 1 z))
150 - : (int -> 'a -> 'a) -> 'a -> 'a = <fun>
151 </pre>
152
153 Finally, we're getting consistent principle types, so we can stop.
154 These types should remind you of the simply-typed lambda calculus
155 types for Church numerals (`(o -> o) -> o -> o`) with one extra bit
156 thrown in (in this case, an int).
157
158 So here's our type constructor for our hand-rolled lists:
159
160     type 'a list' = (int -> 'a -> 'a) -> 'a -> 'a
161
162 Generalizing to lists that contain any kind of element (not just
163 ints), we have
164
165     type ('a, 'b) list' = ('a -> 'b -> 'b) -> 'b -> 'b
166
167 So an `('a, 'b) list'` is a list containing elements of type `'a`,
168 where `'b` is the type of some part of the plumbing.  This is more
169 general than an ordinary OCaml list, but we'll see how to map them
170 into OCaml lists soon.  We don't need to fully grasp the role of the `'b`'s
171 in order to proceed to build a monad:
172
173     l'_unit (x : 'a) : ('a, 'b) list = fun x -> fun f z -> f x z
174
175 No problem.  Arriving at bind is a little more complicated, but
176 exactly the same principles apply, you just have to be careful and
177 systematic about it.
178
179     l'_bind (u : ('a,'b) list') (f : 'a -> ('c, 'd) list') : ('c, 'd) list'  = ...
180
181 Unfortunately, we'll need to spell out the types:
182
183     l'_bind (u : ('a -> 'b -> 'b) -> 'b -> 'b)
184             (f : 'a -> ('c -> 'd -> 'd) -> 'd -> 'd)
185             : ('c -> 'd -> 'd) -> 'd -> 'd = ...
186
187 It's a rookie mistake to quail before complicated types.  You should
188 be no more intimiated by complex types than by a linguistic tree with
189 deeply embedded branches: complex structure created by repeated
190 application of simple rules.
191
192 As usual, we need to unpack the `u` box.  Examine the type of `u`.
193 This time, `u` will only deliver up its contents if we give `u` as an
194 argument a function expecting an `'a`.  Once that argument is applied
195 to an object of type `'a`, we'll have what we need.  Thus:
196
197       .... u (fun (a : 'a) -> ... (f a) ... ) ...
198
199 In order for `u` to have the kind of argument it needs, we have to
200 adjust `(f a)` (which has type `('c -> 'd -> 'd) -> 'd -> 'd`) in
201 order to deliver something of type `'b -> 'b`.  The easiest way is to
202 alias `'d` to `'b`, and provide `(f a)` with an argument of type `'c
203 -> 'b -> 'b`.  Thus:
204
205     l'_bind (u : ('a -> 'b -> 'b) -> 'b -> 'b)
206             (f : 'a -> ('c -> 'b -> 'b) -> 'b -> 'b)
207             : ('c -> 'b -> 'b) -> 'b -> 'b = 
208       .... u (fun (a : 'a) -> f a k) ...
209
210 [Exercise: can you arrive at a fully general bind for this type
211 constructor, one that does not collapse `'d`'s with `'b`'s?]
212
213 As usual, we have to abstract over `k`, but this time, no further
214 adjustments are needed:
215
216     l'_bind (u : ('a -> 'b -> 'b) -> 'b -> 'b)
217             (f : 'a -> ('c -> 'b -> 'b) -> 'b -> 'b)
218             : ('c -> 'b -> 'b) -> 'b -> 'b = 
219       fun (k : 'c -> 'b -> 'b) -> u (fun (a : 'a) -> f a k)
220
221 You should carefully check to make sure that this term is consistent
222 with the typing.
223
224 Our theory is that this monad should be capable of exactly
225 replicating the behavior of the standard List monad.  Let's test:
226
227
228     l_bind [1;2] (fun i -> [i, i+1]) ~~> [1; 2; 2; 3]
229
230     l'_bind (fun f z -> f 1 (f 2 z)) 
231             (fun i -> fun f z -> f i (f (i+1) z)) ~~> <fun>
232
233 Sigh.  OCaml won't show us our own list.  So we have to choose an `f`
234 and a `z` that will turn our hand-crafted lists into standard OCaml
235 lists, so that they will print out.
236
237         # let cons h t = h :: t;;  (* OCaml is stupid about :: *)
238         # l'_bind (fun f z -> f 1 (f 2 z)) 
239                           (fun i -> fun f z -> f i (f (i+1) z)) cons [];;
240         - : int list = [1; 2; 2; 3]
241
242 Ta da!
243
244 To bad this digression, though it ties together various
245 elements of the course, has *no relevance whatsoever* to the topic of
246 continuations...
247
248 Montague's PTQ treatment of DPs as generalized quantifiers
249 ----------------------------------------------------------
250
251 We've hinted that Montague's treatment of DPs as generalized
252 quantifiers embodies the spirit of continuations (see de Groote 2001,
253 Barker 2002 for lengthy discussion).  Let's see why.  
254
255 First, we'll need a type constructor.  As you probably know, 
256 Montague replaced individual-denoting determiner phrases (with type `e`)
257 with generalized quantifiers (with [extensional] type `(e -> t) -> t`.
258 In particular, the denotation of a proper name like *John*, which
259 might originally denote a object `j` of type `e`, came to denote a
260 generalized quantifier `fun pred -> pred j` of type `(e -> t) -> t`.
261 Let's write a general function that will map individuals into their
262 corresponding generalized quantifier:
263
264    gqize (x : e) = fun (p : e -> t) -> p x
265
266 This function wraps up an individual in a fancy box.  That is to say,
267 we are in the presence of a monad.  The type constructor, the unit and
268 the bind follow naturally.  We've done this enough times that we won't
269 belabor the construction of the bind function, the derivation is
270 similar to the List monad just given:
271
272         type 'a continuation = ('a -> 'b) -> 'b
273         c_unit (x : 'a) = fun (p : 'a -> 'b) -> p x
274         c_bind (u : ('a -> 'b) -> 'b) (f : 'a -> ('c -> 'd) -> 'd) : ('c -> 'd) -> 'd =
275           fun (k : 'a -> 'b) -> u (fun (x : 'a) -> f x k)
276
277 How similar is it to the List monad?  Let's examine the type
278 constructor and the terms from the list monad derived above:
279
280     type ('a, 'b) list' = ('a -> 'b -> 'b) -> 'b -> 'b
281     l'_unit x = fun f -> f x                 
282     l'_bind u f = fun k -> u (fun x -> f x k)
283
284 (We performed a sneaky but valid eta reduction in the unit term.)
285
286 The unit and the bind for the Montague continuation monad and the
287 homemade List monad are the same terms!  In other words, the behavior
288 of the List monad and the behavior of the continuations monad are
289 parallel in a deep sense.  To emphasize the parallel, we can
290 instantiate the type of the list' monad using the OCaml list type:
291
292     type 'a c_list = ('a -> 'a list) -> 'a list
293
294 Have we really discovered that lists are secretly continuations?  Or
295 have we merely found a way of simulating lists using list
296 continuations?  Both perspectives are valid, and we can use our
297 intuitions about the list monad to understand continuations, and vice
298 versa (not to mention our intuitions about primitive recursion in
299 Church numerals too).  The connections will be expecially relevant
300 when we consider indefinites and Hamblin semantics on the linguistic
301 side, and non-determinism on the list monad side.
302
303 Refunctionalizing zippers
304 -------------------------
305
306 Manipulating trees with monads
307 ------------------------------
308
309 This thread develops an idea based on a detailed suggestion of Ken
310 Shan's.  We'll build a series of functions that operate on trees,
311 doing various things, including replacing leaves, counting nodes, and
312 converting a tree to a list of leaves.  The end result will be an
313 application for continuations.
314
315 From an engineering standpoint, we'll build a tree transformer that
316 deals in monads.  We can modify the behavior of the system by swapping
317 one monad for another.  (We've already seen how adding a monad can add
318 a layer of funtionality without disturbing the underlying system, for
319 instance, in the way that the reader monad allowed us to add a layer
320 of intensionality to an extensional grammar, but we have not yet seen
321 the utility of replacing one monad with other.)
322
323 First, we'll be needing a lot of trees during the remainder of the
324 course.  Here's a type constructor for binary trees:
325
326     type 'a tree = Leaf of 'a | Node of ('a tree * 'a tree)
327
328 These are trees in which the internal nodes do not have labels.  [How
329 would you adjust the type constructor to allow for labels on the
330 internal nodes?]
331
332 We'll be using trees where the nodes are integers, e.g.,
333
334
335 <pre>
336 let t1 = Node ((Node ((Leaf 2), (Leaf 3))),
337                (Node ((Leaf 5),(Node ((Leaf 7),
338                                       (Leaf 11))))))
339
340     .
341  ___|___
342  |     |
343  .     .
344 _|__  _|__
345 |  |  |  |
346 2  3  5  .
347         _|__
348         |  |
349         7  11
350 </pre>
351
352 Our first task will be to replace each leaf with its double:
353
354 <pre>
355 let rec treemap (newleaf:'a -> 'b) (t:'a tree):('b tree) =
356   match t with Leaf x -> Leaf (newleaf x)
357              | Node (l, r) -> Node ((treemap newleaf l),
358                                     (treemap newleaf r));;
359 </pre>
360 `treemap` takes a function that transforms old leaves into new leaves, 
361 and maps that function over all the leaves in the tree, leaving the
362 structure of the tree unchanged.  For instance:
363
364 <pre>
365 let double i = i + i;;
366 treemap double t1;;
367 - : int tree =
368 Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
369
370     .
371  ___|____
372  |      |
373  .      .
374 _|__  __|__
375 |  |  |   |
376 4  6  10  .
377         __|___
378         |    |
379         14   22
380 </pre>
381
382 We could have built the doubling operation right into the `treemap`
383 code.  However, because what to do to each leaf is a parameter, we can
384 decide to do something else to the leaves without needing to rewrite
385 `treemap`.  For instance, we can easily square each leaf instead by
386 supplying the appropriate `int -> int` operation in place of `double`:
387
388 <pre>
389 let square x = x * x;;
390 treemap square t1;;
391 - : int tree =ppp
392 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
393 </pre>
394
395 Note that what `treemap` does is take some global, contextual
396 information---what to do to each leaf---and supplies that information
397 to each subpart of the computation.  In other words, `treemap` has the
398 behavior of a reader monad.  Let's make that explicit.  
399
400 In general, we're on a journey of making our treemap function more and
401 more flexible.  So the next step---combining the tree transducer with
402 a reader monad---is to have the treemap function return a (monadized)
403 tree that is ready to accept any `int->int` function and produce the
404 updated tree.
405
406 \tree (. (. (f2) (f3))(. (f5) (.(f7)(f11))))
407 <pre>
408 \f    .
409   ____|____
410   |       |
411   .       .
412 __|__   __|__
413 |   |   |   |
414 f2  f3  f5  .
415           __|___
416           |    |
417           f7  f11
418 </pre>
419
420 That is, we want to transform the ordinary tree `t1` (of type `int
421 tree`) into a reader object of type `(int->int)-> int tree`: something 
422 that, when you apply it to an `int->int` function returns an `int
423 tree` in which each leaf `x` has been replaced with `(f x)`.
424
425 With previous readers, we always knew which kind of environment to
426 expect: either an assignment function (the original calculator
427 simulation), a world (the intensionality monad), an integer (the
428 Jacobson-inspired link monad), etc.  In this situation, it will be
429 enough for now to expect that our reader will expect a function of
430 type `int->int`.
431
432 <pre>
433 type 'a reader = (int->int) -> 'a;;  (* mnemonic: e for environment *)
434 let reader_unit (x:'a): 'a reader = fun _ -> x;;
435 let reader_bind (u: 'a reader) (f:'a -> 'c reader):'c reader = fun e -> f (u e) e;;
436 </pre>
437
438 It's easy to figure out how to turn an `int` into an `int reader`:
439
440 <pre>
441 let int2int_reader (x:'a): 'b reader = fun (op:'a -> 'b) -> op x;;
442 int2int_reader 2 (fun i -> i + i);;
443 - : int = 4
444 </pre>
445
446 But what do we do when the integers are scattered over the leaves of a
447 tree?  A binary tree is not the kind of thing that we can apply a
448 function of type `int->int` to.
449
450 <pre>
451 let rec treemonadizer (f:'a -> 'b reader) (t:'a tree):('b tree) reader =
452   match t with Leaf x -> reader_bind (f x) (fun x' -> reader_unit (Leaf x'))
453              | Node (l, r) -> reader_bind (treemonadizer f l) (fun x ->
454                                 reader_bind (treemonadizer f r) (fun y ->
455                                   reader_unit (Node (x, y))));;
456 </pre>
457
458 This function says: give me a function `f` that knows how to turn
459 something of type `'a` into an `'b reader`, and I'll show you how to 
460 turn an `'a tree` into an `'a tree reader`.  In more fanciful terms, 
461 the `treemonadizer` function builds plumbing that connects all of the
462 leaves of a tree into one connected monadic network; it threads the
463 monad through the leaves.
464
465 <pre>
466 # treemonadizer int2int_reader t1 (fun i -> i + i);;
467 - : int tree =
468 Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
469 </pre>
470
471 Here, our environment is the doubling function (`fun i -> i + i`).  If
472 we apply the very same `int tree reader` (namely, `treemonadizer
473 int2int_reader t1`) to a different `int->int` function---say, the
474 squaring function, `fun i -> i * i`---we get an entirely different
475 result:
476
477 <pre>
478 # treemonadizer int2int_reader t1 (fun i -> i * i);;
479 - : int tree =
480 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
481 </pre>
482
483 Now that we have a tree transducer that accepts a monad as a
484 parameter, we can see what it would take to swap in a different monad.
485 For instance, we can use a state monad to count the number of nodes in
486 the tree.
487
488 <pre>
489 type 'a state = int -> 'a * int;;
490 let state_unit x i = (x, i+.5);;
491 let state_bind u f i = let (a, i') = u i in f a (i'+.5);;
492 </pre>
493
494 Gratifyingly, we can use the `treemonadizer` function without any
495 modification whatsoever, except for replacing the (parametric) type
496 `reader` with `state`:
497
498 <pre>
499 let rec treemonadizer (f:'a -> 'b state) (t:'a tree):('b tree) state =
500   match t with Leaf x -> state_bind (f x) (fun x' -> state_unit (Leaf x'))
501              | Node (l, r) -> state_bind (treemonadizer f l) (fun x ->
502                                 state_bind (treemonadizer f r) (fun y ->
503                                   state_unit (Node (x, y))));;
504 </pre>
505
506 Then we can count the number of nodes in the tree:
507
508 <pre>
509 # treemonadizer state_unit t1 0;;
510 - : int tree * int =
511 (Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11))), 13)
512
513     .
514  ___|___
515  |     |
516  .     .
517 _|__  _|__
518 |  |  |  |
519 2  3  5  .
520         _|__
521         |  |
522         7  11
523 </pre>
524
525 Notice that we've counted each internal node twice---it's a good
526 excerice to adjust the code to count each node once.
527
528 One more revealing example before getting down to business: replacing
529 `state` everywhere in `treemonadizer` with `list` gives us
530
531 <pre>
532 # treemonadizer (fun x -> [[x; square x]]) t1;;
533 - : int list tree list =
534 [Node
535   (Node (Leaf [2; 4], Leaf [3; 9]),
536    Node (Leaf [5; 25], Node (Leaf [7; 49], Leaf [11; 121])))]
537 </pre>
538
539 Unlike the previous cases, instead of turning a tree into a function
540 from some input to a result, this transformer replaces each `int` with
541 a list of `int`'s.
542
543 Now for the main point.  What if we wanted to convert a tree to a list
544 of leaves?  
545
546 <pre>
547 type ('a, 'r) continuation = ('a -> 'r) -> 'r;;
548 let continuation_unit x c = c x;;
549 let continuation_bind u f c = u (fun a -> f a c);;
550
551 let rec treemonadizer (f:'a -> ('b, 'r) continuation) (t:'a tree):(('b tree), 'r) continuation =
552   match t with Leaf x -> continuation_bind (f x) (fun x' -> continuation_unit (Leaf x'))
553              | Node (l, r) -> continuation_bind (treemonadizer f l) (fun x ->
554                                 continuation_bind (treemonadizer f r) (fun y ->
555                                   continuation_unit (Node (x, y))));;
556 </pre>
557
558 We use the continuation monad described above, and insert the
559 `continuation` type in the appropriate place in the `treemonadizer` code.
560 We then compute:
561
562 <pre>
563 # treemonadizer (fun a c -> a :: (c a)) t1 (fun t -> []);;
564 - : int list = [2; 3; 5; 7; 11]
565 </pre>
566
567 We have found a way of collapsing a tree into a list of its leaves.
568
569 The continuation monad is amazingly flexible; we can use it to
570 simulate some of the computations performed above.  To see how, first
571 note that an interestingly uninteresting thing happens if we use the
572 continuation unit as our first argument to `treemonadizer`, and then
573 apply the result to the identity function:
574
575 <pre>
576 # treemonadizer continuation_unit t1 (fun x -> x);;
577 - : int tree =
578 Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11)))
579 </pre>
580
581 That is, nothing happens.  But we can begin to substitute more
582 interesting functions for the first argument of `treemonadizer`:
583
584 <pre>
585 (* Simulating the tree reader: distributing a operation over the leaves *)
586 # treemonadizer (fun a c -> c (square a)) t1 (fun x -> x);;
587 - : int tree =
588 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
589
590 (* Simulating the int list tree list *)
591 # treemonadizer (fun a c -> c [a; square a]) t1 (fun x -> x);;
592 - : int list tree =
593 Node
594  (Node (Leaf [2; 4], Leaf [3; 9]),
595   Node (Leaf [5; 25], Node (Leaf [7; 49], Leaf [11; 121])))
596
597 (* Counting leaves *)
598 # treemonadizer (fun a c -> 1 + c a) t1 (fun x -> 0);;
599 - : int = 5
600 </pre>
601
602 We could simulate the tree state example too, but it would require
603 generalizing the type of the continuation monad to 
604
605     type ('a -> 'b -> 'c) continuation = ('a -> 'b) -> 'c;;
606