tree monads
[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 (a : 'a) : ('a state) = fun (s : store) -> (a, 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 (a : 'a) = [a];;
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 (a : 'a) : ('a, 'b) list = fun a -> fun f z -> f a 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 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:
223
224         concat (map f u) =
225         concat [[]; [2]; [2; 4]; [2; 4; 8]] =
226         [2; 2; 4; 2; 4; 8]
227
228 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
229
230       fun k z -> u (fun a b -> f a k b) z
231         
232 do? Well, for each element `a` in `u`, it applies `f` to that `a`, getting one of the lists:
233
234         []
235         [2]
236         [2; 4]
237         [2; 4; 8]
238
239 (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.
240
241 So if, for example, we let `k` be `+` and `z` be `0`, then the computation would proceed:
242
243         0 ==>
244         right-fold + and 0 over [2; 4; 8] = 2+4+8+0 ==>
245         right-fold + and 2+4+8+0 over [2; 4] = 2+4+2+4+8+0 ==>
246         right-fold + and 2+4+2+4+8+0 over [2] = 2+2+4+2+4+8+0 ==>
247         right-fold + and 2+2+4+2+4+8+0 over [] = 2+2+4+2+4+8+0
248
249 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:
250
251       fun k z -> u (fun a b -> f a k b) z
252
253 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
254
255         fun k z -> List.fold_right k (concat (map f u)) z
256
257 would.
258
259 For future reference, we might make two eta-reductions to our formula, so that we have instead:
260
261       let l'_bind = fun k -> u (fun a -> f a k);;
262
263 Let's make some more tests:
264
265
266     l_bind [1;2] (fun i -> [i, i+1]) ~~> [1; 2; 2; 3]
267
268     l'_bind (fun f z -> f 1 (f 2 z)) 
269             (fun i -> fun f z -> f i (f (i+1) z)) ~~> <fun>
270
271 Sigh.  OCaml won't show us our own list.  So we have to choose an `f`
272 and a `z` that will turn our hand-crafted lists into standard OCaml
273 lists, so that they will print out.
274
275         # let cons h t = h :: t;;  (* OCaml is stupid about :: *)
276         # l'_bind (fun f z -> f 1 (f 2 z)) 
277                           (fun i -> fun f z -> f i (f (i+1) z)) cons [];;
278         - : int list = [1; 2; 2; 3]
279
280 Ta da!
281
282 To bad this digression, though it ties together various
283 elements of the course, has *no relevance whatsoever* to the topic of
284 continuations...
285
286 Montague's PTQ treatment of DPs as generalized quantifiers
287 ----------------------------------------------------------
288
289 We've hinted that Montague's treatment of DPs as generalized
290 quantifiers embodies the spirit of continuations (see de Groote 2001,
291 Barker 2002 for lengthy discussion).  Let's see why.  
292
293 First, we'll need a type constructor.  As you probably know, 
294 Montague replaced individual-denoting determiner phrases (with type `e`)
295 with generalized quantifiers (with [extensional] type `(e -> t) -> t`.
296 In particular, the denotation of a proper name like *John*, which
297 might originally denote a object `j` of type `e`, came to denote a
298 generalized quantifier `fun pred -> pred j` of type `(e -> t) -> t`.
299 Let's write a general function that will map individuals into their
300 corresponding generalized quantifier:
301
302    gqize (a : e) = fun (p : e -> t) -> p a
303
304 This function wraps up an individual in a fancy box.  That is to say,
305 we are in the presence of a monad.  The type constructor, the unit and
306 the bind follow naturally.  We've done this enough times that we won't
307 belabor the construction of the bind function, the derivation is
308 similar to the List monad just given:
309
310         type 'a continuation = ('a -> 'b) -> 'b
311         c_unit (a : 'a) = fun (p : 'a -> 'b) -> p a
312         c_bind (u : ('a -> 'b) -> 'b) (f : 'a -> ('c -> 'd) -> 'd) : ('c -> 'd) -> 'd =
313           fun (k : 'a -> 'b) -> u (fun (a : 'a) -> f a k)
314
315 How similar is it to the List monad?  Let's examine the type
316 constructor and the terms from the list monad derived above:
317
318     type ('a, 'b) list' = ('a -> 'b -> 'b) -> 'b -> 'b
319     l'_unit a = fun f -> f a                 
320     l'_bind u f = fun k -> u (fun a -> f a k)
321
322 (We performed a sneaky but valid eta reduction in the unit term.)
323
324 The unit and the bind for the Montague continuation monad and the
325 homemade List monad are the same terms!  In other words, the behavior
326 of the List monad and the behavior of the continuations monad are
327 parallel in a deep sense.  To emphasize the parallel, we can
328 instantiate the type of the list' monad using the OCaml list type:
329
330     type 'a c_list = ('a -> 'a list) -> 'a list
331
332 Have we really discovered that lists are secretly continuations?  Or
333 have we merely found a way of simulating lists using list
334 continuations?  Both perspectives are valid, and we can use our
335 intuitions about the list monad to understand continuations, and vice
336 versa (not to mention our intuitions about primitive recursion in
337 Church numerals too).  The connections will be expecially relevant
338 when we consider indefinites and Hamblin semantics on the linguistic
339 side, and non-determinism on the list monad side.
340
341 Refunctionalizing zippers
342 -------------------------
343
344 Manipulating trees with monads
345 ------------------------------
346
347 This thread develops an idea based on a detailed suggestion of Ken
348 Shan's.  We'll build a series of functions that operate on trees,
349 doing various things, including replacing leaves, counting nodes, and
350 converting a tree to a list of leaves.  The end result will be an
351 application for continuations.
352
353 From an engineering standpoint, we'll build a tree transformer that
354 deals in monads.  We can modify the behavior of the system by swapping
355 one monad for another.  (We've already seen how adding a monad can add
356 a layer of funtionality without disturbing the underlying system, for
357 instance, in the way that the reader monad allowed us to add a layer
358 of intensionality to an extensional grammar, but we have not yet seen
359 the utility of replacing one monad with other.)
360
361 First, we'll be needing a lot of trees during the remainder of the
362 course.  Here's a type constructor for binary trees:
363
364     type 'a tree = Leaf of 'a | Node of ('a tree * 'a tree)
365
366 These are trees in which the internal nodes do not have labels.  [How
367 would you adjust the type constructor to allow for labels on the
368 internal nodes?]
369
370 We'll be using trees where the nodes are integers, e.g.,
371
372
373 <pre>
374 let t1 = Node ((Node ((Leaf 2), (Leaf 3))),
375                (Node ((Leaf 5),(Node ((Leaf 7),
376                                       (Leaf 11))))))
377
378     .
379  ___|___
380  |     |
381  .     .
382 _|__  _|__
383 |  |  |  |
384 2  3  5  .
385         _|__
386         |  |
387         7  11
388 </pre>
389
390 Our first task will be to replace each leaf with its double:
391
392 <pre>
393 let rec treemap (newleaf:'a -> 'b) (t:'a tree):('b tree) =
394   match t with Leaf x -> Leaf (newleaf x)
395              | Node (l, r) -> Node ((treemap newleaf l),
396                                     (treemap newleaf r));;
397 </pre>
398 `treemap` takes a function that transforms old leaves into new leaves, 
399 and maps that function over all the leaves in the tree, leaving the
400 structure of the tree unchanged.  For instance:
401
402 <pre>
403 let double i = i + i;;
404 treemap double t1;;
405 - : int tree =
406 Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
407
408     .
409  ___|____
410  |      |
411  .      .
412 _|__  __|__
413 |  |  |   |
414 4  6  10  .
415         __|___
416         |    |
417         14   22
418 </pre>
419
420 We could have built the doubling operation right into the `treemap`
421 code.  However, because what to do to each leaf is a parameter, we can
422 decide to do something else to the leaves without needing to rewrite
423 `treemap`.  For instance, we can easily square each leaf instead by
424 supplying the appropriate `int -> int` operation in place of `double`:
425
426 <pre>
427 let square x = x * x;;
428 treemap square t1;;
429 - : int tree =ppp
430 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
431 </pre>
432
433 Note that what `treemap` does is take some global, contextual
434 information---what to do to each leaf---and supplies that information
435 to each subpart of the computation.  In other words, `treemap` has the
436 behavior of a reader monad.  Let's make that explicit.  
437
438 In general, we're on a journey of making our treemap function more and
439 more flexible.  So the next step---combining the tree transducer with
440 a reader monad---is to have the treemap function return a (monadized)
441 tree that is ready to accept any `int->int` function and produce the
442 updated tree.
443
444 \tree (. (. (f2) (f3))(. (f5) (.(f7)(f11))))
445 <pre>
446 \f    .
447   ____|____
448   |       |
449   .       .
450 __|__   __|__
451 |   |   |   |
452 f2  f3  f5  .
453           __|___
454           |    |
455           f7  f11
456 </pre>
457
458 That is, we want to transform the ordinary tree `t1` (of type `int
459 tree`) into a reader object of type `(int->int)-> int tree`: something 
460 that, when you apply it to an `int->int` function returns an `int
461 tree` in which each leaf `x` has been replaced with `(f x)`.
462
463 With previous readers, we always knew which kind of environment to
464 expect: either an assignment function (the original calculator
465 simulation), a world (the intensionality monad), an integer (the
466 Jacobson-inspired link monad), etc.  In this situation, it will be
467 enough for now to expect that our reader will expect a function of
468 type `int->int`.
469
470 <pre>
471 type 'a reader = (int->int) -> 'a;;  (* mnemonic: e for environment *)
472 let reader_unit (x:'a): 'a reader = fun _ -> x;;
473 let reader_bind (u: 'a reader) (f:'a -> 'c reader):'c reader = fun e -> f (u e) e;;
474 </pre>
475
476 It's easy to figure out how to turn an `int` into an `int reader`:
477
478 <pre>
479 let int2int_reader (x:'a): 'b reader = fun (op:'a -> 'b) -> op x;;
480 int2int_reader 2 (fun i -> i + i);;
481 - : int = 4
482 </pre>
483
484 But what do we do when the integers are scattered over the leaves of a
485 tree?  A binary tree is not the kind of thing that we can apply a
486 function of type `int->int` to.
487
488 <pre>
489 let rec treemonadizer (f:'a -> 'b reader) (t:'a tree):('b tree) reader =
490   match t with Leaf x -> reader_bind (f x) (fun x' -> reader_unit (Leaf x'))
491              | Node (l, r) -> reader_bind (treemonadizer f l) (fun x ->
492                                 reader_bind (treemonadizer f r) (fun y ->
493                                   reader_unit (Node (x, y))));;
494 </pre>
495
496 This function says: give me a function `f` that knows how to turn
497 something of type `'a` into an `'b reader`, and I'll show you how to 
498 turn an `'a tree` into an `'a tree reader`.  In more fanciful terms, 
499 the `treemonadizer` function builds plumbing that connects all of the
500 leaves of a tree into one connected monadic network; it threads the
501 monad through the leaves.
502
503 <pre>
504 # treemonadizer int2int_reader t1 (fun i -> i + i);;
505 - : int tree =
506 Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
507 </pre>
508
509 Here, our environment is the doubling function (`fun i -> i + i`).  If
510 we apply the very same `int tree reader` (namely, `treemonadizer
511 int2int_reader t1`) to a different `int->int` function---say, the
512 squaring function, `fun i -> i * i`---we get an entirely different
513 result:
514
515 <pre>
516 # treemonadizer int2int_reader t1 (fun i -> i * i);;
517 - : int tree =
518 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
519 </pre>
520
521 Now that we have a tree transducer that accepts a monad as a
522 parameter, we can see what it would take to swap in a different monad.
523 For instance, we can use a state monad to count the number of nodes in
524 the tree.
525
526 <pre>
527 type 'a state = int -> 'a * int;;
528 let state_unit x i = (x, i+.5);;
529 let state_bind u f i = let (a, i') = u i in f a (i'+.5);;
530 </pre>
531
532 Gratifyingly, we can use the `treemonadizer` function without any
533 modification whatsoever, except for replacing the (parametric) type
534 `reader` with `state`:
535
536 <pre>
537 let rec treemonadizer (f:'a -> 'b state) (t:'a tree):('b tree) state =
538   match t with Leaf x -> state_bind (f x) (fun x' -> state_unit (Leaf x'))
539              | Node (l, r) -> state_bind (treemonadizer f l) (fun x ->
540                                 state_bind (treemonadizer f r) (fun y ->
541                                   state_unit (Node (x, y))));;
542 </pre>
543
544 Then we can count the number of nodes in the tree:
545
546 <pre>
547 # treemonadizer state_unit t1 0;;
548 - : int tree * int =
549 (Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11))), 13)
550
551     .
552  ___|___
553  |     |
554  .     .
555 _|__  _|__
556 |  |  |  |
557 2  3  5  .
558         _|__
559         |  |
560         7  11
561 </pre>
562
563 Notice that we've counted each internal node twice---it's a good
564 exercise to adjust the code to count each node once.
565
566 One more revealing example before getting down to business: replacing
567 `state` everywhere in `treemonadizer` with `list` gives us
568
569 <pre>
570 # treemonadizer (fun x -> [ [x; square x] ]) t1;;
571 - : int list tree list =
572 [Node
573   (Node (Leaf [2; 4], Leaf [3; 9]),
574    Node (Leaf [5; 25], Node (Leaf [7; 49], Leaf [11; 121])))]
575 </pre>
576
577 Unlike the previous cases, instead of turning a tree into a function
578 from some input to a result, this transformer replaces each `int` with
579 a list of `int`'s.
580
581 Now for the main point.  What if we wanted to convert a tree to a list
582 of leaves?  
583
584 <pre>
585 type ('a, 'r) continuation = ('a -> 'r) -> 'r;;
586 let continuation_unit x c = c x;;
587 let continuation_bind u f c = u (fun a -> f a c);;
588
589 let rec treemonadizer (f:'a -> ('b, 'r) continuation) (t:'a tree):(('b tree), 'r) continuation =
590   match t with Leaf x -> continuation_bind (f x) (fun x' -> continuation_unit (Leaf x'))
591              | Node (l, r) -> continuation_bind (treemonadizer f l) (fun x ->
592                                 continuation_bind (treemonadizer f r) (fun y ->
593                                   continuation_unit (Node (x, y))));;
594 </pre>
595
596 We use the continuation monad described above, and insert the
597 `continuation` type in the appropriate place in the `treemonadizer` code.
598 We then compute:
599
600 <pre>
601 # treemonadizer (fun a c -> a :: (c a)) t1 (fun t -> []);;
602 - : int list = [2; 3; 5; 7; 11]
603 </pre>
604
605 We have found a way of collapsing a tree into a list of its leaves.
606
607 The continuation monad is amazingly flexible; we can use it to
608 simulate some of the computations performed above.  To see how, first
609 note that an interestingly uninteresting thing happens if we use the
610 continuation unit as our first argument to `treemonadizer`, and then
611 apply the result to the identity function:
612
613 <pre>
614 # treemonadizer continuation_unit t1 (fun x -> x);;
615 - : int tree =
616 Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11)))
617 </pre>
618
619 That is, nothing happens.  But we can begin to substitute more
620 interesting functions for the first argument of `treemonadizer`:
621
622 <pre>
623 (* Simulating the tree reader: distributing a operation over the leaves *)
624 # treemonadizer (fun a c -> c (square a)) t1 (fun x -> x);;
625 - : int tree =
626 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
627
628 (* Simulating the int list tree list *)
629 # treemonadizer (fun a c -> c [a; square a]) t1 (fun x -> x);;
630 - : int list tree =
631 Node
632  (Node (Leaf [2; 4], Leaf [3; 9]),
633   Node (Leaf [5; 25], Node (Leaf [7; 49], Leaf [11; 121])))
634
635 (* Counting leaves *)
636 # treemonadizer (fun a c -> 1 + c a) t1 (fun x -> 0);;
637 - : int = 5
638 </pre>
639
640 We could simulate the tree state example too, but it would require
641 generalizing the type of the continuation monad to 
642
643     type ('a -> 'b -> 'c) continuation = ('a -> 'b) -> 'c;;
644
645 The tree monad
646 --------------
647
648 Of course, by now you may have realized that we have discovered a new
649 monad, the tree monad:
650
651 <pre>
652 type 'a tree = Leaf of 'a | Node of ('a tree) * ('a tree);;
653 let tree_unit (x:'a) = Leaf x;;
654 let rec tree_bind (u:'a tree) (f:'a -> 'b tree):'b tree = 
655   match u with Leaf x -> f x | Node (l, r) -> Node ((tree_bind l f),
656   (tree_bind r f));;
657 </pre>
658
659 For once, let's check the Monad laws.  The left identity law is easy:
660
661     Left identity: bind (unit a) f = bind (Leaf a) f = fa
662
663 To check the other two laws, we need to make the following
664 observation: it is easy to prove based on tree_bind by a simple
665 induction on the structure of the first argument that the tree
666 resulting from `bind u f` is a tree with the same strucure as `u`,
667 except that each leaf `a` has been replaced with `fa`:
668
669 \tree (. (fa1) (. (. (. (fa2)(fa3)) (fa4)) (fa5)))
670 <pre>
671                 .                         .            
672               __|__                     __|__   
673               |   |                     |   |   
674               a1  .                    fa1  .   
675                  _|__                     __|__ 
676                  |  |                     |   | 
677                  .  a5                    .  fa5
678    bind         _|__       f   =        __|__   
679                 |  |                    |   |   
680                 .  a4                   .  fa4  
681               __|__                   __|___       
682               |   |                   |    |       
683               a2  a3                 fa2  fa3         
684 </pre>   
685
686 Given this equivalence, the right identity law
687
688     Right identity: bind u unit = u
689
690 falls out once we realize that
691
692     bind (Leaf a) unit = unit a = Leaf a
693
694 As for the associative law,
695
696     Associativity: bind (bind u f) g = bind u (\a. bind (fa) g)
697
698 we'll give an example that will show how an inductive proof would
699 have to proceed.  Let `f a = Node (Leaf a, Leaf a)`.  Then
700
701 \tree (. (. (. (. (a1)(a2)))))
702 \tree (. (. (. (. (a1) (a1)) (. (a1) (a1)))  ))
703 <pre>
704                                            .            
705                                        ____|____        
706           .               .            |       |        
707 bind    __|__   f  =    __|_    =      .       .         
708         |   |           |   |        __|__   __|__      
709         a1  a2         fa1 fa2       |   |   |   |      
710                                      a1  a1  a1  a1  
711 </pre>
712
713 Now when we bind this tree to `g`, we get
714
715 <pre>
716            .            
717        ____|____        
718        |       |        
719        .       .        
720      __|__   __|__      
721      |   |   |   |      
722     ga1 ga1 ga1 ga1  
723 </pre>
724
725 At this point, it should be easy to convince yourself that
726 using the recipe on the right hand side of the associative law will
727 built the exact same final tree.
728
729 So binary trees are a monad.
730
731 Haskell combines this monad with the Option monad to provide a monad
732 called a
733 [SearchTree](http://hackage.haskell.org/packages/archive/tree-monad/0.2.1/doc/html/src/Control-Monad-SearchTree.html#SearchTree)
734 that is intended to 
735 represent non-deterministic computations as a tree.