edits
[lambda.git] / week11.mdwn
1 These notes may change in the next few days (today is 30 Nov 2010).
2 The material here benefited from many discussions with Ken Shan.
3
4 [[!toc]]
5
6 ##[[Tree and List Zippers]]##
7
8 ##[[Coroutines and Aborts]]##
9
10 ##[[From Lists to Continuations]]##
11
12 This searches for the `n`th element of a list that satisfies the predicate `test`, and returns a pair containing the position of that element, and the element itself. Good. But now what if you wanted to retrieve a different kind of information, such as the `n`th element matching `test`, together with its preceding and succeeding elements? In a real situation, you'd want to develop some good strategy for reporting when the target element doesn't have a predecessor and successor; but we'll just simplify here and report them as having some default value:
13
14         let find_nth' (test : 'a -> bool) (n : int) (lst : 'a list) (default : 'a) : ('a * 'a * 'a) ->
15                 let rec helper (predecessor : 'a) n lst =
16                         match lst with
17                         | [] -> failwith "not found"
18                         | x :: xs when test x -> (if n = 1
19                                 then (predecessor, x, match xs with [] -> default | y::ys -> y)
20                                 else helper x (n - 1) xs
21                         )
22                         | x :: xs -> helper x n xs
23                 in helper default n lst;;
24
25 This duplicates a lot of the structure of `find_nth`; it just has enough different code to retrieve different information when the matching element is found. But now what if you wanted to retrieve yet a different kind of information...?
26
27 Ideally, there should be some way to factor out the code to find the target element---the `n`th element of the list satisfying the predicate `test`---from the code that retrieves the information you want once the target is found. We might build upon the initial `find_nth` function, since that returns the *position* of the matching element. We could hand that result off to some other function that's designed to retrieve information of a specific sort surrounding that position. But suppose our list has millions of elements, and the target element is at position 600512. The search function will already have traversed 600512 elements of the list looking for the target, then the retrieval function would have to *start again from the beginning* and traverse those same 600512 elements again. It could go a bit faster, since it doesn't have to check each element against `test` as it traverses. It already knows how far it has to travel. But still, this should seem a bit wasteful.
28
29 Here's an idea. What if we had some way of representing a list as "broken" at a specific point. For example, if our base list is:
30
31         [10; 20; 30; 40; 50; 60; 70; 80; 90]
32
33 we might imagine the list "broken" at position 3 like this (positions are numbered starting from 0):
34
35                     40;
36                 30;     50;
37             20;             60;
38         [10;                    70;
39                                     80;
40                                         90]
41
42 Then if we move one step forward in the list, it would be "broken" at position 4:
43
44                         50;
45                     40;     60;
46                 30;             70;
47             20;                     80;
48         [10;                            90]
49
50 If we had some convenient representation of these "broken" lists, then our search function could hand *that* off to the retrieval function, and the retrieval function could start right at the position where the list was broken, without having to start at the beginning and traverse many elements to get there. The retrieval function would also be able to inspect elements both forwards and backwards from the position where the list was "broken".
51
52 The kind of data structure we're looking for here is called a **list zipper**. To represent our first broken list, we'd use two lists: (1) containing the elements in the left branch, preceding the target element, *in the order reverse to their appearance in the base list*. (2) containing the target element and the rest of the list, in normal order. So:
53
54                     40;
55                 30;     50;
56             20;             60;
57         [10;                    70;
58                                     80;
59                                         90]
60
61 would be represented as `([30; 20; 10], [40; 50; 60; 70; 80; 90])`. To move forward in the base list, we pop the head element `40` off of the head element of the second list in the zipper, and push it onto the first list, getting `([40; 30; 20; 10], [50; 60; 70; 80; 90])`. To move backwards again, we pop off of the first list, and push it onto the second. To reconstruct the base list, we just "move backwards" until the first list is empty. (This is supposed to evoke the image of zipping up a zipper; hence the data structure's name.)
62
63 We had some discussio in seminar of the right way to understand the "zipper" metaphor. I think it's best to think of the tab of the zipper being here:
64
65                  t
66                   a
67                    b
68                     40;
69                 30;     50;
70             20;             60;
71         [10;                    70;
72                                     80;
73                                         90]
74
75 And imagine that you're just seeing the left half of a real-zipper, rotated 60 degrees counter-clockwise. When the list is all "zipped up", we've "move backwards" to the state where the first element is targetted:
76
77         ([], [10; 20; 30; 40; 50; 60; 70; 80; 90])
78
79 However you understand the "zipper" metaphor, this is a very handy datastructure, and it will become even more handy when we translate it over to more complicated base structures, like trees. To help get a good conceptual grip on how to do that, it's useful to introduce a kind of symbolism for talking about zippers. This is just a metalanguage notation, for us theorists; we don't need our programs to interpret the notation. We'll use a specification like this:
80
81         [10; 20; 30; *; 50; 60; 70; 80; 90], * filled by 40
82
83 to represent a list zipper where the break is at position 3, and the element occupying that position is 40. For a list zipper, this is implemented using the pairs-of-lists structure described above.
84
85
86 ##Tree Zippers##
87
88 Now how could we translate a zipper-like structure over to trees? What we're aiming for is a way to keep track of where we are in a tree, in the same way that the "broken" lists let us keep track of where we are in the base list.
89
90 It's important to set some ground rules for what will follow. If you don't understand these ground rules you will get confused. First off, for many uses of trees one wants some of the nodes or leafs in the tree to be *labeled* with additional information. It's important not to conflate the label with the node itself. Numerically one and the same piece of information---for example, the same `int`---could label two nodes of the tree without those nodes thereby being identical, as here:
91
92                 root
93                 / \
94               /     \
95             /  \    label 1
96           /      \
97         label 1  label 2
98
99 The leftmost leaf and the rightmost leaf have the same label; but they are different leafs. The leftmost leaf has a sibling leaf with the label 2; the rightmost leaf has no siblings that are leafs. Sometimes when one is diagramming trees, one will annotate the nodes with the labels, as above. Other times, when one is diagramming trees, one will instead want to annotate the nodes with tags to make it easier to refer to particular parts of the tree. So for instance, I could diagram the same tree as above as:
100
101                  1
102                 / \
103               2     \
104             /  \     5
105           /      \
106          3        4
107
108 Here I haven't drawn what the labels are. The leftmost leaf, the node tagged "3" in this diagram, doesn't have the label `3`. It has the label 1, as we said before. I just haven't put that into the diagram. The node tagged "2" doesn't have the label `2`. It doesn't have any label. The tree in this example only has information labeling its leafs, not any of its inner nodes. The identity of its inner nodes is exhausted by their position in the tree.
109
110 That is a second thing to note. In what follows, we'll only be working with *leaf-labeled* trees. In some uses of trees, one also wants labels on inner nodes. But we won't be discussing any such trees now. Our trees only have labels on their leafs. The diagrams below will tag all of the nodes, as in the second diagram above, and won't display what the leafs' labels are.
111
112 Final introductory comment: in particular applications, you may only need to work with binary trees---trees where internal nodes always have exactly two subtrees. That is what we'll work with in the homework, for example. But to get the guiding idea of how tree zippers work, it's helpful first to think about trees that permit nodes to have many subtrees. So that's how we'll start.
113
114 Suppose we have the following tree:
115
116                                  9200
117                             /      |  \
118                          /         |    \
119                       /            |      \
120                    /               |        \
121                 /                  |          \
122                500                920          950
123             /   |    \          /  |  \      /  |  \
124          20     50     80      91  92  93   94  95  96
125         1 2 3  4 5 6  7 8 9
126
127 This is a leaf-labeled tree whose labels aren't displayed. The `9200` and so on are tags to make it easier for us to refer to particular parts of the tree.
128
129 Suppose we want to represent that we're *at* the node marked `50`. We might use the following metalanguage notation to specify this:
130
131         {parent = ...; siblings = [subtree 20; *; subtree 80]}, * filled by subtree 50
132
133 This is modeled on the notation suggested above for list zippers. Here `subtree 20` refers to the whole subtree rooted at node `20`:
134
135           20
136          / | \
137         1  2  3
138
139 Similarly for `subtree 50` and `subtree 80`. We haven't said yet what goes in the `parent = ...` slot. Well, the parent of a subtree targetted on `node 50` should intuitively be a tree targetted on `node 500`:
140
141         {parent = ...; siblings = [*; subtree 920; subtree 950]}, * filled by subtree 500
142
143 And the parent of that targetted subtree should intuitively be a tree targetted on `node 9200`:
144
145         {parent = None; siblings = [*]}, * filled by tree 9200
146
147 This tree has no parents because it's the root of the base tree. Fully spelled out, then, our tree targetted on `node 50` would be:
148
149         {
150            parent = {
151               parent = {
152                  parent = None;
153                  siblings = [*]
154               }, * filled by tree 9200;
155               siblings = [*; subtree 920; subtree 950]
156            }, * filled by subtree 500;
157            siblings = [subtree 20; *; subtree 80]
158         }, * filled by subtree 50
159
160 In fact, there's some redundancy in this structure, at the points where we have `* filled by tree 9200` and `* filled by subtree 500`. Since node 9200 doesn't have any label attached to it, the subtree rooted in it is determined by the rest of this structure; and so too with `subtree 500`. So we could really work with:
161
162         {
163            parent = {
164               parent = {
165                  parent = None;
166                  siblings = [*]
167               },
168               siblings = [*; subtree 920; subtree 950]
169            },
170            siblings = [subtree 20; *; subtree 80]
171         }, * filled by subtree 50
172
173
174 We still do need to keep track of what fills the outermost targetted position---`* filled by subtree 50`---because that contain a subtree of arbitrary complexity, that is not determined by the rest of this data structure.
175
176 For simplicity, I'll continue to use the abbreviated form:
177
178         {parent = ...; siblings = [subtree 20; *; subtree 80]}, * filled by subtree 50
179
180 But that should be understood as standing for the more fully-spelled-out structure. Structures of this sort are called **tree zippers**. They should already seem intuitively similar to list zippers, at least in what we're using them to represent. I think it may also be helpful to call them **targetted trees**, though, and so will be switching back and forth between these different terms.
181
182 Moving left in our targetted tree that's targetted on `node 50` would be a matter of shifting the `*` leftwards:
183
184         {parent = ...; siblings = [*; subtree 50; subtree 80]}, * filled by subtree 20
185
186 and similarly for moving right. If the sibling list is implemented as a list zipper, you should already know how to do that. If one were designing a tree zipper for a more restricted kind of tree, however, such as a binary tree, one would probably not represent siblings with a list zipper, but with something more special-purpose and economical.
187
188 Moving downward in the tree would be a matter of constructing a tree targetted on some child of `node 20`, with the first part of the targetted tree above as its parent:
189
190         {
191            parent = {parent = ...; siblings = [*; subtree 50; subtree 80]};
192            siblings = [*; leaf 2; leaf 3]
193         }, * filled by leaf 1
194
195 How would we move upward in a tree? Well, we'd build a regular, untargetted tree with a root node---let's call it `20'`---and whose children are given by the outermost sibling list in the targetted tree above, after inserting the targetted subtree into the `*` position:
196
197                node 20'
198             /     |    \
199          /        |      \
200         leaf 1  leaf 2  leaf 3
201
202 We'll call this new untargetted tree `subtree 20'`. The result of moving upward from our previous targetted tree, targetted on `leaf 1`, would be the outermost `parent` element of that targetted tree, with `subtree 20'` being the subtree that fills that parent's target position `*`:
203
204         {
205            parent = ...;
206            siblings = [*; subtree 50; subtree 80]
207         }, * filled by subtree 20'
208
209 Or, spelling that structure out fully:
210
211         {
212            parent = {
213               parent = {
214                  parent = None;
215                  siblings = [*]
216               },
217               siblings = [*; subtree 920; subtree 950]
218            },
219            siblings = [*; subtree 50; subtree 80]
220         }, * filled by subtree 20'
221
222 Moving upwards yet again would get us:
223
224         {
225            parent = {
226               parent = None;
227               siblings = [*]
228            },
229            siblings = [*; subtree 920; subtree 950]
230         }, * filled by subtree 500'
231
232 where `subtree 500'` refers to a tree built from a root node whose children are given by the list `[*; subtree 50; subtree 80]`, with `subtree 20'` inserted into the `*` position. Moving upwards yet again would get us:
233
234         {
235            parent = None;
236            siblings = [*]
237         }, * filled by tree 9200'
238
239 where the targetted element is the root of our base tree. Like the "moving backward" operation for the list zipper, this "moving upward" operation is supposed to be reminiscent of closing a zipper, and that's why these data structures are called zippers.
240
241 We haven't given you a real implementation of the tree zipper, but only a suggestive notation. We have however told you enough that you should be able to implement it yourself. Or if you're lazy, you can read:
242
243 *       [[!wikipedia Zipper (data structure)]]
244 *       Huet, Gerard. ["Functional Pearl: The Zipper"](http://www.st.cs.uni-sb.de/edu/seminare/2005/advanced-fp/docs/huet-zipper.pdf) Journal of Functional Programming 7 (5): 549-554, September 1997.
245 *       As always, [Oleg](http://okmij.org/ftp/continuations/Continuations.html#zipper) takes this a few steps deeper.
246
247
248 ##Same-fringe using a zipper-based coroutine##
249
250 Recall back in [[Assignment4]], we asked you to enumerate the "fringe" of a leaf-labeled tree. Both of these trees (here I *am* drawing the labels in the diagram):
251
252             .                .
253            / \              / \
254           .   3            1   .
255          / \                  / \
256         1   2                2   3
257
258 have the same fringe: `[1;2;3]`. We also asked you to write a function that determined when two trees have the same fringe. The way you approached that back then was to enumerate each tree's fringe, and then compare the two lists for equality. Today, and then again in a later class, we'll encounter new ways to approach the problem of determining when two trees have the same fringe.
259
260
261 Supposing you did work out an implementation of the tree zipper, then one way to determine whether two trees have the same fringe would be: go downwards (and leftwards) in each tree as far as possible. Compare the targetted leaves. If they're different, stop because the trees have different fringes. If they're the same, then for each tree, move rightward if possible; if it's not (because you're at the rightmost position in a sibling list), more upwards then try again to move rightwards. Repeat until you are able to move rightwards. Once you do move rightwards, go downwards (and leftwards) as far as possible. Then you'll be targetted on the next leaf in the tree's fringe. The operations it takes to get to "the next leaf" may be different for the two trees. For example, in these trees:
262
263             .                .
264            / \              / \
265           .   3            1   .
266          / \                  / \
267         1   2                2   3
268
269 you won't move upwards at the same steps. Keep comparing "the next leafs" until they are different, or you exhaust the leafs of only one of the trees (then again the trees have different fringes), or you exhaust the leafs of both trees at the same time, without having found leafs with different labels. In this last case, the trees have the same fringe.
270
271 If your trees are very big---say, millions of leaves---you can imagine how this would be quicker and more memory-efficient than traversing each tree to construct a list of its fringe, and then comparing the two lists so built to see if they're equal. For one thing, the zipper method can abort early if the fringes diverge early, without needing to traverse or build a list containing the rest of each tree's fringe.
272
273 Let's sketch the implementation of this. We won't provide all the details for an implementation of the tree zipper, but we will sketch an interface for it.
274
275 First, we define a type for leaf-labeled, binary trees:
276
277         type 'a tree = Leaf of 'a | Node of ('a tree * 'a tree)
278
279 Next, the interface for our tree zippers. We'll help ourselves to OCaml's **record types**. These are nothing more than tuples with a pretty interface. Instead of saying:
280
281         # type blah = Blah of (int * int * (char -> bool));;
282
283 and then having to remember which element in the triple was which:
284
285         # let b1 = Blah (1, (fun c -> c = 'M'), 2);;
286         Error: This expression has type int * (char -> bool) * int
287        but an expression was expected of type int * int * (char -> bool)
288         # (* damnit *)
289         # let b1 = Blah (1, 2, (fun c -> c = 'M'));;
290         val b1 : blah = Blah (1, 2, <fun>)
291
292 records let you attach descriptive labels to the components of the tuple:
293
294         # type blah_record = { height : int; weight : int; char_tester : char -> bool };;
295         # let b2 = { height = 1; weight = 2; char_tester = fun c -> c = 'M' };;
296         val b2 : blah_record = {height = 1; weight = 2; char_tester = <fun>}
297         # let b3 = { height = 1; char_tester = (fun c -> c = 'K'); weight = 3 };; (* also works *)
298         val b3 : blah_record = {height = 1; weight = 3; char_tester = <fun>}
299
300 These were the strategies to extract the components of an unlabeled tuple:
301
302         let h = fst some_pair;; (* accessor functions fst and snd are only predefined for pairs *)
303
304         let (h, w, test) = b1;; (* works for arbitrary tuples *)
305
306         match b1 with
307         | (h, w, test) -> ...;; (* same as preceding *)
308
309 Here is how you can extract the components of a labeled record:
310
311         let h = b2.height;; (* handy! *)
312
313         let {height = h; weight = w; char_tester = test} = b2
314         in (* go on to use h, w, and test ... *)
315
316         match test with
317         | {height = h; weight = w; char_tester = test} ->
318                 (* go on to use h, w, and test ... *)
319
320 Anyway, using record types, we might define the tree zipper interface like so:
321
322         type 'a starred_level = Root | Starring_Left of 'a starred_nonroot | Starring_Right of 'a starred_nonroot
323         and 'a starred_nonroot = { parent : 'a starred_level; sibling: 'a tree };;
324
325         type 'a zipper = { level : 'a starred_level; filler: 'a tree };;
326
327         let rec move_botleft (z : 'a zipper) : 'a zipper =
328             (* returns z if the targetted node in z has no children *)
329             (* else returns move_botleft (zipper which results from moving down and left in z) *)
330
331 <!--
332             let {level; filler} = z
333             in match filler with
334             | Leaf _ -> z
335             | Node(left, right) ->
336                 let zdown = {level = Starring_Left {parent = level; sibling = right}; filler = left}
337                 in move_botleft zdown
338             ;;
339 -->
340
341         let rec move_right_or_up (z : 'a zipper) : 'a zipper option =
342             (* if it's possible to move right in z, returns Some (the result of doing so) *)
343             (* else if it's not possible to move any further up in z, returns None *)
344             (* else returns move_right_or_up (result of moving up in z) *)
345
346 <!--
347             let {level; filler} = z
348             in match level with
349             | Starring_Left {parent; sibling = right} -> Some {level = Starring_Right {parent; sibling = filler}; filler = right}
350             | Root -> None
351             | Starring_Right {parent; sibling = left} ->
352                 let z' = {level = parent; filler = Node(left, filler)}
353                 in move_right_or_up z'
354             ;;
355 -->
356
357 The following function takes an 'a tree and returns an 'a zipper focused on its root:
358
359         let new_zipper (t : 'a tree) : 'a zipper =
360             {level = Root; filler = t}
361             ;;
362
363 Finally, we can use a mutable reference cell to define a function that enumerates a tree's fringe until it's exhausted:
364
365         let make_fringe_enumerator (t: 'a tree) =
366             (* create a zipper targetting the botleft of t *)
367             let zbotleft = move_botleft (new_zipper t)
368             (* create a refcell initially pointing to zbotleft *)
369             in let zcell = ref (Some zbotleft)
370             (* construct the next_leaf function *)
371             in let next_leaf () : 'a option =
372                 match !zcell with
373                 | Some z -> (
374                     (* extract label of currently-targetted leaf *)
375                     let Leaf current = z.filler
376                     (* update zcell to point to next leaf, if there is one *)
377                     in let () = zcell := match move_right_or_up z with
378                         | None -> None
379                         | Some z' -> Some (move_botleft z')
380                     (* return saved label *)
381                     in Some current
382                 | None -> (* we've finished enumerating the fringe *)
383                     None
384                 )
385             (* return the next_leaf function *)
386             in next_leaf
387             ;;
388
389 Here's an example of `make_fringe_enumerator` in action:
390
391         # let tree1 = Leaf 1;;
392         val tree1 : int tree = Leaf 1
393         # let next1 = make_fringe_enumerator tree1;;
394         val next1 : unit -> int option = <fun>
395         # next1 ();;
396         - : int option = Some 1
397         # next1 ();;
398         - : int option = None
399         # next1 ();;
400         - : int option = None
401         # let tree2 = Node (Node (Leaf 1, Leaf 2), Leaf 3);;
402         val tree2 : int tree = Node (Node (Leaf 1, Leaf 2), Leaf 3)
403         # let next2 = make_fringe_enumerator tree2;;
404         val next2 : unit -> int option = <fun>
405         # next2 ();;
406         - : int option = Some 1
407         # next2 ();;
408         - : int option = Some 2
409         # next2 ();;
410         - : int option = Some 3
411         # next2 ();;
412         - : int option = None
413         # next2 ();;
414         - : int option = None
415
416 You might think of it like this: `make_fringe_enumerator` returns a little subprogram that will keep returning the next leaf in a tree's fringe, in the form `Some ...`, until it gets to the end of the fringe. After that, it will keep returning `None`.
417
418 Using these fringe enumerators, we can write our `same_fringe` function like this:
419
420         let same_fringe (t1 : 'a tree) (t2 : 'a tree) : bool =
421                 let next1 = make_fringe_enumerator t1
422                 in let next2 = make_fringe_enumerator t2
423                 in let rec loop () : bool =
424                         match next1 (), next2 () with
425                         | Some a, Some b when a = b -> loop ()
426                         | None, None -> true
427                         | _ -> false
428                 in loop ()
429                 ;;
430
431 The auxiliary `loop` function will keep calling itself recursively until a difference in the fringes has manifested itself---either because one fringe is exhausted before the other, or because the next leaves in the two fringes have different labels. If we get to the end of both fringes at the same time (`next1 (), next2 ()` matches the pattern `None, None`) then we've established that the trees do have the same fringe.
432
433 The technique illustrated here with our fringe enumerators is a powerful and important one. It's an example of what's sometimes called **cooperative threading**. A "thread" is a subprogram that the main computation spawns off. Threads are called "cooperative" when the code of the main computation and the thread fixes when control passes back and forth between them. (When the code doesn't control this---for example, it's determined by the operating system or the hardware in ways that the programmer can't predict---that's called "preemptive threading.") Cooperative threads are also sometimes called *coroutines* or *generators*.
434
435 With cooperative threads, one typically yields control to the thread, and then back again to the main program, multiple times. Here's the pattern in which that happens in our `same_fringe` function:
436
437         main program            next1 thread            next2 thread
438         ------------            ------------            ------------
439         start next1
440         (paused)                        starting
441         (paused)                        calculate first leaf
442         (paused)                        <--- return it
443         start next2                     (paused)                        starting
444         (paused)                        (paused)                        calculate first leaf
445         (paused)                        (paused)                        <-- return it
446         compare leaves          (paused)                        (paused)
447         call loop again         (paused)                        (paused)
448         call next1 again        (paused)                        (paused)
449         (paused)                        calculate next leaf     (paused)
450         (paused)                        <-- return it           (paused)
451         ... and so on ...
452
453 If you want to read more about these kinds of threads, here are some links:
454
455 <!-- *  [[!wikipedia Computer_multitasking]]
456 *       [[!wikipedia Thread_(computer_science)]] -->
457
458 *       [[!wikipedia Coroutine]]
459 *       [[!wikipedia Iterator]]
460 *       [[!wikipedia Generator_(computer_science)]]
461 *       [[!wikipedia Fiber_(computer_science)]]
462 <!-- *  [[!wikipedia Green_threads]]
463 *       [[!wikipedia Protothreads]] -->
464
465 The way we built cooperative threads here crucially relied on two heavyweight tools. First, it relied on our having a data structure (the tree zipper) capable of being a static snapshot of where we left off in the tree whose fringe we're enumerating. Second, it relied on our using mutable reference cells so that we could update what the current snapshot (that is, tree zipper) was, so that the next invocation of the `next_leaf` function could start up again where the previous invocation left off.
466
467 It's possible to build cooperative threads without using those tools, however. Some languages have a native syntax for them. Here's how we'd write the same-fringe solution above using native coroutines in the language Lua:
468
469         > function fringe_enumerator (tree)
470             if tree.leaf then
471                 coroutine.yield (tree.leaf)
472             else
473                 fringe_enumerator (tree.left)
474                 fringe_enumerator (tree.right)
475             end
476         end
477         
478         > function same_fringe (tree1, tree2)
479             local next1 = coroutine.wrap (fringe_enumerator)
480             local next2 = coroutine.wrap (fringe_enumerator)
481             local function loop (leaf1, leaf2)
482                 if leaf1 or leaf2 then
483                     return leaf1 == leaf2 and loop( next1(), next2() )
484                 elseif not leaf1 and not leaf2 then
485                     return true
486                 else
487                     return false
488                 end
489             end
490             return loop (next1(tree1), next2(tree2))
491         end
492         
493         > return same_fringe ( {leaf=1}, {leaf=2})
494         false
495         
496         > return same_fringe ( {leaf=1}, {leaf=1})
497         true
498         
499         > return same_fringe ( {left = {leaf=1}, right = {left = {leaf=2}, right = {leaf=3}}},
500             {left = {left = {leaf=1}, right = {leaf=2}}, right = {leaf=3}} )
501         true
502
503 We're going to think about the underlying principles to this execution pattern, and instead learn how to implement it from scratch---without necessarily having zippers to rely on.
504
505
506 ##Exceptions and Aborts##
507
508 To get a better understanding of how that execution patter works, we'll add yet a second execution pattern to our plate, and then think about what they have in common.
509
510 While writing OCaml code, you've probably come across errors. In fact, you've probably come across errors of two sorts. One sort of error comes about when you've got syntax errors or type errors and the OCaml interpreter isn't even able to understand your code:
511
512         # let lst = [1; 2] in
513           "a" :: lst;;
514         Error: This expression has type int list
515                    but an expression was expected of type string list
516
517 But you may also have encountered other kinds of error, that arise while your program is running. For example:
518
519         # 1/0;;
520         Exception: Division_by_zero.
521         # List.nth [1;2] 10;;
522         Exception: Failure "nth".
523
524 These "Exceptions" are **run-time errors**. OCaml will automatically detect some of them, like when you attempt to divide by zero. Other exceptions are *raised* by code. For instance, here is the implementation of `List.nth`:
525
526         let nth l n =
527           if n < 0 then invalid_arg "List.nth" else
528           let rec nth_aux l n =
529                 match l with
530                 | [] -> failwith "nth"
531                 | a::l -> if n = 0 then a else nth_aux l (n-1)
532           in nth_aux l n
533
534 Notice the two clauses `invalid_arg "List.nth"` and `failwith "nth"`. These are two helper functions which are shorthand for:
535
536         raise (Invalid_argument "List.nth");;
537         raise (Failure "nth");;
538
539 where `Invalid_argument "List.nth"` is a value of type `exn`, and so too `Failure "nth"`. When you have some value `ex` of type `exn` and evaluate the expression:
540
541         raise ex
542
543 the effect is for the program to immediately stop without evaluating any further code:
544
545         # let xcell = ref 0;;
546         val xcell : int ref = {contents = 0}
547         # let ex = Failure "test"
548           in let _ = raise ex
549           in xcell := 1;;
550         Exception: Failure "test".
551         # !xcell;;
552         - : int = 0
553
554 Notice that the line `xcell := 1` was never evaluated, so the contents of `xcell` are still `0`.
555
556 I said when you evaluate the expression:
557
558         raise ex
559
560 the effect is for the program to immediately stop. That's not exactly true. You can also programmatically arrange to *catch* errors, without the program necessarily stopping. In OCaml we do that with a `try ... with PATTERN -> ...` construct, analogous to the `match ... with PATTERN -> ...` construct:
561
562         # let foo x =
563             try
564                 if x = 1 then 10
565                 else if x = 2 then raise (Failure "two")
566                 else raise (Failure "three")
567             with Failure "two" -> 20
568             ;;
569         val foo : int -> int = <fun>
570         # foo 1;;
571         - : int = 10
572         # foo 2;;
573         - : int = 20
574         # foo 3;;
575         Exception: Failure "three".
576
577 Notice what happens here. If we call `foo 1`, then the code between `try` and `with` evaluates to `10`, with no exceptions being raised. That then is what the entire `try ... with ...` block evaluates to; and so too what `foo 1` evaluates to. If we call `foo 2`, then the code between `try` and `with` raises an exception `Failure "two"`. The pattern in the `with` clause matches that exception, so we get instead `20`. If we call `foo 3`, we again raise an exception. This exception isn't matched by the `with` block, so it percolates up to the top of the program, and then the program immediately stops.
578
579 So what I should have said is that when you evaluate the expression:
580
581         raise ex
582
583 *and that exception is never caught*, then the effect is for the program to immediately stop.
584
585 Of course, it's possible to handle errors in other ways too. There's no reason why the implementation of `List.nth` *had* to do things this way. They might instead have returned `Some a` when the list had an nth member `a`, and `None` when it does not. But it's pedagogically useful for us to think about this pattern now.
586
587 When an exception is raised, it percolates up through the code that called it, until it finds a surrounding `try ... with ...` that matches it. That might not be the first `try ... with ...` that it encounters. For example:
588
589         # try
590             try
591                 raise (Failure "blah")
592             with Failure "fooey" -> 10
593           with Failure "blah" -> 20;;
594         - : int = 20
595
596 The matching `try ... with ...` block need not *lexically surround* the site where the error was raised:
597
598         # let foo b x =
599             try
600                 b x
601             with Failure "blah" -> 20
602         in let bar x =
603             raise (Failure "blah")
604         in foo bar 0;;
605         - : int = 20
606
607 Here we call `foo bar 0`, and `foo` in turn calls `bar 0`, and `bar` raises the exception. Since there's no matching `try ... with ...` block in `bar`, we percolate back up the history of *who called this function?* and find a matching `try ... with ...` block in `foo`. This catches the error and so then the `try ... with ...` block in `foo` that called `bar` in the first place will evaluate to `20`.
608
609 OK, now this exception-handling apparatus does exemplify the second execution pattern we want to focus on. But it may bring it into clearer focus if we simplify the pattern even more. Imagine we could write code like this instead:
610
611         # let foo x =
612             try
613                 (if x = 1 then 10
614                 else abort 20) + 1
615             end
616             ;;
617
618 then if we called `foo 1`, we'd get the result `11`. If we called `foo 2`, on the other hand, we'd get `20` (note, not `21`). This exemplifies the same interesting "jump out of this part of the code" behavior that the `try ... raise ... with ...` code does, but without the details of matching which exception was raised, and handling the exception to produce a new result.
619
620 Many programming languages have this simplified exceution pattern, either instead of or alongside a `try ... with ...`-like pattern. In Lua and many other languages, `abort` is instead called `return`. The preceding example would be written:
621
622         > function foo(x)
623             local value
624             if (x == 1) then
625                 value = 10
626             else
627                 return 20
628             end
629             return value + 1
630         end
631         
632         > return foo(1)
633         11
634         
635         > return foo(2)
636         20
637
638 Okay, so that's our second execution pattern.
639
640 ##What do these have in common?##
641
642 In both of these patterns, we need to have some way to take a snapshot of where we are in the evaluation of a complex piece of code, so that we might later resume execution at that point. In the coroutine example, the two threads need to have a snapshot of where they were in the enumeration of their tree's leaves. In the abort example, we need to have a snapshot of where to pick up again if some embedded piece of code aborts. Sometimes we might distill that snapshot into a datastructure like a zipper. But we might not always know how to do so; and learning how to think about these snapshots without the help of zippers will help us see patterns and similarities we might otherwise miss.
643
644 A more general way to think about these snapshots is to think of the code we're taking a snapshot of as a *function.* For example, in this code:
645
646         let foo x =
647             try
648                 (if x = 1 then 10
649                 else abort 20) + 1
650             end
651         in (foo 2) + 1;;
652
653 we can imagine a box:
654
655         let foo x =
656         +---------------------------+
657         |   try                     |
658         |       (if x = 1 then 10   |
659         |       else abort 20) + 1  |
660         |   end                     |
661         +---------------------------+
662         in (foo 2) + 1;;
663
664 and as we're about to enter the box, we want to take a snapshot of the code *outside* the box. If we decide to abort, we'd be aborting to that snapshotted code.
665
666 <!--
667 # #require "delimcc";;
668 # open Delimcc;;
669 # let reset body = let p = new_prompt () in push_prompt p (body p);;
670 val reset : ('a Delimcc.prompt -> unit -> 'a) -> 'a = <fun>
671 # let foo x = reset(fun p () -> (shift p (fun k -> if x = 1 then k 10 else 20)) + 1) in (foo 1) + 100;;
672 - : int = 111
673 # let foo x = reset(fun p () -> (shift p (fun k -> if x = 1 then k 10 else 20)) + 1) in (foo 2) + 100;;
674 - : int = 120
675 -->
676
677
678
679
680 --------------------------------------
681
682 In coming weeks, we'll learn about a different way to create threads, that relies on **continuations** rather than on those two tools. All of these tools are inter-related. As Oleg says, "Zipper can be viewed as a delimited continuation reified as a data structure." These different tools are also inter-related with monads. Many of these tools can be used to define the others. We'll explore some of the connections between them in the remaining weeks, but we encourage you to explore more.
683
684
685 ##Introducing Continuations##
686
687 A continuation is "the rest of the program." Or better: an **delimited continuation** is "the rest of the program, up to a certain boundary." An **undelimited continuation** is "the rest of the program, period."
688
689 Even if you haven't read specifically about this notion (for example, even if you haven't read Chris and Ken's work on using continuations in natural language semantics), you'll have brushed shoulders with it already several times in this course.
690
691 A naive semantics for atomic sentences will say the subject term is of type `e`, and the predicate of type `e -> t`, and that the subject provides an argument to the function expressed by the predicate.
692
693 Monatague proposed we instead take subject terms to be of type `(e -> t) -> t`, and that now it'd be the predicate (still of type `e -> t`) that provides an argument to the function expressed by the subject.
694
695 If all the subject did then was supply an `e` to the `e -> t` it receives as an argument, we wouldn't have gained anything we weren't already able to do. But of course, there are other things the subject can do with the `e -> t` it receives as an argument. For instance, it can check whether anything in the domain satisfies that `e -> t`; or whether most things do; and so on.
696
697 This inversion of who is the argument and who is the function receiving the argument is paradigmatic of working with continuations. We did the same thing ourselves back in the early days of the seminar, for example in our implementation of pairs. In the untyped lambda calculus, we identified the pair `(x, y)` with a function:
698
699         \handler. handler x y
700
701 A pair-handling function would accept the two elements of a pair as arguments, and then do something with one or both of them. The important point here is that the handler was supplied as an argument to the pair. Eventually, the handler would itself be supplied with arguments. But only after it was supplied as an argument to the pair. This inverts the order you'd expect about what is the data or argument, and what is the function that operates on it.
702
703 Consider a complex computation, such as:
704
705         1 + 2 * (1 - g (3 + 4))
706
707 Part of this computation---`3 + 4`---leads up to supplying `g` with an argument. The rest of the computation---`1 + 2 * (1 - ___)`---waits for the result of applying `g` to that argument and will go on to do something with it (inserting the result into the `___` slot). That "rest of the computation" can be regarded as a function:
708
709         \result. 1 + 2 * (1 - result)
710
711 This function will be applied to whatever is the result of `g (3 + 4)`. So this function can be called the *continuation* of that application of `g`. For some purposes, it's useful to be able to invert the function/argument order here, and rather than supplying the result of applying `g` to the continuation, we instead supply the continuation to `g`. Well, not to `g` itself, since `g` only wants a single `int` argument. But we might build some `g`-like function which accepts not just an `int` argument like `g` does, but also a continuation argument.
712
713 Go back and read the material on "Aborting a Search Through a List" in [[Week4]] for an example of doing this.
714
715 In very general terms, the strategy is to work with functions like this:
716
717         let g' k (i : int) =
718                 ... do stuff ...
719                 ... if you want to abort early, supply an argument to k ...
720                 ... do more stuff ...
721                 ... normal result
722         in let gcon = fun result -> 1 + 2 * (1 - result)
723         in gcon (g' gcon (3 + 4))
724
725 It's a convention to use variables like `k` for continuation arguments. If the function `g'` never supplies an argument to its contination argument `k`, but instead just finishes evaluating to a normal result, that normal result will be delivered to `g'`'s continuation `gcon`, just as happens when we don't pass around any explicit continuation variables.
726
727 The above snippet of OCaml code doesn't really capture what happens when we pass explicit continuation variables. For suppose that inside `g'`, we do supply an argument to `k`. That would go into the `result` parameter in `gcon`. But then what happens once we've finished evaluating the application of `gcon` to that `result`? In the OCaml snippet above, the final value would then bubble up through the context in the body of `g'` where `k` was applied, and eventually out to the final line of the snippet, where it once again supplied an argument to `gcon`. That's not what happens with a real continuation. A real continuation works more like this:
728
729         let g' k (i : int) =
730                 ... do stuff ...
731                 ... if you want to abort early, supply an argument to k ...
732                 ... do more stuff ...
733                 ... normal result
734         in let gcon = fun result ->
735                 let final_value = 1 + 2 * (1 - result)
736                 in end_program_with final_value
737         in gcon (g' gcon (3 + 4))
738
739 So once we've finished evaluating the application of `gcon` to a `result`, the program is finished. (This is how undelimited continuations behave. We'll discuss delimited continuations later.)
740
741 So now, guess what would be the result of doing the following:
742
743         let g' k (i : int) =
744                 1 + k i
745         in let gcon = fun result ->
746                 let final_value = (1, result)
747                 in end_program_with final_value
748         in gcon (g' gcon (3 + 4))
749
750 <!-- (1, 7) ... explain why not (1, 8) -->
751
752
753 Refunctionalizing zippers: from lists to continuations
754 ------------------------------------------------------
755
756 If zippers are continuations reified (defuntionalized), then one route
757 to continuations is to re-functionalize a zipper.  Then the
758 concreteness and understandability of the zipper provides a way of
759 understanding and equivalent treatment using continuations.
760
761 Let's work with lists of chars for a change.  To maximize readability, we'll
762 indulge in an abbreviatory convention that "abSd" abbreviates the
763 list `['a'; 'b'; 'S'; 'd']`.
764
765 We will set out to compute a deceptively simple-seeming **task: given a
766 string, replace each occurrence of 'S' in that string with a copy of
767 the string up to that point.**
768
769 We'll define a function `t` (for "task") that maps strings to their
770 updated version.
771
772 Expected behavior:
773
774 <pre>
775 t "abSd" ~~> "ababd"
776 </pre>   
777
778
779 In linguistic terms, this is a kind of anaphora
780 resolution, where `'S'` is functioning like an anaphoric element, and
781 the preceding string portion is the antecedent.
782
783 This deceptively simple task gives rise to some mind-bending complexity.
784 Note that it matters which 'S' you target first (the position of the *
785 indicates the targeted 'S'):
786
787 <pre>
788     t "aSbS" 
789         *
790 ~~> t "aabS" 
791           *
792 ~~> "aabaab"
793 </pre>
794
795 versus
796
797 <pre>
798     t "aSbS"
799           *
800 ~~> t "aSbaSb" 
801         *
802 ~~> t "aabaSb"
803            *
804 ~~> "aabaaabab"
805 </pre>   
806
807 versus
808
809 <pre>
810     t "aSbS"
811           *
812 ~~> t "aSbaSb"
813            *
814 ~~> t "aSbaaSbab"
815             *
816 ~~> t "aSbaaaSbaabab"
817              *
818 ~~> ...
819 </pre>
820
821 Aparently, this task, as simple as it is, is a form of computation,
822 and the order in which the `'S'`s get evaluated can lead to divergent
823 behavior.
824
825 For now, we'll agree to always evaluate the leftmost `'S'`, which
826 guarantees termination, and a final string without any `'S'` in it.
827
828 This is a task well-suited to using a zipper.  We'll define a function
829 `tz` (for task with zippers), which accomplishes the task by mapping a
830 char list zipper to a char list.  We'll call the two parts of the
831 zipper `unzipped` and `zipped`; we start with a fully zipped list, and
832 move elements to the zipped part by pulling the zipped down until the
833 entire list has been unzipped (and so the zipped half of the zipper is empty).
834
835 <pre>
836 type 'a list_zipper = ('a list) * ('a list);;
837
838 let rec tz (z:char list_zipper) = 
839     match z with (unzipped, []) -> List.rev(unzipped) (* Done! *)
840                | (unzipped, 'S'::zipped) -> tz ((List.append unzipped unzipped), zipped) 
841                | (unzipped, target::zipped) -> tz (target::unzipped, zipped);; (* Pull zipper *)
842
843 # tz ([], ['a'; 'b'; 'S'; 'd']);;
844 - : char list = ['a'; 'b'; 'a'; 'b'; 'd']
845
846 # tz ([], ['a'; 'S'; 'b'; 'S']);;
847 - : char list = ['a'; 'a'; 'b'; 'a'; 'a'; 'b']
848 </pre>
849
850 Note that this implementation enforces the evaluate-leftmost rule.
851 Task completed.
852
853 One way to see exactly what is going on is to watch the zipper in
854 action by tracing the execution of `tz`.  By using the `#trace`
855 directive in the Ocaml interpreter, the system will print out the
856 arguments to `tz` each time it is (recurcively) called.  Note that the
857 lines with left-facing arrows (`<--`) show (recursive) calls to `tz`,
858 giving the value of its argument (a zipper), and the lines with
859 right-facing arrows (`-->`) show the output of each recursive call, a
860 simple list.  
861
862 <pre>
863 # #trace tz;;
864 t1 is now traced.
865 # tz ([], ['a'; 'b'; 'S'; 'd']);;
866 tz <-- ([], ['a'; 'b'; 'S'; 'd'])
867 tz <-- (['a'], ['b'; 'S'; 'd'])         (* Pull zipper *)
868 tz <-- (['b'; 'a'], ['S'; 'd'])         (* Pull zipper *)
869 tz <-- (['b'; 'a'; 'b'; 'a'], ['d'])    (* Special step *)
870 tz <-- (['d'; 'b'; 'a'; 'b'; 'a'], [])  (* Pull zipper *)
871 tz --> ['a'; 'b'; 'a'; 'b'; 'd']        (* Output reversed *)
872 tz --> ['a'; 'b'; 'a'; 'b'; 'd']
873 tz --> ['a'; 'b'; 'a'; 'b'; 'd']
874 tz --> ['a'; 'b'; 'a'; 'b'; 'd']
875 tz --> ['a'; 'b'; 'a'; 'b'; 'd']
876 - : char list = ['a'; 'b'; 'a'; 'b'; 'd'] 
877 </pre>
878
879 The nice thing about computations involving lists is that it's so easy
880 to visualize them as a data structure.  Eventually, we want to get to
881 a place where we can talk about more abstract computations.  In order
882 to get there, we'll first do the exact same thing we just did with
883 concrete zipper using procedures.  
884
885 Think of a list as a procedural recipe: `['a'; 'b'; 'S'; 'd']` 
886 is the result of the computation `a::(b::(S::(d::[])))` (or, in our old
887 style, `makelist a (makelist b (makelist S (makelist c empty)))`).
888 The recipe for constructing the list goes like this:
889
890 <pre>
891 (0)  Start with the empty list []
892 (1)  make a new list whose first element is 'd' and whose tail is the list constructed in step (0)
893 (2)  make a new list whose first element is 'S' and whose tail is the list constructed in step (1)
894 -----------------------------------------
895 (3)  make a new list whose first element is 'b' and whose tail is the list constructed in step (2)
896 (4)  make a new list whose first element is 'a' and whose tail is the list constructed in step (3)
897 </pre>
898
899 What is the type of each of these steps?  Well, it will be a function
900 from the result of the previous step (a list) to a new list: it will
901 be a function of type `char list -> char list`.  We'll call each step
902 (or group of steps) a **continuation** of the recipe.  So in this
903 context, a continuation is a function of type `char list -> char
904 list`.  For instance, the continuation corresponding to the portion of
905 the recipe below the horizontal line is the function `fun (tail:char
906 list) -> a::(b::tail)`.
907
908 This means that we can now represent the unzipped part of our
909 zipper--the part we've already unzipped--as a continuation: a function
910 describing how to finish building the list.  We'll write a new
911 function, `tc` (for task with continuations), that will take an input
912 list (not a zipper!) and a continuation and return a processed list.
913 The structure and the behavior will follow that of `tz` above, with
914 some small but interesting differences.  We've included the orginal
915 `tz` to facilitate detailed comparison:
916
917 <pre>
918 let rec tz (z:char list_zipper) = 
919     match z with (unzipped, []) -> List.rev(unzipped) (* Done! *)
920                | (unzipped, 'S'::zipped) -> tz ((List.append unzipped unzipped), zipped) 
921                | (unzipped, target::zipped) -> tz (target::unzipped, zipped);; (* Pull zipper *)
922
923 let rec tc (l: char list) (c: (char list) -> (char list)) =
924   match l with [] -> List.rev (c [])
925              | 'S'::zipped -> tc zipped (fun x -> c (c x))
926              | target::zipped -> tc zipped (fun x -> target::(c x));;
927
928 # tc ['a'; 'b'; 'S'; 'd'] (fun x -> x);;
929 - : char list = ['a'; 'b'; 'a'; 'b']
930
931 # tc ['a'; 'S'; 'b'; 'S'] (fun x -> x);;
932 - : char list = ['a'; 'a'; 'b'; 'a'; 'a'; 'b']
933 </pre>
934
935 To emphasize the parallel, I've re-used the names `zipped` and
936 `target`.  The trace of the procedure will show that these variables
937 take on the same values in the same series of steps as they did during
938 the execution of `tz` above.  There will once again be one initial and
939 four recursive calls to `tc`, and `zipped` will take on the values
940 `"bSd"`, `"Sd"`, `"d"`, and `""` (and, once again, on the final call,
941 the first `match` clause will fire, so the the variable `zipper` will
942 not be instantiated).
943
944 I have not called the functional argument `unzipped`, although that is
945 what the parallel would suggest.  The reason is that `unzipped` is a
946 list, but `c` is a function.  That's the most crucial difference, the
947 point of the excercise, and it should be emphasized.  For instance,
948 you can see this difference in the fact that in `tz`, we have to glue
949 together the two instances of `unzipped` with an explicit (and
950 relatively inefficient) `List.append`.
951 In the `tc` version of the task, we simply compose `c` with itself: 
952 `c o c = fun x -> c (c x)`.
953
954 Why use the identity function as the initial continuation?  Well, if
955 you have already constructed the initial list `"abSd"`, what's the next
956 step in the recipe to produce the desired result, i.e, the very same
957 list, `"abSd"`?  Clearly, the identity continuation.
958
959 A good way to test your understanding is to figure out what the
960 continuation function `c` must be at the point in the computation when
961 `tc` is called with the first argument `"Sd"`.  Two choices: is it
962 `fun x -> a::b::x`, or it is `fun x -> b::a::x`?  The way to see if
963 you're right is to execute the following command and see what happens:
964
965     tc ['S'; 'd'] (fun x -> 'a'::'b'::x);;
966
967 There are a number of interesting directions we can go with this task.
968 The reason this task was chosen is because it can be viewed as a
969 simplified picture of a computation using continuations, where `'S'`
970 plays the role of a control operator with some similarities to what is
971 often called `shift`.  In the analogy, the input list portrays a
972 sequence of functional applications, where `[f1; f2; f3; x]` represents
973 `f1(f2(f3 x))`.  The limitation of the analogy is that it is only
974 possible to represent computations in which the applications are
975 always right-branching, i.e., the computation `((f1 f2) f3) x` cannot
976 be directly represented.
977
978 One possibile development is that we could add a special symbol `'#'`,
979 and then the task would be to copy from the target `'S'` only back to
980 the closest `'#'`.  This would allow the task to simulate delimited
981 continuations with embedded prompts.
982
983 The reason the task is well-suited to the list zipper is in part
984 because the list monad has an intimate connection with continuations.
985 The following section explores this connection.  We'll return to the
986 list task after talking about generalized quantifiers below.
987
988
989 Rethinking the list monad
990 -------------------------
991
992 To construct a monad, the key element is to settle on a type
993 constructor, and the monad more or less naturally follows from that.
994 We'll remind you of some examples of how monads follow from the type
995 constructor in a moment.  This will involve some review of familair
996 material, but it's worth doing for two reasons: it will set up a
997 pattern for the new discussion further below, and it will tie together
998 some previously unconnected elements of the course (more specifically,
999 version 3 lists and monads).
1000
1001 For instance, take the **Reader Monad**.  Once we decide that the type
1002 constructor is
1003
1004     type 'a reader = env -> 'a
1005
1006 then the choice of unit and bind is natural:
1007
1008     let r_unit (a : 'a) : 'a reader = fun (e : env) -> a
1009
1010 The reason this is a fairly natural choice is that because the type of
1011 an `'a reader` is `env -> 'a` (by definition), the type of the
1012 `r_unit` function is `'a -> env -> 'a`, which is an instance of the
1013 type of the *K* combinator.  So it makes sense that *K* is the unit
1014 for the reader monad.
1015
1016 Since the type of the `bind` operator is required to be
1017
1018     r_bind : ('a reader) -> ('a -> 'b reader) -> ('b reader)
1019
1020 We can reason our way to the traditional reader `bind` function as
1021 follows. We start by declaring the types determined by the definition
1022 of a bind operation:
1023
1024     let r_bind (u : 'a reader) (f : 'a -> 'b reader) : ('b reader) = ...
1025
1026 Now we have to open up the `u` box and get out the `'a` object in order to
1027 feed it to `f`.  Since `u` is a function from environments to
1028 objects of type `'a`, the way we open a box in this monad is
1029 by applying it to an environment:
1030
1031 <pre>
1032         ... f (u e) ...
1033 </pre>
1034
1035 This subexpression types to `'b reader`, which is good.  The only
1036 problem is that we made use of an environment `e` that we didn't already have,
1037 so we must abstract over that variable to balance the books:
1038
1039         fun e -> f (u e) ...
1040
1041 [To preview the discussion of the Curry-Howard correspondence, what
1042 we're doing here is constructing an intuitionistic proof of the type,
1043 and using the Curry-Howard labeling of the proof as our bind term.]
1044
1045 This types to `env -> 'b reader`, but we want to end up with `env ->
1046 '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:
1047
1048 <pre>
1049 r_bind (u : 'a reader) (f : 'a -> 'b reader) : ('b reader) = f (u e) e         
1050 </pre>
1051
1052 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.
1053
1054 [The bind we cite here is a condensed version of the careful `let a = u e in ...`
1055 constructions we provided in earlier lectures.  We use the condensed
1056 version here in order to emphasize similarities of structure across
1057 monads.]
1058
1059 The **State Monad** is similar.  Once we've decided to use the following type constructor:
1060
1061     type 'a state = store -> ('a, store)
1062
1063 Then our unit is naturally:
1064
1065     let s_unit (a : 'a) : ('a state) = fun (s : store) -> (a, s)
1066
1067 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:
1068
1069     let s_bind (u : 'a state) (f : 'a -> 'b state) : 'b state = 
1070                 ... f (...) ...
1071
1072 But unlocking the `u` box is a little more complicated.  As before, we
1073 need to posit a state `s` that we can apply `u` to.  Once we do so,
1074 however, we won't have an `'a`, we'll have a pair whose first element
1075 is an `'a`.  So we have to unpack the pair:
1076
1077         ... let (a, s') = u s in ... (f a) ...
1078
1079 Abstracting over the `s` and adjusting the types gives the result:
1080
1081         let s_bind (u : 'a state) (f : 'a -> 'b state) : 'b state = 
1082                 fun (s : store) -> let (a, s') = u s in f a s'
1083
1084 The **Option/Maybe Monad** doesn't follow the same pattern so closely, so we
1085 won't pause to explore it here, though conceptually its unit and bind
1086 follow just as naturally from its type constructor.
1087
1088 Our other familiar monad is the **List Monad**, which we were told
1089 looks like this:
1090
1091     type 'a list = ['a];;
1092     l_unit (a : 'a) = [a];;
1093     l_bind u f = List.concat (List.map f u);;
1094
1095 Thinking through the list monad will take a little time, but doing so
1096 will provide a connection with continuations.
1097
1098 Recall that `List.map` takes a function and a list and returns the
1099 result to applying the function to the elements of the list:
1100
1101     List.map (fun i -> [i;i+1]) [1;2] ~~> [[1; 2]; [2; 3]]
1102
1103 and List.concat takes a list of lists and erases the embdded list
1104 boundaries:
1105
1106     List.concat [[1; 2]; [2; 3]] ~~> [1; 2; 2; 3]
1107
1108 And sure enough, 
1109
1110     l_bind [1;2] (fun i -> [i, i+1]) ~~> [1; 2; 2; 3]
1111
1112 Now, why this unit, and why this bind?  Well, ideally a unit should
1113 not throw away information, so we can rule out `fun x -> []` as an
1114 ideal unit.  And units should not add more information than required,
1115 so there's no obvious reason to prefer `fun x -> [x,x]`.  In other
1116 words, `fun x -> [x]` is a reasonable choice for a unit.
1117
1118 As for bind, an `'a list` monadic object contains a lot of objects of
1119 type `'a`, and we want to make use of each of them (rather than
1120 arbitrarily throwing some of them away).  The only
1121 thing we know for sure we can do with an object of type `'a` is apply
1122 the function of type `'a -> 'a list` to them.  Once we've done so, we
1123 have a collection of lists, one for each of the `'a`'s.  One
1124 possibility is that we could gather them all up in a list, so that
1125 `bind' [1;2] (fun i -> [i;i]) ~~> [[1;1];[2;2]]`.  But that restricts
1126 the object returned by the second argument of `bind` to always be of
1127 type `'b list list`.  We can elimiate that restriction by flattening
1128 the list of lists into a single list: this is
1129 just List.concat applied to the output of List.map.  So there is some logic to the
1130 choice of unit and bind for the list monad.  
1131
1132 Yet we can still desire to go deeper, and see if the appropriate bind
1133 behavior emerges from the types, as it did for the previously
1134 considered monads.  But we can't do that if we leave the list type as
1135 a primitive Ocaml type.  However, we know several ways of implementing
1136 lists using just functions.  In what follows, we're going to use type
1137 3 lists, the right fold implementation (though it's important and
1138 intriguing to wonder how things would change if we used some other
1139 strategy for implementating lists).  These were the lists that made
1140 lists look like Church numerals with extra bits embdded in them:
1141
1142     empty list:                fun f z -> z
1143     list with one element:     fun f z -> f 1 z
1144     list with two elements:    fun f z -> f 2 (f 1 z)
1145     list with three elements:  fun f z -> f 3 (f 2 (f 1 z))
1146
1147 and so on.  To save time, we'll let the OCaml interpreter infer the
1148 principle types of these functions (rather than inferring what the
1149 types should be ourselves):
1150
1151         # fun f z -> z;;
1152         - : 'a -> 'b -> 'b = <fun>
1153         # fun f z -> f 1 z;;
1154         - : (int -> 'a -> 'b) -> 'a -> 'b = <fun>
1155         # fun f z -> f 2 (f 1 z);;
1156         - : (int -> 'a -> 'a) -> 'a -> 'a = <fun>
1157         # fun f z -> f 3 (f 2 (f 1 z))
1158         - : (int -> 'a -> 'a) -> 'a -> 'a = <fun>
1159
1160 We can see what the consistent, general principle types are at the end, so we
1161 can stop. These types should remind you of the simply-typed lambda calculus
1162 types for Church numerals (`(o -> o) -> o -> o`) with one extra type
1163 thrown in, the type of the element a the head of the list
1164 (in this case, an int).
1165
1166 So here's our type constructor for our hand-rolled lists:
1167
1168     type 'b list' = (int -> 'b -> 'b) -> 'b -> 'b
1169
1170 Generalizing to lists that contain any kind of element (not just
1171 ints), we have
1172
1173     type ('a, 'b) list' = ('a -> 'b -> 'b) -> 'b -> 'b
1174
1175 So an `('a, 'b) list'` is a list containing elements of type `'a`,
1176 where `'b` is the type of some part of the plumbing.  This is more
1177 general than an ordinary OCaml list, but we'll see how to map them
1178 into OCaml lists soon.  We don't need to fully grasp the role of the `'b`'s
1179 in order to proceed to build a monad:
1180
1181     l'_unit (a : 'a) : ('a, 'b) list = fun a -> fun f z -> f a z
1182
1183 No problem.  Arriving at bind is a little more complicated, but
1184 exactly the same principles apply, you just have to be careful and
1185 systematic about it.
1186
1187     l'_bind (u : ('a,'b) list') (f : 'a -> ('c, 'd) list') : ('c, 'd) list'  = ...
1188
1189 Unpacking the types gives:
1190
1191     l'_bind (u : ('a -> 'b -> 'b) -> 'b -> 'b)
1192             (f : 'a -> ('c -> 'd -> 'd) -> 'd -> 'd)
1193             : ('c -> 'd -> 'd) -> 'd -> 'd = ...
1194
1195 Perhaps a bit intimiating.
1196 But it's a rookie mistake to quail before complicated types. You should
1197 be no more intimiated by complex types than by a linguistic tree with
1198 deeply embedded branches: complex structure created by repeated
1199 application of simple rules.
1200
1201 [This would be a good time to try to build your own term for the types
1202 just given.  Doing so (or attempting to do so) will make the next
1203 paragraph much easier to follow.]
1204
1205 As usual, we need to unpack the `u` box.  Examine the type of `u`.
1206 This time, `u` will only deliver up its contents if we give `u` an
1207 argument that is a function expecting an `'a` and a `'b`. `u` will 
1208 fold that function over its type `'a` members, and that's how we'll get the `'a`s we need. Thus:
1209
1210         ... u (fun (a : 'a) (b : 'b) -> ... f a ... ) ...
1211
1212 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)`:
1213
1214         ... u (fun (a : 'a) (b : 'b) -> ... f a k ... ) ...
1215
1216 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:
1217
1218         ... u (fun (a : 'a) (b : 'b) -> f a k b) ...
1219
1220 Now, we've used a `k` that we pulled out of nowhere, so we need to abstract over it:
1221
1222         fun (k : 'c -> 'b -> 'b) -> u (fun (a : 'a) (b : 'b) -> f a k b)
1223
1224 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 our bind is:
1225
1226     l'_bind (u : ('a -> 'b -> 'b) -> 'b -> 'b)
1227             (f : 'a -> ('c -> 'b -> 'b) -> 'b -> 'b)
1228             : ('c -> 'b -> 'b) -> 'b -> 'b = 
1229       fun k -> u (fun a b -> f a k b)
1230
1231 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.
1232
1233 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:
1234
1235       fun k z -> u (fun a b -> f a k b) z
1236
1237 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?
1238
1239 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:
1240
1241         concat (map f u) =
1242         concat [[]; [2]; [2; 4]; [2; 4; 8]] =
1243         [2; 2; 4; 2; 4; 8]
1244
1245 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
1246
1247       fun k z -> u (fun a b -> f a k b) z
1248         
1249 do? Well, for each element `a` in `u`, it applies `f` to that `a`, getting one of the lists:
1250
1251         []
1252         [2]
1253         [2; 4]
1254         [2; 4; 8]
1255
1256 (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.
1257
1258 So if, for example, we let `k` be `+` and `z` be `0`, then the computation would proceed:
1259
1260         0 ==>
1261         right-fold + and 0 over [2; 4; 8] = 2+4+8+0 ==>
1262         right-fold + and 2+4+8+0 over [2; 4] = 2+4+2+4+8+0 ==>
1263         right-fold + and 2+4+2+4+8+0 over [2] = 2+2+4+2+4+8+0 ==>
1264         right-fold + and 2+2+4+2+4+8+0 over [] = 2+2+4+2+4+8+0
1265
1266 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:
1267
1268       fun k z -> u (fun a b -> f a k b) z
1269
1270 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
1271
1272         fun k z -> List.fold_right k (concat (map f u)) z
1273
1274 would.
1275
1276 For future reference, we might make two eta-reductions to our formula, so that we have instead:
1277
1278       let l'_bind = fun k -> u (fun a -> f a k);;
1279
1280 Let's make some more tests:
1281
1282
1283     l_bind [1;2] (fun i -> [i, i+1]) ~~> [1; 2; 2; 3]
1284
1285     l'_bind (fun f z -> f 1 (f 2 z)) 
1286             (fun i -> fun f z -> f i (f (i+1) z)) ~~> <fun>
1287
1288 Sigh.  OCaml won't show us our own list.  So we have to choose an `f`
1289 and a `z` that will turn our hand-crafted lists into standard OCaml
1290 lists, so that they will print out.
1291
1292         # let cons h t = h :: t;;  (* OCaml is stupid about :: *)
1293         # l'_bind (fun f z -> f 1 (f 2 z)) 
1294                           (fun i -> fun f z -> f i (f (i+1) z)) cons [];;
1295         - : int list = [1; 2; 2; 3]
1296
1297 Ta da!
1298
1299
1300 Montague's PTQ treatment of DPs as generalized quantifiers
1301 ----------------------------------------------------------
1302
1303 We've hinted that Montague's treatment of DPs as generalized
1304 quantifiers embodies the spirit of continuations (see de Groote 2001,
1305 Barker 2002 for lengthy discussion).  Let's see why.  
1306
1307 First, we'll need a type constructor.  As you probably know, 
1308 Montague replaced individual-denoting determiner phrases (with type `e`)
1309 with generalized quantifiers (with [extensional] type `(e -> t) -> t`.
1310 In particular, the denotation of a proper name like *John*, which
1311 might originally denote a object `j` of type `e`, came to denote a
1312 generalized quantifier `fun pred -> pred j` of type `(e -> t) -> t`.
1313 Let's write a general function that will map individuals into their
1314 corresponding generalized quantifier:
1315
1316    gqize (a : e) = fun (p : e -> t) -> p a
1317
1318 This function is what Partee 1987 calls LIFT, and it would be
1319 reasonable to use it here, but we will avoid that name, given that we
1320 use that word to refer to other functions.
1321
1322 This function wraps up an individual in a box.  That is to say,
1323 we are in the presence of a monad.  The type constructor, the unit and
1324 the bind follow naturally.  We've done this enough times that we won't
1325 belabor the construction of the bind function, the derivation is
1326 highly similar to the List monad just given:
1327
1328         type 'a continuation = ('a -> 'b) -> 'b
1329         c_unit (a : 'a) = fun (p : 'a -> 'b) -> p a
1330         c_bind (u : ('a -> 'b) -> 'b) (f : 'a -> ('c -> 'd) -> 'd) : ('c -> 'd) -> 'd =
1331           fun (k : 'a -> 'b) -> u (fun (a : 'a) -> f a k)
1332
1333 Note that `c_unit` is exactly the `gqize` function that Montague used
1334 to lift individuals into the continuation monad.
1335
1336 That last bit in `c_bind` looks familiar---we just saw something like
1337 it in the List monad.  How similar is it to the List monad?  Let's
1338 examine the type constructor and the terms from the list monad derived
1339 above:
1340
1341     type ('a, 'b) list' = ('a -> 'b -> 'b) -> 'b -> 'b
1342     l'_unit a = fun f -> f a                 
1343     l'_bind u f = fun k -> u (fun a -> f a k)
1344
1345 (We performed a sneaky but valid eta reduction in the unit term.)
1346
1347 The unit and the bind for the Montague continuation monad and the
1348 homemade List monad are the same terms!  In other words, the behavior
1349 of the List monad and the behavior of the continuations monad are
1350 parallel in a deep sense.
1351
1352 Have we really discovered that lists are secretly continuations?  Or
1353 have we merely found a way of simulating lists using list
1354 continuations?  Well, strictly speaking, what we have done is shown
1355 that one particular implementation of lists---the right fold
1356 implementation---gives rise to a continuation monad fairly naturally,
1357 and that this monad can reproduce the behavior of the standard list
1358 monad.  But what about other list implementations?  Do they give rise
1359 to monads that can be understood in terms of continuations?
1360
1361 Manipulating trees with monads
1362 ------------------------------
1363
1364 This topic develops an idea based on a detailed suggestion of Ken
1365 Shan's.  We'll build a series of functions that operate on trees,
1366 doing various things, including replacing leaves, counting nodes, and
1367 converting a tree to a list of leaves.  The end result will be an
1368 application for continuations.
1369
1370 From an engineering standpoint, we'll build a tree transformer that
1371 deals in monads.  We can modify the behavior of the system by swapping
1372 one monad for another.  We've already seen how adding a monad can add
1373 a layer of funtionality without disturbing the underlying system, for
1374 instance, in the way that the reader monad allowed us to add a layer
1375 of intensionality to an extensional grammar, but we have not yet seen
1376 the utility of replacing one monad with other.
1377
1378 First, we'll be needing a lot of trees during the remainder of the
1379 course.  Here's a type constructor for binary trees:
1380
1381     type 'a tree = Leaf of 'a | Node of ('a tree * 'a tree)
1382
1383 These are trees in which the internal nodes do not have labels.  [How
1384 would you adjust the type constructor to allow for labels on the
1385 internal nodes?]
1386
1387 We'll be using trees where the nodes are integers, e.g.,
1388
1389
1390 <pre>
1391 let t1 = Node ((Node ((Leaf 2), (Leaf 3))),
1392                (Node ((Leaf 5),(Node ((Leaf 7),
1393                                       (Leaf 11))))))
1394
1395     .
1396  ___|___
1397  |     |
1398  .     .
1399 _|__  _|__
1400 |  |  |  |
1401 2  3  5  .
1402         _|__
1403         |  |
1404         7  11
1405 </pre>
1406
1407 Our first task will be to replace each leaf with its double:
1408
1409 <pre>
1410 let rec treemap (newleaf:'a -> 'b) (t:'a tree):('b tree) =
1411   match t with Leaf x -> Leaf (newleaf x)
1412              | Node (l, r) -> Node ((treemap newleaf l),
1413                                     (treemap newleaf r));;
1414 </pre>
1415 `treemap` takes a function that transforms old leaves into new leaves, 
1416 and maps that function over all the leaves in the tree, leaving the
1417 structure of the tree unchanged.  For instance:
1418
1419 <pre>
1420 let double i = i + i;;
1421 treemap double t1;;
1422 - : int tree =
1423 Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
1424
1425     .
1426  ___|____
1427  |      |
1428  .      .
1429 _|__  __|__
1430 |  |  |   |
1431 4  6  10  .
1432         __|___
1433         |    |
1434         14   22
1435 </pre>
1436
1437 We could have built the doubling operation right into the `treemap`
1438 code.  However, because what to do to each leaf is a parameter, we can
1439 decide to do something else to the leaves without needing to rewrite
1440 `treemap`.  For instance, we can easily square each leaf instead by
1441 supplying the appropriate `int -> int` operation in place of `double`:
1442
1443 <pre>
1444 let square x = x * x;;
1445 treemap square t1;;
1446 - : int tree =ppp
1447 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
1448 </pre>
1449
1450 Note that what `treemap` does is take some global, contextual
1451 information---what to do to each leaf---and supplies that information
1452 to each subpart of the computation.  In other words, `treemap` has the
1453 behavior of a reader monad.  Let's make that explicit.  
1454
1455 In general, we're on a journey of making our treemap function more and
1456 more flexible.  So the next step---combining the tree transducer with
1457 a reader monad---is to have the treemap function return a (monadized)
1458 tree that is ready to accept any `int->int` function and produce the
1459 updated tree.
1460
1461 \tree (. (. (f2) (f3))(. (f5) (.(f7)(f11))))
1462 <pre>
1463 \f    .
1464   ____|____
1465   |       |
1466   .       .
1467 __|__   __|__
1468 |   |   |   |
1469 f2  f3  f5  .
1470           __|___
1471           |    |
1472           f7  f11
1473 </pre>
1474
1475 That is, we want to transform the ordinary tree `t1` (of type `int
1476 tree`) into a reader object of type `(int->int)-> int tree`: something 
1477 that, when you apply it to an `int->int` function returns an `int
1478 tree` in which each leaf `x` has been replaced with `(f x)`.
1479
1480 With previous readers, we always knew which kind of environment to
1481 expect: either an assignment function (the original calculator
1482 simulation), a world (the intensionality monad), an integer (the
1483 Jacobson-inspired link monad), etc.  In this situation, it will be
1484 enough for now to expect that our reader will expect a function of
1485 type `int->int`.
1486
1487 <pre>
1488 type 'a reader = (int->int) -> 'a;;  (* mnemonic: e for environment *)
1489 let reader_unit (x:'a): 'a reader = fun _ -> x;;
1490 let reader_bind (u: 'a reader) (f:'a -> 'c reader):'c reader = fun e -> f (u e) e;;
1491 </pre>
1492
1493 It's easy to figure out how to turn an `int` into an `int reader`:
1494
1495 <pre>
1496 let int2int_reader (x:'a): 'b reader = fun (op:'a -> 'b) -> op x;;
1497 int2int_reader 2 (fun i -> i + i);;
1498 - : int = 4
1499 </pre>
1500
1501 But what do we do when the integers are scattered over the leaves of a
1502 tree?  A binary tree is not the kind of thing that we can apply a
1503 function of type `int->int` to.
1504
1505 <pre>
1506 let rec treemonadizer (f:'a -> 'b reader) (t:'a tree):('b tree) reader =
1507   match t with Leaf x -> reader_bind (f x) (fun x' -> reader_unit (Leaf x'))
1508              | Node (l, r) -> reader_bind (treemonadizer f l) (fun x ->
1509                                 reader_bind (treemonadizer f r) (fun y ->
1510                                   reader_unit (Node (x, y))));;
1511 </pre>
1512
1513 This function says: give me a function `f` that knows how to turn
1514 something of type `'a` into an `'b reader`, and I'll show you how to 
1515 turn an `'a tree` into an `'a tree reader`.  In more fanciful terms, 
1516 the `treemonadizer` function builds plumbing that connects all of the
1517 leaves of a tree into one connected monadic network; it threads the
1518 monad through the leaves.
1519
1520 <pre>
1521 # treemonadizer int2int_reader t1 (fun i -> i + i);;
1522 - : int tree =
1523 Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
1524 </pre>
1525
1526 Here, our environment is the doubling function (`fun i -> i + i`).  If
1527 we apply the very same `int tree reader` (namely, `treemonadizer
1528 int2int_reader t1`) to a different `int->int` function---say, the
1529 squaring function, `fun i -> i * i`---we get an entirely different
1530 result:
1531
1532 <pre>
1533 # treemonadizer int2int_reader t1 (fun i -> i * i);;
1534 - : int tree =
1535 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
1536 </pre>
1537
1538 Now that we have a tree transducer that accepts a monad as a
1539 parameter, we can see what it would take to swap in a different monad.
1540 For instance, we can use a state monad to count the number of nodes in
1541 the tree.
1542
1543 <pre>
1544 type 'a state = int -> 'a * int;;
1545 let state_unit x i = (x, i+.5);;
1546 let state_bind u f i = let (a, i') = u i in f a (i'+.5);;
1547 </pre>
1548
1549 Gratifyingly, we can use the `treemonadizer` function without any
1550 modification whatsoever, except for replacing the (parametric) type
1551 `reader` with `state`:
1552
1553 <pre>
1554 let rec treemonadizer (f:'a -> 'b state) (t:'a tree):('b tree) state =
1555   match t with Leaf x -> state_bind (f x) (fun x' -> state_unit (Leaf x'))
1556              | Node (l, r) -> state_bind (treemonadizer f l) (fun x ->
1557                                 state_bind (treemonadizer f r) (fun y ->
1558                                   state_unit (Node (x, y))));;
1559 </pre>
1560
1561 Then we can count the number of nodes in the tree:
1562
1563 <pre>
1564 # treemonadizer state_unit t1 0;;
1565 - : int tree * int =
1566 (Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11))), 13)
1567
1568     .
1569  ___|___
1570  |     |
1571  .     .
1572 _|__  _|__
1573 |  |  |  |
1574 2  3  5  .
1575         _|__
1576         |  |
1577         7  11
1578 </pre>
1579
1580 Notice that we've counted each internal node twice---it's a good
1581 exercise to adjust the code to count each node once.
1582
1583 One more revealing example before getting down to business: replacing
1584 `state` everywhere in `treemonadizer` with `list` gives us
1585
1586 <pre>
1587 # treemonadizer (fun x -> [ [x; square x] ]) t1;;
1588 - : int list tree list =
1589 [Node
1590   (Node (Leaf [2; 4], Leaf [3; 9]),
1591    Node (Leaf [5; 25], Node (Leaf [7; 49], Leaf [11; 121])))]
1592 </pre>
1593
1594 Unlike the previous cases, instead of turning a tree into a function
1595 from some input to a result, this transformer replaces each `int` with
1596 a list of `int`'s.
1597
1598 Now for the main point.  What if we wanted to convert a tree to a list
1599 of leaves?  
1600
1601 <pre>
1602 type ('a, 'r) continuation = ('a -> 'r) -> 'r;;
1603 let continuation_unit x c = c x;;
1604 let continuation_bind u f c = u (fun a -> f a c);;
1605
1606 let rec treemonadizer (f:'a -> ('b, 'r) continuation) (t:'a tree):(('b tree), 'r) continuation =
1607   match t with Leaf x -> continuation_bind (f x) (fun x' -> continuation_unit (Leaf x'))
1608              | Node (l, r) -> continuation_bind (treemonadizer f l) (fun x ->
1609                                 continuation_bind (treemonadizer f r) (fun y ->
1610                                   continuation_unit (Node (x, y))));;
1611 </pre>
1612
1613 We use the continuation monad described above, and insert the
1614 `continuation` type in the appropriate place in the `treemonadizer` code.
1615 We then compute:
1616
1617 <pre>
1618 # treemonadizer (fun a c -> a :: (c a)) t1 (fun t -> []);;
1619 - : int list = [2; 3; 5; 7; 11]
1620 </pre>
1621
1622 We have found a way of collapsing a tree into a list of its leaves.
1623
1624 The continuation monad is amazingly flexible; we can use it to
1625 simulate some of the computations performed above.  To see how, first
1626 note that an interestingly uninteresting thing happens if we use the
1627 continuation unit as our first argument to `treemonadizer`, and then
1628 apply the result to the identity function:
1629
1630 <pre>
1631 # treemonadizer continuation_unit t1 (fun x -> x);;
1632 - : int tree =
1633 Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11)))
1634 </pre>
1635
1636 That is, nothing happens.  But we can begin to substitute more
1637 interesting functions for the first argument of `treemonadizer`:
1638
1639 <pre>
1640 (* Simulating the tree reader: distributing a operation over the leaves *)
1641 # treemonadizer (fun a c -> c (square a)) t1 (fun x -> x);;
1642 - : int tree =
1643 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
1644
1645 (* Simulating the int list tree list *)
1646 # treemonadizer (fun a c -> c [a; square a]) t1 (fun x -> x);;
1647 - : int list tree =
1648 Node
1649  (Node (Leaf [2; 4], Leaf [3; 9]),
1650   Node (Leaf [5; 25], Node (Leaf [7; 49], Leaf [11; 121])))
1651
1652 (* Counting leaves *)
1653 # treemonadizer (fun a c -> 1 + c a) t1 (fun x -> 0);;
1654 - : int = 5
1655 </pre>
1656
1657 We could simulate the tree state example too, but it would require
1658 generalizing the type of the continuation monad to 
1659
1660     type ('a -> 'b -> 'c) continuation = ('a -> 'b) -> 'c;;
1661
1662 The binary tree monad
1663 ---------------------
1664
1665 Of course, by now you may have realized that we have discovered a new
1666 monad, the binary tree monad:
1667
1668 <pre>
1669 type 'a tree = Leaf of 'a | Node of ('a tree) * ('a tree);;
1670 let tree_unit (x:'a) = Leaf x;;
1671 let rec tree_bind (u:'a tree) (f:'a -> 'b tree):'b tree = 
1672   match u with Leaf x -> f x 
1673              | Node (l, r) -> Node ((tree_bind l f), (tree_bind r f));;
1674 </pre>
1675
1676 For once, let's check the Monad laws.  The left identity law is easy:
1677
1678     Left identity: bind (unit a) f = bind (Leaf a) f = fa
1679
1680 To check the other two laws, we need to make the following
1681 observation: it is easy to prove based on `tree_bind` by a simple
1682 induction on the structure of the first argument that the tree
1683 resulting from `bind u f` is a tree with the same strucure as `u`,
1684 except that each leaf `a` has been replaced with `fa`:
1685
1686 \tree (. (fa1) (. (. (. (fa2)(fa3)) (fa4)) (fa5)))
1687 <pre>
1688                 .                         .       
1689               __|__                     __|__   
1690               |   |                     |   |   
1691               a1  .                    fa1  .   
1692                  _|__                     __|__ 
1693                  |  |                     |   | 
1694                  .  a5                    .  fa5
1695    bind         _|__       f   =        __|__   
1696                 |  |                    |   |   
1697                 .  a4                   .  fa4  
1698               __|__                   __|___   
1699               |   |                   |    |   
1700               a2  a3                 fa2  fa3         
1701 </pre>   
1702
1703 Given this equivalence, the right identity law
1704
1705     Right identity: bind u unit = u
1706
1707 falls out once we realize that
1708
1709     bind (Leaf a) unit = unit a = Leaf a
1710
1711 As for the associative law,
1712
1713     Associativity: bind (bind u f) g = bind u (\a. bind (fa) g)
1714
1715 we'll give an example that will show how an inductive proof would
1716 proceed.  Let `f a = Node (Leaf a, Leaf a)`.  Then
1717
1718 \tree (. (. (. (. (a1)(a2)))))
1719 \tree (. (. (. (. (a1) (a1)) (. (a1) (a1)))  ))
1720 <pre>
1721                                            .
1722                                        ____|____
1723           .               .            |       |
1724 bind    __|__   f  =    __|_    =      .       .
1725         |   |           |   |        __|__   __|__
1726         a1  a2         fa1 fa2       |   |   |   |
1727                                      a1  a1  a1  a1  
1728 </pre>
1729
1730 Now when we bind this tree to `g`, we get
1731
1732 <pre>
1733            .
1734        ____|____
1735        |       |
1736        .       .
1737      __|__   __|__
1738      |   |   |   |
1739     ga1 ga1 ga1 ga1  
1740 </pre>
1741
1742 At this point, it should be easy to convince yourself that
1743 using the recipe on the right hand side of the associative law will
1744 built the exact same final tree.
1745
1746 So binary trees are a monad.
1747
1748 Haskell combines this monad with the Option monad to provide a monad
1749 called a
1750 [SearchTree](http://hackage.haskell.org/packages/archive/tree-monad/0.2.1/doc/html/src/Control-Monad-SearchTree.html#SearchTree)
1751 that is intended to 
1752 represent non-deterministic computations as a tree.
1753
1754 ##[[List Monad as Continuation Monad]]##
1755
1756 ##[[Manipulating Trees with Monads]]##
1757