edits
[lambda.git] / manipulating_trees_with_monads.mdwn
1 [[!toc]]
2
3 Manipulating trees with monads
4 ------------------------------
5
6 This topic develops an idea based on a suggestion of Ken Shan's.
7 We'll build a series of functions that operate on trees, doing various
8 things, including updating leaves with a Reader monad, counting nodes
9 with a State monad, replacing leaves with a List monad, and converting
10 a tree into a list of leaves with a Continuation monad.  It will turn
11 out that the continuation monad can simulate the behavior of each of
12 the other monads.
13
14 From an engineering standpoint, we'll build a tree transformer that
15 deals in monads.  We can modify the behavior of the system by swapping
16 one monad for another.  We've already seen how adding a monad can add
17 a layer of funtionality without disturbing the underlying system, for
18 instance, in the way that the Reader monad allowed us to add a layer
19 of intensionality to an extensional grammar, but we have not yet seen
20 the utility of replacing one monad with other.
21
22 First, we'll be needing a lot of trees for the remainder of the
23 course.  Here again is a type constructor for leaf-labeled, binary trees:
24
25     type 'a tree = Leaf of 'a | Node of ('a tree * 'a tree);;
26
27 [How would you adjust the type constructor to allow for labels on the
28 internal nodes?]
29
30 We'll be using trees where the nodes are integers, e.g.,
31
32
33         let t1 = Node (Node (Leaf 2, Leaf 3),
34                        Node (Leaf 5, Node (Leaf 7,
35                                            Leaf 11)))
36             .
37          ___|___
38          |     |
39          .     .
40         _|_   _|__
41         |  |  |  |
42         2  3  5  .
43                 _|__
44                 |  |
45                 7  11
46
47 Our first task will be to replace each leaf with its double:
48
49         let rec tree_map (leaf_modifier : 'a -> 'b) (t : 'a tree) : 'b tree =
50           match t with
51             | Leaf i -> Leaf (leaf_modifier i)
52             | Node (l, r) -> Node (tree_map leaf_modifier l,
53                                    tree_map leaf_modifier r);;
54
55 `tree_map` takes a function that transforms old leaves into new leaves,
56 and maps that function over all the leaves in the tree, leaving the
57 structure of the tree unchanged.  For instance:
58
59         let double i = i + i;;
60         tree_map double t1;;
61         - : int tree =
62         Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
63         
64             .
65          ___|____
66          |      |
67          .      .
68         _|__  __|__
69         |  |  |   |
70         4  6  10  .
71                 __|___
72                 |    |
73                 14   22
74
75 We could have built the doubling operation right into the `tree_map`
76 code.  However, because we've made what to do to each leaf a
77 parameter, we can decide to do something else to the leaves without
78 needing to rewrite `tree_map`.  For instance, we can easily square
79 each leaf instead by supplying the appropriate `int -> int` operation
80 in place of `double`:
81
82         let square i = i * i;;
83         tree_map square t1;;
84         - : int tree =
85         Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
86
87 Note that what `tree_map` does is take some unchanging contextual
88 information---what to do to each leaf---and supplies that information
89 to each subpart of the computation.  In other words, `tree_map` has the
90 behavior of a Reader monad.  Let's make that explicit.
91
92 In general, we're on a journey of making our `tree_map` function more and
93 more flexible.  So the next step---combining the tree transformer with
94 a Reader monad---is to have the `tree_map` function return a (monadized)
95 tree that is ready to accept any `int -> int` function and produce the
96 updated tree.
97
98         \f      .
99            _____|____
100            |        |
101            .        .
102          __|___   __|___
103          |    |   |    |
104         f 2  f 3  f 5  .
105                      __|___
106                      |    |
107                     f 7  f 11
108
109 That is, we want to transform the ordinary tree `t1` (of type `int
110 tree`) into a reader monadic object of type `(int -> int) -> int
111 tree`: something that, when you apply it to an `int -> int` function
112 `f` returns an `int tree` in which each leaf `i` has been replaced
113 with `f i`.
114
115 [Application note: this kind of reader object could provide a model
116 for Kaplan's characters.  It turns an ordinary tree into one that
117 expects contextual information (here, the `λ f`) that can be
118 used to compute the content of indexicals embedded arbitrarily deeply
119 in the tree.]
120
121 With our previous applications of the Reader monad, we always knew
122 which kind of environment to expect: either an assignment function, as
123 in the original calculator simulation; a world, as in the
124 intensionality monad; an individual, as in the Jacobson-inspired link
125 monad; etc.  In the present case, we expect that our "environment"
126 will be some function of type `int -> int`. "Looking up" some `int` in
127 the environment will return us the `int` that comes out the other side
128 of that function.
129
130         type 'a reader = (int -> int) -> 'a;;  (* mnemonic: e for environment *)
131         let reader_unit (a : 'a) : 'a reader = fun _ -> a;;
132         let reader_bind (u: 'a reader) (f : 'a -> 'b reader) : 'b reader = fun e -> f (u e) e;;
133
134 It would be a simple matter to turn an *integer* into an `int reader`:
135
136         let int_readerize : int -> int reader = fun (a : int) -> fun (modifier : int -> int) -> modifier a;;
137         int_readerize 2 (fun i -> i + i);;
138         - : int = 4
139
140 But how do we do the analagous transformation when our `int`s are scattered over the leaves of a tree? How do we turn an `int tree` into a reader?
141 A tree is not the kind of thing that we can apply a
142 function of type `int -> int` to.
143
144 But we can do this:
145
146         let rec tree_monadize (f : 'a -> 'b reader) (t : 'a tree) : 'b tree reader =
147             match t with
148             | Leaf a -> reader_bind (f a) (fun b -> reader_unit (Leaf b))
149             | Node (l, r) -> reader_bind (tree_monadize f l) (fun l' ->
150                                reader_bind (tree_monadize f r) (fun r' ->
151                                  reader_unit (Node (l', r'))));;
152
153 This function says: give me a function `f` that knows how to turn
154 something of type `'a` into an `'b reader`---this is a function of the same type that you could bind an `'a reader` to---and I'll show you how to
155 turn an `'a tree` into an `'b tree reader`.  That is, if you show me how to do this:
156
157                       ------------
158           1     --->  |    1     |
159                       ------------
160
161 then I'll give you back the ability to do this:
162
163                       ____________
164           .           |    .     |
165         __|___  --->  |  __|___  |
166         |    |        |  |    |  |
167         1    2        |  1    2  |
168                       ------------
169
170 And how will that boxed tree behave? Whatever actions you perform on it will be transmitted down to corresponding operations on its leaves. For instance, our `int reader` expects an `int -> int` environment. If supplying environment `e` to our `int reader` doubles the contained `int`:
171
172                       ------------
173           1     --->  |    1     |  applied to e  ~~>  2
174                       ------------
175
176 Then we can expect that supplying it to our `int tree reader` will double all the leaves:
177
178                       ____________
179           .           |    .     |                      .
180         __|___  --->  |  __|___  | applied to e  ~~>  __|___
181         |    |        |  |    |  |                    |    |
182         1    2        |  1    2  |                    2    4
183                       ------------
184
185 In more fanciful terms, the `tree_monadize` function builds plumbing that connects all of the leaves of a tree into one connected monadic network; it threads the
186 `'b reader` monad through the original tree's leaves.
187
188         # tree_monadize int_readerize t1 double;;
189         - : int tree =
190         Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
191
192 Here, our environment is the doubling function (`fun i -> i + i`).  If
193 we apply the very same `int tree reader` (namely, `tree_monadize
194 int_readerize t1`) to a different `int -> int` function---say, the
195 squaring function, `fun i -> i * i`---we get an entirely different
196 result:
197
198         # tree_monadize int_readerize t1 square;;
199         - : int tree =
200         Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
201
202 Now that we have a tree transformer that accepts a *reader* monad as a
203 parameter, we can see what it would take to swap in a different monad.
204
205 For instance, we can use a State monad to count the number of leaves in
206 the tree.
207
208         type 'a state = int -> 'a * int;;
209         let state_unit a = fun s -> (a, s);;
210         let state_bind u f = fun s -> let (a, s') = u s in f a s';;
211
212 Gratifyingly, we can use the `tree_monadize` function without any
213 modification whatsoever, except for replacing the (parametric) type
214 `'b reader` with `'b state`, and substituting in the appropriate unit and bind:
215
216         let rec tree_monadize (f : 'a -> 'b state) (t : 'a tree) : 'b tree state =
217             match t with
218             | Leaf a -> state_bind (f a) (fun b -> state_unit (Leaf b))
219             | Node (l, r) -> state_bind (tree_monadize f l) (fun l' ->
220                                state_bind (tree_monadize f r) (fun r' ->
221                                  state_unit (Node (l', r'))));;
222
223 Then we can count the number of leaves in the tree:
224
225         # tree_monadize (fun a -> fun s -> (a, s+1)) t1 0;;
226         - : int tree * int =
227         (Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11))), 5)
228         
229             .
230          ___|___
231          |     |
232          .     .
233         _|__  _|__         , 5
234         |  |  |  |
235         2  3  5  .
236                 _|__
237                 |  |
238                 7  11
239
240 Note that the value returned is a pair consisting of a tree and an
241 integer, 5, which represents the count of the leaves in the tree.
242
243 Why does this work? Because the operation `fun a -> fun s -> (a, s+1)`
244 takes an `int` and wraps it in an `int state` monadic box that
245 increments the state. When we give that same operations to our
246 `tree_monadize` function, it then wraps an `int tree` in a box, one
247 that does the same state-incrementing for each of its leaves.
248
249 We can use the state monad to replace leaves with a number
250 corresponding to that leave's ordinal position.  When we do so, we
251 reveal the order in which the monadic tree forces evaluation:
252
253         # tree_monadize (fun a -> fun s -> (s+1, s+1)) t1 0;;
254         - : int tree * int =
255         (Node (Node (Leaf 1, Leaf 2), Node (Leaf 3, Node (Leaf 4, Leaf 5))), 5)
256
257 The key thing to notice is that instead of copying `a` into the
258 monadic box, we throw away the `a` and put a copy of the state in
259 instead.
260
261 Reversing the order requires reversing the order of the state_bind
262 operations.  It's not obvious that this will type correctly, so think
263 it through:
264
265         let rec tree_monadize_rev (f : 'a -> 'b state) (t : 'a tree) : 'b tree state =
266             match t with
267             | Leaf a -> state_bind (f a) (fun b -> state_unit (Leaf b))
268             | Node (l, r) -> state_bind (tree_monadize f r) (fun r' ->     (* R first *)
269                                state_bind (tree_monadize f l) (fun l'->    (* Then L  *)
270                                  state_unit (Node (l', r'))));;
271
272         # tree_monadize_rev (fun a -> fun s -> (s+1, s+1)) t1 0;;
273         - : int tree * int =
274         (Node (Node (Leaf 5, Leaf 4), Node (Leaf 3, Node (Leaf 2, Leaf 1))), 5)
275
276 We will need below to depend on controlling the order in which nodes
277 are visited when we use the continuation monad to solve the
278 same-fringe problem.
279
280 One more revealing example before getting down to business: replacing
281 `state` everywhere in `tree_monadize` with `list` gives us
282
283         # tree_monadize (fun i -> [ [i; square i] ]) t1;;
284         - : int list tree list =
285         [Node
286           (Node (Leaf [2; 4], Leaf [3; 9]),
287            Node (Leaf [5; 25], Node (Leaf [7; 49], Leaf [11; 121])))]
288
289 Unlike the previous cases, instead of turning a tree into a function
290 from some input to a result, this transformer replaces each `int` with
291 a list of `int`'s. We might also have done this with a Reader monad, though then our environments would need to be of type `int -> int list`. Experiment with what happens if you supply the `tree_monadize` based on the List monad an operation like `fun i -> [2*i; 3*i]`. Use small trees for your experiment.
292
293 [Why is the argument to `tree_monadize` `int -> int list list` instead
294 of `int -> int list`?  Well, as usual, the List monad bind operation
295 will erase the outer list box, so if we want to replace the leaves
296 with lists, we have to nest the replacement lists inside a disposable
297 box.]
298
299 Now for the main point.  What if we wanted to convert a tree to a list
300 of leaves?
301
302         type ('a, 'r) continuation = ('a -> 'r) -> 'r;;
303         let continuation_unit a = fun k -> k a;;
304         let continuation_bind u f = fun k -> u (fun a -> f a k);;
305         
306         let rec tree_monadize (f : 'a -> ('b, 'r) continuation) (t : 'a tree) : ('b tree, 'r) continuation =
307             match t with
308             | Leaf a -> continuation_bind (f a) (fun b -> continuation_unit (Leaf b))
309             | Node (l, r) -> continuation_bind (tree_monadize f l) (fun l' ->
310                                continuation_bind (tree_monadize f r) (fun r' ->
311                                  continuation_unit (Node (l', r'))));;
312
313 We use the Continuation monad described above, and insert the
314 `continuation` type in the appropriate place in the `tree_monadize` code. Then if we give the `tree_monadize` function an operation that converts `int`s into `'b`-wrapping Continuation monads, it will give us back a way to turn `int tree`s into corresponding `'b tree`-wrapping Continuation monads.
315
316 So for example, we compute:
317
318         # tree_monadize (fun a -> fun k -> a :: k a) t1 (fun t -> []);;
319         - : int list = [2; 3; 5; 7; 11]
320
321 We have found a way of collapsing a tree into a list of its
322 leaves. Can you trace how this is working? Think first about what the
323 operation `fun a -> fun k -> a :: k a` does when you apply it to a
324 plain `int`, and the continuation `fun _ -> []`. Then given what we've
325 said about `tree_monadize`, what should we expect `tree_monadize (fun
326 a -> fun k -> a :: k a` to do?
327
328 In a moment, we'll return to the same-fringe problem.  Since the
329 simple but inefficient way to solve it is to map each tree to a list
330 of its leaves, this transformation is on the path to a more efficient
331 solution.  We'll just have to figure out how to postpone computing the
332 tail of the list until its needed...
333
334 The Continuation monad is amazingly flexible; we can use it to
335 simulate some of the computations performed above.  To see how, first
336 note that an interestingly uninteresting thing happens if we use
337 `continuation_unit` as our first argument to `tree_monadize`, and then
338 apply the result to the identity function:
339
340         # tree_monadize continuation_unit t1 (fun t -> t);;
341         - : int tree =
342         Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11)))
343
344 That is, nothing happens.  But we can begin to substitute more
345 interesting functions for the first argument of `tree_monadize`:
346
347         (* Simulating the tree reader: distributing a operation over the leaves *)
348         # tree_monadize (fun a -> fun k -> k (square a)) t1 (fun t -> t);;
349         - : int tree =
350         Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
351
352         (* Simulating the int list tree list *)
353         # tree_monadize (fun a -> fun k -> k [a; square a]) t1 (fun t -> t);;
354         - : int list tree =
355         Node
356          (Node (Leaf [2; 4], Leaf [3; 9]),
357           Node (Leaf [5; 25], Node (Leaf [7; 49], Leaf [11; 121])))
358
359         (* Counting leaves *)
360         # tree_monadize (fun a -> fun k -> 1 + k a) t1 (fun t -> 0);;
361         - : int = 5
362
363 [To be fixed: exactly which kind of monad each of these computations simulates.]
364
365 We could simulate the tree state example too by setting the relevant 
366 type to `('a, 'state -> 'result) continuation`.
367 In fact, Andre Filinsky has suggested that the continuation monad is
368 able to simulate any other monad (Google for "mother of all monads").
369
370 We would eventually want to generalize the continuation type to
371
372         type ('a, 'b, 'c) continuation = ('a -> 'b) -> 'c;;
373
374 If you want to see how to parameterize the definition of the `tree_monadize` function, so that you don't have to keep rewriting it for each new monad, see [this code](/code/tree_monadize.ml).
375
376 Using continuations to solve the same fringe problem
377 ----------------------------------------------------
378
379 We've seen two solutions to the same fringe problem so far.  
380 The problem, recall, is to take two trees and decide whether they have
381 the same leaves in the same order.
382
383 <pre>
384  ta            tb          tc
385  .             .           .
386 _|__          _|__        _|__
387 |  |          |  |        |  |
388 1  .          .  3        1  .
389   _|__       _|__           _|__
390   |  |       |  |           |  |
391   2  3       1  2           3  2
392
393 let ta = Node (Leaf 1, Node (Leaf 2, Leaf 3));;
394 let tb = Node (Node (Leaf 1, Leaf 2), Leaf 3);;
395 let tc = Node (Leaf 1, Node (Leaf 3, Leaf 2));;
396 </pre>
397
398 So `ta` and `tb` are different trees that have the same fringe, but
399 `ta` and `tc` are not.
400
401 The simplest solution is to map each tree to a list of its leaves,
402 then compare the lists.  But because we will have computed the entire
403 fringe before starting the comparison, if the fringes differ in an
404 early position, we've wasted our time examining the rest of the trees.
405
406 The second solution was to use tree zippers and mutable state to
407 simulate coroutines (see [[coroutines and aborts]]).  In that
408 solution, we pulled the zipper on the first tree until we found the
409 next leaf, then stored the zipper structure in the mutable variable
410 while we turned our attention to the other tree.  Because we stopped
411 as soon as we find the first mismatched leaf, this solution does not
412 have the flaw just mentioned of the solution that maps both trees to a
413 list of leaves before beginning comparison.
414
415 Since zippers are just continuations reified, we expect that the
416 solution in terms of zippers can be reworked using continuations, and
417 this is indeed the case.  Before we can arrive at a solution, however,
418 we must define a data structure called a stream:
419
420     type 'a stream = End | Next of 'a * (unit -> 'a stream);;
421
422 A stream is like a list in that it contains a series of objects (all
423 of the same type, here, type `'a`).  The first object in the stream
424 corresponds to the head of a list, which we pair with a stream
425 representing the rest of a the list.  There is a special stream called
426 `End` that represents a stream that contains no (more) elements,
427 analogous to the empty list `[]`.  
428
429 Actually, we pair each element not with a stream, but with a thunked
430 stream, that is, a function from the unit type to streams.  The idea
431 is that the next element in the stream is not computed until we forced
432 the thunk by applying it to the unit:
433
434 <pre>
435 # let rec make_int_stream i = Next (i, fun () -> make_int_stream (i + 1));;
436 val make_int_stream : int -> int stream = <fun>
437 # let int_stream = make_int_stream 1;;
438 val int_stream : int stream = Next (1, <fun>)         (* First element: 1 *)
439 # match int_stream with Next (i, rest) -> rest;;      
440 - : unit -> int stream = <fun>                        (* Rest: a thunk *)
441
442 (* Force the thunk to compute the second element *)
443 # (match int_stream with Next (i, rest) -> rest) ();;
444 - : int stream = Next (2, <fun>)      
445 </pre>
446
447 You can think of `int_stream` as a functional object that provides
448 access to an infinite sequence of integers, one at a time.  It's as if
449 we had written `[1;2;...]` where `...` meant "continue indefinitely".
450
451 So, with streams in hand, we need only rewrite our continuation tree
452 monadizer so that instead of mapping trees to lists, it maps them to 
453 streams.  Instead of 
454
455         # tree_monadize (fun a k -> a :: k a) t1 (fun t -> []);;
456         - : int list = [2; 3; 5; 7; 11]
457
458 as above, we have 
459
460         # tree_monadize (fun i k -> Next (i, fun () -> k ())) t1 (fun _ -> End);;
461         - : int stream = Next (2, <fun>)
462
463 We can see the first element in the stream, the first leaf (namely,
464 2), but in order to see the next, we'll have to force a thunk.
465
466 Then to complete the same-fringe function, we simply convert both
467 trees into leaf-streams, then compare the streams element by element.
468 The code is enitrely routine, but for the sake of completeness, here it is:
469
470 <pre>
471 let rec compare_streams stream1 stream2 =
472     match stream1, stream2 with 
473     | End, End -> true (* Done!  Fringes match. *)
474     | Next (next1, rest1), Next (next2, rest2) when next1 = next2 -> compare_streams (rest1 ()) (rest2 ())
475     | _ -> false;;
476
477 let same_fringe t1 t2 =
478   let stream1 = tree_monadize (fun i k -> Next (i, fun () -> k ())) t1 (fun _ -> End) in 
479   let stream2 = tree_monadize (fun i k -> Next (i, fun () -> k ())) t2 (fun _ -> End) in 
480   compare_streams stream1 stream2;;
481 </pre>
482
483 Notice the forcing of the thunks in the recursive call to
484 `compare_streams`.  So indeed:
485
486 <pre>
487 # same_fringe ta tb;;
488 - : bool = true
489 # same_fringe ta tc;;
490 - : bool = false
491 </pre>
492
493 Now, this implementation is a bit silly, since in order to convert the
494 trees to leaf streams, our tree_monadizer function has to visit every
495 node in the tree.  But if we needed to compare each tree to a large
496 set of other trees, we could arrange to monadize each tree only once,
497 and then run compare_streams on the monadized trees.
498
499 By the way, what if you have reason to believe that the fringes of
500 your trees are more likely to differ near the right edge than the left
501 edge?  If we reverse evaluation order in the tree_monadizer function,
502 as shown above when we replaced leaves with their ordinal position,
503 then the resulting streams would produce leaves from the right to the
504 left.
505
506 The idea of using continuations to characterize natural language meaning
507 ------------------------------------------------------------------------
508
509 We might a philosopher or a linguist be interested in continuations,
510 especially if efficiency of computation is usually not an issue?
511 Well, the application of continuations to the same-fringe problem
512 shows that continuations can manage order of evaluation in a
513 well-controlled manner.  In a series of papers, one of us (Barker) and
514 Ken Shan have argued that a number of phenomena in natural langauge
515 semantics are sensitive to the order of evaluation.  We can't
516 reproduce all of the intricate arguments here, but we can give a sense
517 of how the analyses use continuations to achieve an analysis of
518 natural language meaning.
519
520 **Quantification and default quantifier scope construal**.  
521
522 We saw in the copy-string example and in the same-fringe example that
523 local properties of a tree (whether a character is `S` or not, which
524 integer occurs at some leaf position) can control global properties of
525 the computation (whether the preceeding string is copied or not,
526 whether the computation halts or proceeds).  Local control of
527 surrounding context is a reasonable description of in-situ
528 quantification.
529
530     (1) John saw everyone yesterday.
531
532 This sentence means (roughly)
533
534     forall x . yesterday(saw x) john
535
536 That is, the quantifier *everyone* contributes a variable in the
537 direct object position, and a universal quantifier that takes scope
538 over the whole sentence.  If we have a lexical meaning function like
539 the following:
540
541 <pre>
542 let lex (s:string) k = match s with 
543   | "everyone" -> Node (Leaf "forall x", k "x")
544   | "someone" -> Node (Leaf "exists y", k "y")
545   | _ -> k s;;
546
547 let sentence1 = Node (Leaf "John", 
548                       Node (Node (Leaf "saw", 
549                                   Leaf "everyone"), 
550                             Leaf "yesterday"));;
551 </pre>
552
553 Then we can crudely approximate quantification as follows:
554
555 <pre>
556 # tree_monadize lex sentence1 (fun x -> x);;
557 - : string tree =
558 Node
559  (Leaf "forall x",
560   Node (Leaf "John", Node (Node (Leaf "saw", Leaf "x"), Leaf "yesterday")))
561 </pre>
562
563 In order to see the effects of evaluation order, 
564 observe what happens when we combine two quantifiers in the same
565 sentence:
566
567 <pre>
568 # let sentence2 = Node (Leaf "everyone", Node (Leaf "saw", Leaf "someone"));;
569 # tree_monadize lex sentence2 (fun x -> x);;
570 - : string tree =
571 Node
572  (Leaf "forall x",
573   Node (Leaf "exists y", Node (Leaf "x", Node (Leaf "saw", Leaf "y"))))
574 </pre>
575
576 The universal takes scope over the existential.  If, however, we
577 replace the usual tree_monadizer with tree_monadizer_rev, we get
578 inverse scope:
579
580 <pre>
581 # tree_monadize_rev lex sentence2 (fun x -> x);;
582 - : string tree =
583 Node
584  (Leaf "exists y",
585   Node (Leaf "forall x", Node (Leaf "x", Node (Leaf "saw", Leaf "y"))))
586 </pre>
587
588 There are many crucially important details about quantification that
589 are being simplified here, and the continuation treatment here is not
590 scalable for a number of reasons.  Nevertheless, it will serve to give
591 an idea of how continuations can provide insight into the behavior of
592 quantifiers.  
593
594
595 The Binary Tree monad
596 ---------------------
597
598 Of course, by now you may have realized that we have discovered a new
599 monad, the Binary Tree monad.  Just as mere lists are in fact a monad,
600 so are trees.  Here is the type constructor, unit, and bind:
601
602         type 'a tree = Leaf of 'a | Node of ('a tree) * ('a tree);;
603         let tree_unit (a: 'a) : 'a tree = Leaf a;;
604         let rec tree_bind (u : 'a tree) (f : 'a -> 'b tree) : 'b tree =
605             match u with
606             | Leaf a -> f a
607             | Node (l, r) -> Node (tree_bind l f, tree_bind r f);;
608
609 For once, let's check the Monad laws.  The left identity law is easy:
610
611     Left identity: bind (unit a) f = bind (Leaf a) f = f a
612
613 To check the other two laws, we need to make the following
614 observation: it is easy to prove based on `tree_bind` by a simple
615 induction on the structure of the first argument that the tree
616 resulting from `bind u f` is a tree with the same strucure as `u`,
617 except that each leaf `a` has been replaced with `f a`:
618
619                         .                         .
620                       __|__                     __|__
621                       |   |                     |   |
622                       a1  .                   f a1  .
623                          _|__                     __|__
624                          |  |                     |   |
625                          .  a5                    .  f a5
626            bind         _|__       f   =        __|__
627                         |  |                    |   |
628                         .  a4                   .  f a4
629                       __|__                   __|___
630                       |   |                   |    |
631                       a2  a3                f a2  f a3
632
633 Given this equivalence, the right identity law
634
635         Right identity: bind u unit = u
636
637 falls out once we realize that
638
639         bind (Leaf a) unit = unit a = Leaf a
640
641 As for the associative law,
642
643         Associativity: bind (bind u f) g = bind u (\a. bind (f a) g)
644
645 we'll give an example that will show how an inductive proof would
646 proceed.  Let `f a = Node (Leaf a, Leaf a)`.  Then
647
648                                                    .
649                                                ____|____
650                   .               .            |       |
651         bind    __|__   f  =    __|_    =      .       .
652                 |   |           |   |        __|__   __|__
653                 a1  a2        f a1 f a2      |   |   |   |
654                                              a1  a1  a1  a1
655
656 Now when we bind this tree to `g`, we get
657
658                     .
659                _____|______
660                |          |
661                .          .
662              __|__      __|__
663              |   |      |   |
664            g a1 g a1  g a1 g a1
665
666 At this point, it should be easy to convince yourself that
667 using the recipe on the right hand side of the associative law will
668 built the exact same final tree.
669
670 So binary trees are a monad.
671
672 Haskell combines this monad with the Option monad to provide a monad
673 called a
674 [SearchTree](http://hackage.haskell.org/packages/archive/tree-monad/0.2.1/doc/html/src/Control-Monad-SearchTree.html#SearchTree)
675 that is intended to represent non-deterministic computations as a tree.
676
677
678 What's this have to do with tree\_monadize?
679 --------------------------------------------
680
681 So we've defined a Tree monad:
682
683         type 'a tree = Leaf of 'a | Node of ('a tree) * ('a tree);;
684         let tree_unit (a: 'a) : 'a tree = Leaf a;;
685         let rec tree_bind (u : 'a tree) (f : 'a -> 'b tree) : 'b tree =
686             match u with
687             | Leaf a -> f a
688             | Node (l, r) -> Node (tree_bind l f, tree_bind r f);;
689
690 What's this have to do with the `tree_monadize` functions we defined earlier?
691
692         let rec tree_monadize (f : 'a -> 'b reader) (t : 'a tree) : 'b tree reader =
693             match t with
694             | Leaf a -> reader_bind (f a) (fun b -> reader_unit (Leaf b))
695             | Node (l, r) -> reader_bind (tree_monadize f l) (fun l' ->
696                                reader_bind (tree_monadize f r) (fun r' ->
697                                  reader_unit (Node (l', r'))));;
698
699 ... and so on for different monads?
700
701 The answer is that each of those `tree_monadize` functions is adding a Tree monad *layer* to a pre-existing Reader (and so on) monad. We discuss that further here: [[Monad Transformers]].
702