edits
[lambda.git] / zipper-lists-continuations.mdwn
1
2 [[!toc]]
3
4 Today we're going to encounter continuations.  We're going to come at
5 them from three different directions, and each time we're going to end
6 up at the same place: a particular monad, which we'll call the
7 continuation monad.
8
9 Much of this discussion benefited from detailed comments and
10 suggestions from Ken Shan.
11
12
13 Rethinking the list monad
14 -------------------------
15
16 To construct a monad, the key element is to settle on a type
17 constructor, and the monad naturally follows from that.  We'll remind
18 you of some examples of how monads follow from the type constructor in
19 a moment.  This will involve some review of familair material, but
20 it's worth doing for two reasons: it will set up a pattern for the new
21 discussion further below, and it will tie together some previously
22 unconnected elements of the course (more specifically, version 3 lists
23 and monads).
24
25 For instance, take the **Reader Monad**.  Once we decide that the type
26 constructor is
27
28     type 'a reader = env -> 'a
29
30 then the choice of unit and bind is natural:
31
32     let r_unit (a : 'a) : 'a reader = fun (e : env) -> a
33
34 Since the type of an `'a reader` is `env -> 'a` (by definition),
35 the type of the `r_unit` function is `'a -> env -> 'a`, which is a
36 specific case of the type of the *K* combinator.  It makes sense
37 that *K* is the unit for the reader monad.
38
39 Since the type of the `bind` operator is required to be
40
41     r_bind : ('a reader) -> ('a -> 'b reader) -> ('b reader)
42
43 We can reason our way to the correct `bind` function as follows. We start by declaring the type:
44
45     let r_bind (u : 'a reader) (f : 'a -> 'b reader) : ('b reader) =
46
47 Now we have to open up the `u` box and get out the `'a` object in order to
48 feed it to `f`.  Since `u` is a function from environments to
49 objects of type `'a`, the way we open a box in this monad is
50 by applying it to an environment:
51
52         ... f (u e) ...
53
54 This subexpression types to `'b reader`, which is good.  The only
55 problem is that we invented an environment `e` that we didn't already have ,
56 so we have to abstract over that variable to balance the books:
57
58         fun e -> f (u e) ...
59
60 This types to `env -> 'b reader`, but we want to end up with `env ->
61 '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:
62
63     r_bind (u : 'a reader) (f : 'a -> 'b reader) : ('b reader) =
64                 f (u e) e         
65
66 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.
67
68 [The bind we cite here is a condensed version of the careful `let a = u e in ...`
69 constructions we provided in earlier lectures.  We use the condensed
70 version here in order to emphasize similarities of structure across
71 monads.]
72
73 The **State Monad** is similar.  Once we've decided to use the following type constructor:
74
75     type 'a state = store -> ('a, store)
76
77 Then our unit is naturally:
78
79     let s_unit (a : 'a) : ('a state) = fun (s : store) -> (a, s)
80
81 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:
82
83     let s_bind (u : 'a state) (f : 'a -> 'b state) : 'b state = 
84                 ... f (...) ...
85
86 But unlocking the `u` box is a little more complicated.  As before, we
87 need to posit a state `s` that we can apply `u` to.  Once we do so,
88 however, we won't have an `'a`, we'll have a pair whose first element
89 is an `'a`.  So we have to unpack the pair:
90
91         ... let (a, s') = u s in ... (f a) ...
92
93 Abstracting over the `s` and adjusting the types gives the result:
94
95         let s_bind (u : 'a state) (f : 'a -> 'b state) : 'b state = 
96                 fun (s : store) -> let (a, s') = u s in f a s'
97
98 The **Option/Maybe Monad** doesn't follow the same pattern so closely, so we
99 won't pause to explore it here, though conceptually its unit and bind
100 follow just as naturally from its type constructor.
101
102 Our other familiar monad is the **List Monad**, which we were told
103 looks like this:
104
105     type 'a list = ['a];;
106     l_unit (a : 'a) = [a];;
107     l_bind u f = List.concat (List.map f u);;
108
109 Thinking through the list monad will take a little time, but doing so
110 will provide a connection with continuations.
111
112 Recall that `List.map` takes a function and a list and returns the
113 result to applying the function to the elements of the list:
114
115     List.map (fun i -> [i;i+1]) [1;2] ~~> [[1; 2]; [2; 3]]
116
117 and List.concat takes a list of lists and erases the embdded list
118 boundaries:
119
120     List.concat [[1; 2]; [2; 3]] ~~> [1; 2; 2; 3]
121
122 And sure enough, 
123
124     l_bind [1;2] (fun i -> [i, i+1]) ~~> [1; 2; 2; 3]
125
126 Now, why this unit, and why this bind?  Well, ideally a unit should
127 not throw away information, so we can rule out `fun x -> []` as an
128 ideal unit.  And units should not add more information than required,
129 so there's no obvious reason to prefer `fun x -> [x,x]`.  In other
130 words, `fun x -> [x]` is a reasonable guess for a unit.
131
132 As for bind, an `'a list` monadic object contains a lot of objects of
133 type `'a`, and we want to make some use of each of them.  The only
134 thing we know for sure we can do with an object of type `'a` is apply
135 the function of type `'a -> 'a list` to them.  Once we've done so, we
136 have a collection of lists, one for each of the `'a`'s.  One
137 possibility is that we could gather them all up in a list, so that
138 `bind' [1;2] (fun i -> [i;i]) ~~> [[1;1];[2;2]]`.  But that restricts
139 the object returned by the second argument of `bind` to always be of
140 type `'b list list`.  We can elimiate that restriction by flattening
141 the list of lists into a single list.  So there is some logic to the
142 choice of unit and bind for the list monad.  
143
144 Yet we can still desire to go deeper, and see if the appropriate bind
145 behavior emerges from the types, as it did for the previously
146 considered monads.  But we can't do that if we leave the list type is
147 a primitive Ocaml type.  However, we know several ways of implementing
148 lists using just functions.  In what follows, we're going to use type
149 3 lists (the right fold implementation), though it's important to
150 wonder how things would change if we used some other strategy for
151 implementating lists.  These were the lists that made lists look like
152 Church numerals with extra bits embdded in them:
153
154     empty list:                fun f z -> z
155     list with one element:     fun f z -> f 1 z
156     list with two elements:    fun f z -> f 2 (f 1 z)
157     list with three elements:  fun f z -> f 3 (f 2 (f 1 z))
158
159 and so on.  To save time, we'll let the OCaml interpreter infer the
160 principle types of these functions (rather than deducing what the
161 types should be):
162
163         # fun f z -> z;;
164         - : 'a -> 'b -> 'b = <fun>
165         # fun f z -> f 1 z;;
166         - : (int -> 'a -> 'b) -> 'a -> 'b = <fun>
167         # fun f z -> f 2 (f 1 z);;
168         - : (int -> 'a -> 'a) -> 'a -> 'a = <fun>
169         # fun f z -> f 3 (f 2 (f 1 z))
170         - : (int -> 'a -> 'a) -> 'a -> 'a = <fun>
171
172 We can see what the consistent, general principle types are at the end, so we
173 can stop. These types should remind you of the simply-typed lambda calculus
174 types for Church numerals (`(o -> o) -> o -> o`) with one extra bit thrown in
175 (in this case, an int).
176
177 So here's our type constructor for our hand-rolled lists:
178
179     type 'b list' = (int -> 'b -> 'b) -> 'b -> 'b
180
181 Generalizing to lists that contain any kind of element (not just
182 ints), we have
183
184     type ('a, 'b) list' = ('a -> 'b -> 'b) -> 'b -> 'b
185
186 So an `('a, 'b) list'` is a list containing elements of type `'a`,
187 where `'b` is the type of some part of the plumbing.  This is more
188 general than an ordinary OCaml list, but we'll see how to map them
189 into OCaml lists soon.  We don't need to fully grasp the role of the `'b`'s
190 in order to proceed to build a monad:
191
192     l'_unit (a : 'a) : ('a, 'b) list = fun a -> fun f z -> f a z
193
194 No problem.  Arriving at bind is a little more complicated, but
195 exactly the same principles apply, you just have to be careful and
196 systematic about it.
197
198     l'_bind (u : ('a,'b) list') (f : 'a -> ('c, 'd) list') : ('c, 'd) list'  = ...
199
200 Unpacking the types gives:
201
202     l'_bind (u : ('a -> 'b -> 'b) -> 'b -> 'b)
203             (f : 'a -> ('c -> 'd -> 'd) -> 'd -> 'd)
204             : ('c -> 'd -> 'd) -> 'd -> 'd = ...
205
206 But it's a rookie mistake to quail before complicated types. You should
207 be no more intimiated by complex types than by a linguistic tree with
208 deeply embedded branches: complex structure created by repeated
209 application of simple rules.
210
211 As usual, we need to unpack the `u` box.  Examine the type of `u`.
212 This time, `u` will only deliver up its contents if we give `u` as an
213 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:
214
215         ... u (fun (a : 'a) (b : 'b) -> ... f a ... ) ...
216
217 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)`:
218
219         ... u (fun (a : 'a) (b : 'b) -> ... f a k ... ) ...
220
221 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:
222
223         ... u (fun (a : 'a) (b : 'b) -> f a k b) ...
224
225 Now, we've used a `k` that we pulled out of nowhere, so we need to abstract over it:
226
227         fun (k : 'c -> 'b -> 'b) -> u (fun (a : 'a) (b : 'b) -> f a k b)
228
229 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:
230
231     l'_bind (u : ('a -> 'b -> 'b) -> 'b -> 'b)
232             (f : 'a -> ('c -> 'b -> 'b) -> 'b -> 'b)
233             : ('c -> 'b -> 'b) -> 'b -> 'b = 
234       fun k -> u (fun a b -> f a k b)
235
236 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.
237
238 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:
239
240       fun k z -> u (fun a b -> f a k b) z
241
242 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?
243
244 Suppose we have a list' whose contents are `[1; 2; 4; 8]`---that is, our list' will be `fun f z -> f 1 (f 2 (f 4 (f 8 z)))`. We call that list' `u`. Suppose we also have a function `f` that for each `int` we give it, gives back a list of the divisors of that `int` that are greater than 1. Intuitively, then, binding `u` to `f` should give us:
245
246         concat (map f u) =
247         concat [[]; [2]; [2; 4]; [2; 4; 8]] =
248         [2; 2; 4; 2; 4; 8]
249
250 Or rather, it should give us a list' version of that, which takes a function `k` and value `z` as arguments, and returns the right fold of `k` and `z` over those elements. What does our formula
251
252       fun k z -> u (fun a b -> f a k b) z
253         
254 do? Well, for each element `a` in `u`, it applies `f` to that `a`, getting one of the lists:
255
256         []
257         [2]
258         [2; 4]
259         [2; 4; 8]
260
261 (or rather, their list' versions). Then it takes the accumulated result `b` of previous steps in the fold, and it folds `k` and `b` over the list generated by `f a`. The result of doing so is passed on to the next step as the accumulated result so far.
262
263 So if, for example, we let `k` be `+` and `z` be `0`, then the computation would proceed:
264
265         0 ==>
266         right-fold + and 0 over [2; 4; 8] = 2+4+8+0 ==>
267         right-fold + and 2+4+8+0 over [2; 4] = 2+4+2+4+8+0 ==>
268         right-fold + and 2+4+2+4+8+0 over [2] = 2+2+4+2+4+8+0 ==>
269         right-fold + and 2+2+4+2+4+8+0 over [] = 2+2+4+2+4+8+0
270
271 which indeed is the result of right-folding + and 0 over `[2; 2; 4; 2; 4; 8]`. If you trace through how this works, you should be able to persuade yourself that our formula:
272
273       fun k z -> u (fun a b -> f a k b) z
274
275 will deliver just the same folds, for arbitrary choices of `k` and `z` (with the right types), and arbitrary list's `u` and appropriately-typed `f`s, as
276
277         fun k z -> List.fold_right k (concat (map f u)) z
278
279 would.
280
281 For future reference, we might make two eta-reductions to our formula, so that we have instead:
282
283       let l'_bind = fun k -> u (fun a -> f a k);;
284
285 Let's make some more tests:
286
287
288     l_bind [1;2] (fun i -> [i, i+1]) ~~> [1; 2; 2; 3]
289
290     l'_bind (fun f z -> f 1 (f 2 z)) 
291             (fun i -> fun f z -> f i (f (i+1) z)) ~~> <fun>
292
293 Sigh.  OCaml won't show us our own list.  So we have to choose an `f`
294 and a `z` that will turn our hand-crafted lists into standard OCaml
295 lists, so that they will print out.
296
297         # let cons h t = h :: t;;  (* OCaml is stupid about :: *)
298         # l'_bind (fun f z -> f 1 (f 2 z)) 
299                           (fun i -> fun f z -> f i (f (i+1) z)) cons [];;
300         - : int list = [1; 2; 2; 3]
301
302 Ta da!
303
304
305 Montague's PTQ treatment of DPs as generalized quantifiers
306 ----------------------------------------------------------
307
308 We've hinted that Montague's treatment of DPs as generalized
309 quantifiers embodies the spirit of continuations (see de Groote 2001,
310 Barker 2002 for lengthy discussion).  Let's see why.  
311
312 First, we'll need a type constructor.  As you probably know, 
313 Montague replaced individual-denoting determiner phrases (with type `e`)
314 with generalized quantifiers (with [extensional] type `(e -> t) -> t`.
315 In particular, the denotation of a proper name like *John*, which
316 might originally denote a object `j` of type `e`, came to denote a
317 generalized quantifier `fun pred -> pred j` of type `(e -> t) -> t`.
318 Let's write a general function that will map individuals into their
319 corresponding generalized quantifier:
320
321    gqize (a : e) = fun (p : e -> t) -> p a
322
323 This function wraps up an individual in a fancy box.  That is to say,
324 we are in the presence of a monad.  The type constructor, the unit and
325 the bind follow naturally.  We've done this enough times that we won't
326 belabor the construction of the bind function, the derivation is
327 similar to the List monad just given:
328
329         type 'a continuation = ('a -> 'b) -> 'b
330         c_unit (a : 'a) = fun (p : 'a -> 'b) -> p a
331         c_bind (u : ('a -> 'b) -> 'b) (f : 'a -> ('c -> 'd) -> 'd) : ('c -> 'd) -> 'd =
332           fun (k : 'a -> 'b) -> u (fun (a : 'a) -> f a k)
333
334 How similar is it to the List monad?  Let's examine the type
335 constructor and the terms from the list monad derived above:
336
337     type ('a, 'b) list' = ('a -> 'b -> 'b) -> 'b -> 'b
338     l'_unit a = fun f -> f a                 
339     l'_bind u f = fun k -> u (fun a -> f a k)
340
341 (We performed a sneaky but valid eta reduction in the unit term.)
342
343 The unit and the bind for the Montague continuation monad and the
344 homemade List monad are the same terms!  In other words, the behavior
345 of the List monad and the behavior of the continuations monad are
346 parallel in a deep sense.
347
348 Have we really discovered that lists are secretly continuations?  Or
349 have we merely found a way of simulating lists using list
350 continuations?  Well, strictly speaking, what we have done is shown
351 that one particular implementation of lists---the left fold
352 implementation---gives rise to a continuation monad fairly naturally,
353 and that this monad can reproduce the behavior of the standard list
354 monad.  But what about other list implementations?  Do they give rise
355 to monads that can be understood in terms of continuations?
356
357 Refunctionalizing zippers
358 -------------------------
359
360 Manipulating trees with monads
361 ------------------------------
362
363 This thread develops an idea based on a detailed suggestion of Ken
364 Shan's.  We'll build a series of functions that operate on trees,
365 doing various things, including replacing leaves, counting nodes, and
366 converting a tree to a list of leaves.  The end result will be an
367 application for continuations.
368
369 From an engineering standpoint, we'll build a tree transformer that
370 deals in monads.  We can modify the behavior of the system by swapping
371 one monad for another.  (We've already seen how adding a monad can add
372 a layer of funtionality without disturbing the underlying system, for
373 instance, in the way that the reader monad allowed us to add a layer
374 of intensionality to an extensional grammar, but we have not yet seen
375 the utility of replacing one monad with other.)
376
377 First, we'll be needing a lot of trees during the remainder of the
378 course.  Here's a type constructor for binary trees:
379
380     type 'a tree = Leaf of 'a | Node of ('a tree * 'a tree)
381
382 These are trees in which the internal nodes do not have labels.  [How
383 would you adjust the type constructor to allow for labels on the
384 internal nodes?]
385
386 We'll be using trees where the nodes are integers, e.g.,
387
388
389 <pre>
390 let t1 = Node ((Node ((Leaf 2), (Leaf 3))),
391                (Node ((Leaf 5),(Node ((Leaf 7),
392                                       (Leaf 11))))))
393
394     .
395  ___|___
396  |     |
397  .     .
398 _|__  _|__
399 |  |  |  |
400 2  3  5  .
401         _|__
402         |  |
403         7  11
404 </pre>
405
406 Our first task will be to replace each leaf with its double:
407
408 <pre>
409 let rec treemap (newleaf:'a -> 'b) (t:'a tree):('b tree) =
410   match t with Leaf x -> Leaf (newleaf x)
411              | Node (l, r) -> Node ((treemap newleaf l),
412                                     (treemap newleaf r));;
413 </pre>
414 `treemap` takes a function that transforms old leaves into new leaves, 
415 and maps that function over all the leaves in the tree, leaving the
416 structure of the tree unchanged.  For instance:
417
418 <pre>
419 let double i = i + i;;
420 treemap double t1;;
421 - : int tree =
422 Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
423
424     .
425  ___|____
426  |      |
427  .      .
428 _|__  __|__
429 |  |  |   |
430 4  6  10  .
431         __|___
432         |    |
433         14   22
434 </pre>
435
436 We could have built the doubling operation right into the `treemap`
437 code.  However, because what to do to each leaf is a parameter, we can
438 decide to do something else to the leaves without needing to rewrite
439 `treemap`.  For instance, we can easily square each leaf instead by
440 supplying the appropriate `int -> int` operation in place of `double`:
441
442 <pre>
443 let square x = x * x;;
444 treemap square t1;;
445 - : int tree =ppp
446 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
447 </pre>
448
449 Note that what `treemap` does is take some global, contextual
450 information---what to do to each leaf---and supplies that information
451 to each subpart of the computation.  In other words, `treemap` has the
452 behavior of a reader monad.  Let's make that explicit.  
453
454 In general, we're on a journey of making our treemap function more and
455 more flexible.  So the next step---combining the tree transducer with
456 a reader monad---is to have the treemap function return a (monadized)
457 tree that is ready to accept any `int->int` function and produce the
458 updated tree.
459
460 \tree (. (. (f2) (f3))(. (f5) (.(f7)(f11))))
461 <pre>
462 \f    .
463   ____|____
464   |       |
465   .       .
466 __|__   __|__
467 |   |   |   |
468 f2  f3  f5  .
469           __|___
470           |    |
471           f7  f11
472 </pre>
473
474 That is, we want to transform the ordinary tree `t1` (of type `int
475 tree`) into a reader object of type `(int->int)-> int tree`: something 
476 that, when you apply it to an `int->int` function returns an `int
477 tree` in which each leaf `x` has been replaced with `(f x)`.
478
479 With previous readers, we always knew which kind of environment to
480 expect: either an assignment function (the original calculator
481 simulation), a world (the intensionality monad), an integer (the
482 Jacobson-inspired link monad), etc.  In this situation, it will be
483 enough for now to expect that our reader will expect a function of
484 type `int->int`.
485
486 <pre>
487 type 'a reader = (int->int) -> 'a;;  (* mnemonic: e for environment *)
488 let reader_unit (x:'a): 'a reader = fun _ -> x;;
489 let reader_bind (u: 'a reader) (f:'a -> 'c reader):'c reader = fun e -> f (u e) e;;
490 </pre>
491
492 It's easy to figure out how to turn an `int` into an `int reader`:
493
494 <pre>
495 let int2int_reader (x:'a): 'b reader = fun (op:'a -> 'b) -> op x;;
496 int2int_reader 2 (fun i -> i + i);;
497 - : int = 4
498 </pre>
499
500 But what do we do when the integers are scattered over the leaves of a
501 tree?  A binary tree is not the kind of thing that we can apply a
502 function of type `int->int` to.
503
504 <pre>
505 let rec treemonadizer (f:'a -> 'b reader) (t:'a tree):('b tree) reader =
506   match t with Leaf x -> reader_bind (f x) (fun x' -> reader_unit (Leaf x'))
507              | Node (l, r) -> reader_bind (treemonadizer f l) (fun x ->
508                                 reader_bind (treemonadizer f r) (fun y ->
509                                   reader_unit (Node (x, y))));;
510 </pre>
511
512 This function says: give me a function `f` that knows how to turn
513 something of type `'a` into an `'b reader`, and I'll show you how to 
514 turn an `'a tree` into an `'a tree reader`.  In more fanciful terms, 
515 the `treemonadizer` function builds plumbing that connects all of the
516 leaves of a tree into one connected monadic network; it threads the
517 monad through the leaves.
518
519 <pre>
520 # treemonadizer int2int_reader t1 (fun i -> i + i);;
521 - : int tree =
522 Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
523 </pre>
524
525 Here, our environment is the doubling function (`fun i -> i + i`).  If
526 we apply the very same `int tree reader` (namely, `treemonadizer
527 int2int_reader t1`) to a different `int->int` function---say, the
528 squaring function, `fun i -> i * i`---we get an entirely different
529 result:
530
531 <pre>
532 # treemonadizer int2int_reader t1 (fun i -> i * i);;
533 - : int tree =
534 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
535 </pre>
536
537 Now that we have a tree transducer that accepts a monad as a
538 parameter, we can see what it would take to swap in a different monad.
539 For instance, we can use a state monad to count the number of nodes in
540 the tree.
541
542 <pre>
543 type 'a state = int -> 'a * int;;
544 let state_unit x i = (x, i+.5);;
545 let state_bind u f i = let (a, i') = u i in f a (i'+.5);;
546 </pre>
547
548 Gratifyingly, we can use the `treemonadizer` function without any
549 modification whatsoever, except for replacing the (parametric) type
550 `reader` with `state`:
551
552 <pre>
553 let rec treemonadizer (f:'a -> 'b state) (t:'a tree):('b tree) state =
554   match t with Leaf x -> state_bind (f x) (fun x' -> state_unit (Leaf x'))
555              | Node (l, r) -> state_bind (treemonadizer f l) (fun x ->
556                                 state_bind (treemonadizer f r) (fun y ->
557                                   state_unit (Node (x, y))));;
558 </pre>
559
560 Then we can count the number of nodes in the tree:
561
562 <pre>
563 # treemonadizer state_unit t1 0;;
564 - : int tree * int =
565 (Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11))), 13)
566
567     .
568  ___|___
569  |     |
570  .     .
571 _|__  _|__
572 |  |  |  |
573 2  3  5  .
574         _|__
575         |  |
576         7  11
577 </pre>
578
579 Notice that we've counted each internal node twice---it's a good
580 exercise to adjust the code to count each node once.
581
582 One more revealing example before getting down to business: replacing
583 `state` everywhere in `treemonadizer` with `list` gives us
584
585 <pre>
586 # treemonadizer (fun x -> [ [x; square x] ]) t1;;
587 - : int list tree list =
588 [Node
589   (Node (Leaf [2; 4], Leaf [3; 9]),
590    Node (Leaf [5; 25], Node (Leaf [7; 49], Leaf [11; 121])))]
591 </pre>
592
593 Unlike the previous cases, instead of turning a tree into a function
594 from some input to a result, this transformer replaces each `int` with
595 a list of `int`'s.
596
597 Now for the main point.  What if we wanted to convert a tree to a list
598 of leaves?  
599
600 <pre>
601 type ('a, 'r) continuation = ('a -> 'r) -> 'r;;
602 let continuation_unit x c = c x;;
603 let continuation_bind u f c = u (fun a -> f a c);;
604
605 let rec treemonadizer (f:'a -> ('b, 'r) continuation) (t:'a tree):(('b tree), 'r) continuation =
606   match t with Leaf x -> continuation_bind (f x) (fun x' -> continuation_unit (Leaf x'))
607              | Node (l, r) -> continuation_bind (treemonadizer f l) (fun x ->
608                                 continuation_bind (treemonadizer f r) (fun y ->
609                                   continuation_unit (Node (x, y))));;
610 </pre>
611
612 We use the continuation monad described above, and insert the
613 `continuation` type in the appropriate place in the `treemonadizer` code.
614 We then compute:
615
616 <pre>
617 # treemonadizer (fun a c -> a :: (c a)) t1 (fun t -> []);;
618 - : int list = [2; 3; 5; 7; 11]
619 </pre>
620
621 We have found a way of collapsing a tree into a list of its leaves.
622
623 The continuation monad is amazingly flexible; we can use it to
624 simulate some of the computations performed above.  To see how, first
625 note that an interestingly uninteresting thing happens if we use the
626 continuation unit as our first argument to `treemonadizer`, and then
627 apply the result to the identity function:
628
629 <pre>
630 # treemonadizer continuation_unit t1 (fun x -> x);;
631 - : int tree =
632 Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11)))
633 </pre>
634
635 That is, nothing happens.  But we can begin to substitute more
636 interesting functions for the first argument of `treemonadizer`:
637
638 <pre>
639 (* Simulating the tree reader: distributing a operation over the leaves *)
640 # treemonadizer (fun a c -> c (square a)) t1 (fun x -> x);;
641 - : int tree =
642 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
643
644 (* Simulating the int list tree list *)
645 # treemonadizer (fun a c -> c [a; square a]) t1 (fun x -> x);;
646 - : int list tree =
647 Node
648  (Node (Leaf [2; 4], Leaf [3; 9]),
649   Node (Leaf [5; 25], Node (Leaf [7; 49], Leaf [11; 121])))
650
651 (* Counting leaves *)
652 # treemonadizer (fun a c -> 1 + c a) t1 (fun x -> 0);;
653 - : int = 5
654 </pre>
655
656 We could simulate the tree state example too, but it would require
657 generalizing the type of the continuation monad to 
658
659     type ('a -> 'b -> 'c) continuation = ('a -> 'b) -> 'c;;
660
661 The binary tree monad
662 ---------------------
663
664 Of course, by now you may have realized that we have discovered a new
665 monad, the binary tree monad:
666
667 <pre>
668 type 'a tree = Leaf of 'a | Node of ('a tree) * ('a tree);;
669 let tree_unit (x:'a) = Leaf x;;
670 let rec tree_bind (u:'a tree) (f:'a -> 'b tree):'b tree = 
671   match u with Leaf x -> f x 
672              | Node (l, r) -> Node ((tree_bind l f), (tree_bind r f));;
673 </pre>
674
675 For once, let's check the Monad laws.  The left identity law is easy:
676
677     Left identity: bind (unit a) f = bind (Leaf a) f = fa
678
679 To check the other two laws, we need to make the following
680 observation: it is easy to prove based on `tree_bind` by a simple
681 induction on the structure of the first argument that the tree
682 resulting from `bind u f` is a tree with the same strucure as `u`,
683 except that each leaf `a` has been replaced with `fa`:
684
685 \tree (. (fa1) (. (. (. (fa2)(fa3)) (fa4)) (fa5)))
686 <pre>
687                 .                         .       
688               __|__                     __|__   
689               |   |                     |   |   
690               a1  .                    fa1  .   
691                  _|__                     __|__ 
692                  |  |                     |   | 
693                  .  a5                    .  fa5
694    bind         _|__       f   =        __|__   
695                 |  |                    |   |   
696                 .  a4                   .  fa4  
697               __|__                   __|___   
698               |   |                   |    |   
699               a2  a3                 fa2  fa3         
700 </pre>   
701
702 Given this equivalence, the right identity law
703
704     Right identity: bind u unit = u
705
706 falls out once we realize that
707
708     bind (Leaf a) unit = unit a = Leaf a
709
710 As for the associative law,
711
712     Associativity: bind (bind u f) g = bind u (\a. bind (fa) g)
713
714 we'll give an example that will show how an inductive proof would
715 proceed.  Let `f a = Node (Leaf a, Leaf a)`.  Then
716
717 \tree (. (. (. (. (a1)(a2)))))
718 \tree (. (. (. (. (a1) (a1)) (. (a1) (a1)))  ))
719 <pre>
720                                            .
721                                        ____|____
722           .               .            |       |
723 bind    __|__   f  =    __|_    =      .       .
724         |   |           |   |        __|__   __|__
725         a1  a2         fa1 fa2       |   |   |   |
726                                      a1  a1  a1  a1  
727 </pre>
728
729 Now when we bind this tree to `g`, we get
730
731 <pre>
732            .
733        ____|____
734        |       |
735        .       .
736      __|__   __|__
737      |   |   |   |
738     ga1 ga1 ga1 ga1  
739 </pre>
740
741 At this point, it should be easy to convince yourself that
742 using the recipe on the right hand side of the associative law will
743 built the exact same final tree.
744
745 So binary trees are a monad.
746
747 Haskell combines this monad with the Option monad to provide a monad
748 called a
749 [SearchTree](http://hackage.haskell.org/packages/archive/tree-monad/0.2.1/doc/html/src/Control-Monad-SearchTree.html#SearchTree)
750 that is intended to 
751 represent non-deterministic computations as a tree.