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