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 ##List Zippers##
7
8 Say you've got some moderately-complex function for searching through a list, for example:
9
10         let find_nth (test : 'a -> bool) (n : int) (lst : 'a list) : (int * 'a) ->
11                 let rec helper (position : int) n lst =
12                         match lst with
13                         | [] -> failwith "not found"
14                         | x :: xs when test x -> (if n = 1
15                                 then (position, x)
16                                 else helper (position + 1) (n - 1) xs
17                         )
18                         | x :: xs -> helper (position + 1) n xs
19                 in helper 0 n lst;;
20
21 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:
22
23         let find_nth' (test : 'a -> bool) (n : int) (lst : 'a list) (default : 'a) : ('a * 'a * 'a) ->
24                 let rec helper (predecessor : 'a) n lst =
25                         match lst with
26                         | [] -> failwith "not found"
27                         | x :: xs when test x -> (if n = 1
28                                 then (predecessor, x, match xs with [] -> default | y::ys -> y)
29                                 else helper x (n - 1) xs
30                         )
31                         | x :: xs -> helper x n xs
32                 in helper default n lst;;
33
34 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...?
35
36 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.
37
38 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:
39
40         [10; 20; 30; 40; 50; 60; 70; 80; 90]
41
42 we might imagine the list "broken" at position 3 like this (positions are numbered starting from 0):
43
44                     40;
45                 30;     50;
46             20;             60;
47         [10;                    70;
48                                     80;
49                                         90]
50
51 Then if we move one step forward in the list, it would be "broken" at position 4:
52
53                         50;
54                     40;     60;
55                 30;             70;
56             20;                     80;
57         [10;                            90]
58
59 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".
60
61 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:
62
63                     40;
64                 30;     50;
65             20;             60;
66         [10;                    70;
67                                     80;
68                                         90]
69
70 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.)
71
72 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:
73
74                  t
75                   a
76                    b
77                     40;
78                 30;     50;
79             20;             60;
80         [10;                    70;
81                                     80;
82                                         90]
83
84 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:
85
86         ([], [10; 20; 30; 40; 50; 60; 70; 80; 90])
87
88 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:
89
90         [10; 20; 30; *; 50; 60; 70; 80; 90], * filled by 40
91
92 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.
93
94
95 ##Tree Zippers##
96
97 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.
98
99 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:
100
101                 root
102                 / \
103               /     \
104             /  \    label 1
105           /      \
106         label 1  label 2
107
108 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:
109
110                  1
111                 / \
112               2     \
113             /  \     5
114           /      \
115          3        4
116
117 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.
118
119 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.
120
121 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.
122
123 Suppose we have the following tree:
124
125                                  9200
126                             /      |  \
127                          /         |    \
128                       /            |      \
129                    /               |        \
130                 /                  |          \
131                500                920          950
132             /   |    \          /  |  \      /  |  \
133          20     50     80      91  92  93   94  95  96
134         1 2 3  4 5 6  7 8 9
135
136 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.
137
138 Suppose we want to represent that we're *at* the node marked `50`. We might use the following metalanguage notation to specify this:
139
140         {parent = ...; siblings = [subtree 20; *; subtree 80]}, * filled by subtree 50
141
142 This is modeled on the notation suggested above for list zippers. Here `subtree 20` refers to the whole subtree rooted at node `20`:
143
144           20
145          / | \
146         1  2  3
147
148 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`:
149
150         {parent = ...; siblings = [*; subtree 920; subtree 950]}, * filled by subtree 500
151
152 And the parent of that targetted subtree should intuitively be a tree targetted on `node 9200`:
153
154         {parent = None; siblings = [*]}, * filled by tree 9200
155
156 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:
157
158         {
159            parent = {
160               parent = {
161                  parent = None;
162                  siblings = [*]
163               }, * filled by tree 9200;
164               siblings = [*; subtree 920; subtree 950]
165            }, * filled by subtree 500;
166            siblings = [subtree 20; *; subtree 80]
167         }, * filled by subtree 50
168
169 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:
170
171         {
172            parent = {
173               parent = {
174                  parent = None;
175                  siblings = [*]
176               },
177               siblings = [*; subtree 920; subtree 950]
178            },
179            siblings = [subtree 20; *; subtree 80]
180         }, * filled by subtree 50
181
182
183 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.
184
185 For simplicity, I'll continue to use the abbreviated form:
186
187         {parent = ...; siblings = [subtree 20; *; subtree 80]}, * filled by subtree 50
188
189 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.
190
191 Moving left in our targetted tree that's targetted on `node 50` would be a matter of shifting the `*` leftwards:
192
193         {parent = ...; siblings = [*; subtree 50; subtree 80]}, * filled by subtree 20
194
195 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.
196
197 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:
198
199         {
200            parent = {parent = ...; siblings = [*; subtree 50; subtree 80]};
201            siblings = [*; leaf 2; leaf 3]
202         }, * filled by leaf 1
203
204 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:
205
206                node 20'
207             /     |    \
208          /        |      \
209         leaf 1  leaf 2  leaf 3
210
211 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 `*`:
212
213         {
214            parent = ...;
215            siblings = [*; subtree 50; subtree 80]
216         }, * filled by subtree 20'
217
218 Or, spelling that structure out fully:
219
220         {
221            parent = {
222               parent = {
223                  parent = None;
224                  siblings = [*]
225               },
226               siblings = [*; subtree 920; subtree 950]
227            },
228            siblings = [*; subtree 50; subtree 80]
229         }, * filled by subtree 20'
230
231 Moving upwards yet again would get us:
232
233         {
234            parent = {
235               parent = None;
236               siblings = [*]
237            },
238            siblings = [*; subtree 920; subtree 950]
239         }, * filled by subtree 500'
240
241 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:
242
243         {
244            parent = None;
245            siblings = [*]
246         }, * filled by tree 9200'
247
248 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.
249
250 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:
251
252 *       [[!wikipedia Zipper (data structure)]]
253 *       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.
254 *       As always, [Oleg](http://okmij.org/ftp/continuations/Continuations.html#zipper) takes this a few steps deeper.
255
256 ##Same-fringe using a tree zipper##
257
258 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):
259
260             .                .
261            / \              / \
262           .   3            1   .
263          / \                  / \
264         1   2                2   3
265
266 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.
267
268
269 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:
270
271             .                .
272            / \              / \
273           .   3            1   .
274          / \                  / \
275         1   2                2   3
276
277 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.
278
279 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.
280
281 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.
282
283 First, we define a type for leaf-labeled, binary trees:
284
285         type 'a tree = Leaf of 'a | Node of ('a tree * 'a tree)
286
287 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:
288
289         # type blah = Blah of (int * int * (char -> bool));;
290
291 and then having to remember which element in the triple was which:
292
293         # let b1 = Blah (1, (fun c -> c = 'M'), 2);;
294         Error: This expression has type int * (char -> bool) * int
295        but an expression was expected of type int * int * (char -> bool)
296         # (* damnit *)
297         # let b1 = Blah (1, 2, (fun c -> c = 'M'));;
298         val b1 : blah = Blah (1, 2, <fun>)
299
300 records let you attach descriptive labels to the components of the tuple:
301
302         # type blah_record = { height : int; weight : int; char_tester : char -> bool };;
303         # let b2 = { height = 1; weight = 2; char_tester = fun c -> c = 'M' };;
304         val b2 : blah_record = {height = 1; weight = 2; char_tester = <fun>}
305         # let b3 = { height = 1; char_tester = (fun c -> c = 'K'); weight = 3 };; (* also works *)
306         val b3 : blah_record = {height = 1; weight = 3; char_tester = <fun>}
307
308 These were the strategies to extract the components of an unlabeled tuple:
309
310         let h = fst some_pair;; (* accessor functions fst and snd are only predefined for pairs *)
311
312         let (h, w, test) = b1;; (* works for arbitrary tuples *)
313
314         match b1 with
315         | (h, w, test) -> ...;; (* same as preceding *)
316
317 Here is how you can extract the components of a labeled record:
318
319         let h = b2.height;; (* handy! *)
320
321         let {height = h; weight = w; char_tester = test} = b2
322         in (* go on to use h, w, and test ... *)
323
324         match test with
325         | {height = h; weight = w; char_tester = test} ->
326                 (* go on to use h, w, and test ... *)
327
328 Anyway, using record types, we might define the tree zipper interface like so:
329
330         type 'a starred_level = Root | Starring_Left of 'a starred_nonroot | Starring_Right of 'a starred_nonroot
331         and 'a starred_nonroot = { parent : 'a starred_level; sibling: 'a tree };;
332
333         type 'a zipper = { level : 'a starred_level; filler: 'a tree };;
334
335         let rec move_botleft (z : 'a zipper) : 'a zipper =
336             (* returns z if the targetted node in z has no children *)
337             (* else returns move_botleft (zipper which results from moving down and left in z) *)
338
339 <!--
340             let {level; filler} = z
341             in match filler with
342             | Leaf _ -> z
343             | Node(left, right) ->
344                 let zdown = {level = Starring_Left {parent = level; sibling = right}; filler = left}
345                 in move_botleft zdown
346             ;;
347 -->
348
349         let rec move_right_or_up (z : 'a zipper) : 'a zipper option =
350             (* if it's possible to move right in z, returns Some (the result of doing so) *)
351             (* else if it's not possible to move any further up in z, returns None *)
352             (* else returns move_right_or_up (result of moving up in z) *)
353
354 <!--
355             let {level; filler} = z
356             in match level with
357             | Starring_Left {parent; sibling = right} -> Some {level = Starring_Right {parent; sibling = filler}; filler = right}
358             | Root -> None
359             | Starring_Right {parent; sibling = left} ->
360                 let z' = {level = parent; filler = Node(left, filler)}
361                 in move_right_or_up z'
362             ;;
363 -->
364
365 The following function takes an 'a tree and returns an 'a zipper focused on its root:
366
367         let new_zipper (t : 'a tree) : 'a zipper =
368             {level = Root; filler = t}
369             ;;
370
371 Finally, we can use a mutable reference cell to define a function that enumerates a tree's fringe until it's exhausted:
372
373         let make_fringe_enumerator (t: 'a tree) =
374             (* create a zipper targetting the botleft of t *)
375             let zbotleft = move_botleft (new_zipper t)
376             (* create a refcell initially pointing to zbotleft *)
377             in let zcell = ref (Some zbotleft)
378             (* construct the next_leaf function *)
379             in let next_leaf () : 'a option =
380                 match !zcell with
381                 | Some z -> (
382                     (* extract label of currently-targetted leaf *)
383                     let Leaf current = z.filler
384                     (* update zcell to point to next leaf, if there is one *)
385                     in let () = zcell := match move_right_or_up z with
386                         | None -> None
387                         | Some z' -> Some (move_botleft z')
388                     (* return saved label *)
389                     in Some current
390                 | None -> (* we've finished enumerating the fringe *)
391                     None
392                 )
393             (* return the next_leaf function *)
394             in next_leaf
395             ;;
396
397 Here's an example of `make_fringe_enumerator` in action:
398
399         # let tree1 = Leaf 1;;
400         val tree1 : int tree = Leaf 1
401         # let next1 = make_fringe_enumerator tree1;;
402         val next1 : unit -> int option = <fun>
403         # next1 ();;
404         - : int option = Some 1
405         # next1 ();;
406         - : int option = None
407         # next1 ();;
408         - : int option = None
409         # let tree2 = Node (Node (Leaf 1, Leaf 2), Leaf 3);;
410         val tree2 : int tree = Node (Node (Leaf 1, Leaf 2), Leaf 3)
411         # let next2 = make_fringe_enumerator tree2;;
412         val next2 : unit -> int option = <fun>
413         # next2 ();;
414         - : int option = Some 1
415         # next2 ();;
416         - : int option = Some 2
417         # next2 ();;
418         - : int option = Some 3
419         # next2 ();;
420         - : int option = None
421         # next2 ();;
422         - : int option = None
423
424 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`.
425
426 Using these fringe enumerators, we can write our `same_fringe` function like this:
427
428         let same_fringe (t1 : 'a tree) (t2 : 'a tree) : bool =
429                 let next1 = make_fringe_enumerator t1
430                 in let next2 = make_fringe_enumerator t2
431                 in let rec loop () : bool =
432                         match next1 (), next2 () with
433                         | Some a, Some b when a = b -> loop ()
434                         | None, None -> true
435                         | _ -> false
436                 in loop ()
437                 ;;
438
439 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.
440
441 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*.
442
443 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:
444
445         main program            next1 thread            next2 thread
446         ------------            ------------            ------------
447         start next1
448         (paused)                        starting
449         (paused)                        calculate first leaf
450         (paused)                        <--- return it
451         start next2                     (paused)                        starting
452         (paused)                        (paused)                        calculate first leaf
453         (paused)                        (paused)                        <-- return it
454         compare leaves          (paused)                        (paused)
455         call loop again         (paused)                        (paused)
456         call next1 again        (paused)                        (paused)
457         (paused)                        calculate next leaf     (paused)
458         (paused)                        <-- return it           (paused)
459         ... and so on ...
460
461 If you want to read more about these kinds of threads, here are some links:
462
463 <!-- *  [[!wikipedia Computer_multitasking]]
464 *       [[!wikipedia Thread_(computer_science)]] -->
465
466 *       [[!wikipedia Coroutine]]
467 *       [[!wikipedia Iterator]]
468 *       [[!wikipedia Generator_(computer_science)]]
469 *       [[!wikipedia Fiber_(computer_science)]]
470 <!-- *  [[!wikipedia Green_threads]]
471 *       [[!wikipedia Protothreads]] -->
472
473 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.
474
475 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.
476
477
478 ##Introducing Continuations##
479
480 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."
481
482 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.
483
484 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.
485
486 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.
487
488 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.
489
490 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:
491
492         \handler. handler x y
493
494 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.
495
496 Consider a complex computation, such as:
497
498         1 + 2 * (1 - g (3 + 4))
499
500 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:
501
502         \result. 1 + 2 * (1 - result)
503
504 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.
505
506 Go back and read the material on "Aborting a Search Through a List" in [[Week4]] for an example of doing this.
507
508 In very general terms, the strategy is to work with functions like this:
509
510         let g' k (i : int) =
511                 ... do stuff ...
512                 ... if you want to abort early, supply an argument to k ...
513                 ... do more stuff ...
514                 ... normal result
515         in let gcon = fun result -> 1 + 2 * (1 - result)
516         in gcon (g' gcon (3 + 4))
517
518 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.
519
520 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:
521
522         let g' k (i : int) =
523                 ... do stuff ...
524                 ... if you want to abort early, supply an argument to k ...
525                 ... do more stuff ...
526                 ... normal result
527         in let gcon = fun result ->
528                 let final_value = 1 + 2 * (1 - result)
529                 in end_program_with final_value
530         in gcon (g' gcon (3 + 4))
531
532 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.)
533
534 So now, guess what would be the result of doing the following:
535
536         let g' k (i : int) =
537                 1 + k i
538         in let gcon = fun result ->
539                 let final_value = (1, result)
540                 in end_program_with final_value
541         in gcon (g' gcon (3 + 4))
542
543 <!-- (1, 7) ... explain why not (1, 8) -->
544
545
546 Refunctionalizing zippers: from lists to continuations
547 ------------------------------------------------------
548
549 If zippers are continuations reified (defuntionalized), then one route
550 to continuations is to re-functionalize a zipper.  Then the
551 concreteness and understandability of the zipper provides a way of
552 understanding and equivalent treatment using continuations.
553
554 Let's work with lists of chars for a change.  To maximize readability, we'll
555 indulge in an abbreviatory convention that "abSd" abbreviates the
556 list `['a'; 'b'; 'S'; 'd']`.
557
558 We will set out to compute a deceptively simple-seeming **task: given a
559 string, replace each occurrence of 'S' in that string with a copy of
560 the string up to that point.**
561
562 We'll define a function `t` (for "task") that maps strings to their
563 updated version.
564
565 Expected behavior:
566
567 <pre>
568 t "abSd" ~~> "ababd"
569 </pre>   
570
571
572 In linguistic terms, this is a kind of anaphora
573 resolution, where `'S'` is functioning like an anaphoric element, and
574 the preceding string portion is the antecedent.
575
576 This deceptively simple task gives rise to some mind-bending complexity.
577 Note that it matters which 'S' you target first (the position of the *
578 indicates the targeted 'S'):
579
580 <pre>
581     t "aSbS" 
582         *
583 ~~> t "aabS" 
584           *
585 ~~> "aabaab"
586 </pre>
587
588 versus
589
590 <pre>
591     t "aSbS"
592           *
593 ~~> t "aSbaSb" 
594         *
595 ~~> t "aabaSb"
596            *
597 ~~> "aabaaabab"
598 </pre>   
599
600 versus
601
602 <pre>
603     t "aSbS"
604           *
605 ~~> t "aSbaSb"
606            *
607 ~~> t "aSbaaSbab"
608             *
609 ~~> t "aSbaaaSbaabab"
610              *
611 ~~> ...
612 </pre>
613
614 Aparently, this task, as simple as it is, is a form of computation,
615 and the order in which the `'S'`s get evaluated can lead to divergent
616 behavior.
617
618 For now, we'll agree to always evaluate the leftmost `'S'`.
619
620 This is a task well-suited to using a zipper.  We'll define a function
621 `tz`, which accomplished the task by mapping a char list zipper to a
622 char list.  We'll call the two parts of the zipper `unzipped` and
623 `zipped`; we start with a fully zipped list, and move elements to the
624 zipped part by pulling the zipped down until the zipped part is empty.
625
626 <pre>
627 type 'a list_zipper = ('a list) * ('a list);;
628
629 let rec tz (z:char list_zipper) = 
630     match z with (unzipped, []) -> List.rev(unzipped) (* Done! *)
631                | (unzipped, 'S'::zipped) -> tz ((List.append unzipped unzipped), zipped) 
632                | (unzipped, target::zipped) -> tz (target::unzipped, zipped);; (* Pull zipper *)
633
634 # tz ([], ['a'; 'b'; 'S'; 'd']);;
635 - : char list = ['a'; 'b'; 'a'; 'b'; 'd']
636
637 # tz ([], ['a'; 'S'; 'b'; 'S']);;
638 - : char list = ['a'; 'a'; 'b'; 'a'; 'a'; 'b']
639 </pre>
640
641 Note that this implementation enforces the evaluate-leftmost rule.
642 Task completed.
643
644 One way to see exactly what is going on is to watch the zipper in
645 action by tracing the execution of `t1`.  By using the `#trace`
646 directive in the Ocaml interpreter, the system will print out the
647 arguments to `t1` each time it is (recurcively) called.  Note that the
648 lines with left-facing arrows (`<--`) show (recursive) calls to `tz`,
649 giving the value of its argument (a zipper), and the lines with
650 right-facing arrows (`-->`) show the output of each recursive call, a
651 list.  
652
653 <pre>
654 # #trace tz;;
655 t1 is now traced.
656 # tz ([], ['a'; 'b'; 'S'; 'd']);;
657 tz <-- ([], ['a'; 'b'; 'S'; 'd'])
658 tz <-- (['a'], ['b'; 'S'; 'd'])         (* Pull zipper *)
659 tz <-- (['b'; 'a'], ['S'; 'd'])         (* Pull zipper *)
660 tz <-- (['b'; 'a'; 'b'; 'a'], ['d'])    (* Special step *)
661 tz <-- (['d'; 'b'; 'a'; 'b'; 'a'], [])  (* Pull zipper *)
662 tz --> ['a'; 'b'; 'a'; 'b'; 'd']        (* Output reversed *)
663 tz --> ['a'; 'b'; 'a'; 'b'; 'd']
664 tz --> ['a'; 'b'; 'a'; 'b'; 'd']
665 tz --> ['a'; 'b'; 'a'; 'b'; 'd']
666 tz --> ['a'; 'b'; 'a'; 'b'; 'd']
667 - : char list = ['a'; 'b'; 'a'; 'b'; 'd'] 
668 </pre>
669
670 The nice thing about computations involving lists is that it's so easy
671 to visualize them as a data structure.  Eventually, we want to get to
672 a place where we can talk about more abstract computations.  In order
673 to get there, we'll first do the exact same thing we just did with
674 concrete zipper using procedures.  
675
676 Think of a list as a procedural recipe: `['a'; 'b'; 'S'; 'd']` 
677 is the result of the computation `a::(b::(S::(d::[])))` (or, in our old
678 style, `makelist a (makelist b (makelist S (makelist c empty)))`).
679 The recipe for constructing the list goes like this:
680
681 <pre>
682 (0)  Start with the empty list []
683 (1)  make a new list whose first element is 'd' and whose tail is the list constructed in step (0)
684 (2)  make a new list whose first element is 'S' and whose tail is the list constructed in step (1)
685 -----------------------------------------
686 (3)  make a new list whose first element is 'b' and whose tail is the list constructed in step (2)
687 (4)  make a new list whose first element is 'a' and whose tail is the list constructed in step (3)
688 <pre>
689
690 What is the type of each of these steps?  Well, it will be a function
691 from the result of the previous step (a list) to a new list: it will
692 be a function of type `char list -> char list`.  We'll call each step
693 a **continuation** of the recipe.  So in this context, a continuation
694 is a function of type `char list -> char list`.  For instance, the
695 continuation corresponding to the portion of the recipe below the
696 horizontal line is the function `fun (tail:char list) -> a::(b::tail)`.
697
698 This means that we can now represent the unzipped part of our
699 zipper--the part we've already unzipped--as a continuation: a function
700 describing how to finish building the list.  We'll write a new
701 function, `tc` (for task with continuations), that will take an input
702 list (not a zipper!) and a continuation and return a processed list.
703 The structure and the behavior will follow that of `tz` above, with
704 some small but interesting differences:
705
706 <pre>
707 let rec tc (l: char list) (c: (char list) -> (char list)) =
708   match l with [] -> List.rev (c [])
709              | 'S'::zipped -> tc zipped (fun x -> c (c x))
710              | target::zipped -> tc zipped (fun x -> target::(c x));;
711
712 # tc ['a'; 'b'; 'S'; 'd'] (fun x -> x);;
713 - : char list = ['a'; 'b'; 'a'; 'b']
714
715 # tc ['a'; 'S'; 'b'; 'S'] (fun x -> x);;
716 - : char list = ['a'; 'a'; 'b'; 'a'; 'a'; 'b']
717 </pre>
718
719 To emphasize the parallel, I've re-used the names `zipped` and
720 `target`.  The trace of the procedure will show that these variables
721 take on the same values in the same series of steps as they did during
722 the execution of `tz` above.  There will once again be one initial and
723 four recursive calls to `tc`, and `zipped` will take on the values
724 `"bSd"`, `"Sd"`, `"d"`, and `""` (and, once again, on the final call,
725 the first `match` clause will fire, so the the variable `zipper` will
726 not be instantiated).
727
728 I have not called the functional argument `unzipped`, although that is
729 what the parallel would suggest.  The reason is that `unzipped` is a
730 list, but `c` is a function.  That's the most crucial difference, the
731 point of the excercise, and it should be emphasized.  For instance,
732 you can see this difference in the fact that in `tz`, we have to glue
733 together the two instances of `unzipped` with an explicit `List.append`.
734 In the `tc` version of the task, we simply compose `c` with itself: 
735 `c o c = fun x -> c (c x)`.
736
737 Why use the identity function as the initial continuation?  Well, if
738 you have already constructed the list "abSd", what's the next step in
739 the recipe to produce the desired result (which is the same list,
740 "abSd")?  Clearly, the identity continuation.
741
742 A good way to test your understanding is to figure out what the
743 continuation function `c` must be at the point in the computation when
744 `tc` is called with 
745
746 There are a number of interesting directions we can go with this task.
747 The task was chosen because the computation can be viewed as a
748 simplified picture of a computation using continuations, where `'S'`
749 plays the role of a control operator with some similarities to what is
750 often called `shift`.  &sset; &integral; In the analogy, the list
751 portrays a string of functional applications, where `[f1; f2; f3; x]`
752 represents `f1(f2(f3 x))`.  The limitation of the analogy is that it
753 is only possible to represent computations in which the applications
754 are always right-branching, i.e., the computation `((f1 f2) f3) x`
755 cannot be directly represented.
756
757 One possibile development is that we could add a special symbol `'#'`,
758 and then the task would be to copy from the target `'S'` only back to
759 the closest `'#'`.  This would allow the task to simulate delimited
760 continuations (for right-branching computations).
761
762 The task is well-suited to the list zipper because the list monad has
763 an intimate connection with continuations.  The following section
764 makes this connection.  We'll return to the list task after talking
765 about generalized quantifiers below.
766
767
768 Rethinking the list monad
769 -------------------------
770
771 To construct a monad, the key element is to settle on a type
772 constructor, and the monad naturally follows from that.  We'll remind
773 you of some examples of how monads follow from the type constructor in
774 a moment.  This will involve some review of familair material, but
775 it's worth doing for two reasons: it will set up a pattern for the new
776 discussion further below, and it will tie together some previously
777 unconnected elements of the course (more specifically, version 3 lists
778 and monads).
779
780 For instance, take the **Reader Monad**.  Once we decide that the type
781 constructor is
782
783     type 'a reader = env -> 'a
784
785 then the choice of unit and bind is natural:
786
787     let r_unit (a : 'a) : 'a reader = fun (e : env) -> a
788
789 Since the type of an `'a reader` is `env -> 'a` (by definition),
790 the type of the `r_unit` function is `'a -> env -> 'a`, which is a
791 specific case of the type of the *K* combinator.  So it makes sense
792 that *K* is the unit for the reader monad.
793
794 Since the type of the `bind` operator is required to be
795
796     r_bind : ('a reader) -> ('a -> 'b reader) -> ('b reader)
797
798 We can reason our way to the correct `bind` function as follows. We
799 start by declaring the types determined by the definition of a bind operation:
800
801     let r_bind (u : 'a reader) (f : 'a -> 'b reader) : ('b reader) = ...
802
803 Now we have to open up the `u` box and get out the `'a` object in order to
804 feed it to `f`.  Since `u` is a function from environments to
805 objects of type `'a`, the way we open a box in this monad is
806 by applying it to an environment:
807
808         ... f (u e) ...
809
810 This subexpression types to `'b reader`, which is good.  The only
811 problem is that we invented an environment `e` that we didn't already have ,
812 so we have to abstract over that variable to balance the books:
813
814         fun e -> f (u e) ...
815
816 This types to `env -> 'b reader`, but we want to end up with `env ->
817 '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:
818
819     r_bind (u : 'a reader) (f : 'a -> 'b reader) : ('b reader) =
820                 f (u e) e         
821
822 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.
823
824 [The bind we cite here is a condensed version of the careful `let a = u e in ...`
825 constructions we provided in earlier lectures.  We use the condensed
826 version here in order to emphasize similarities of structure across
827 monads.]
828
829 The **State Monad** is similar.  Once we've decided to use the following type constructor:
830
831     type 'a state = store -> ('a, store)
832
833 Then our unit is naturally:
834
835     let s_unit (a : 'a) : ('a state) = fun (s : store) -> (a, s)
836
837 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:
838
839     let s_bind (u : 'a state) (f : 'a -> 'b state) : 'b state = 
840                 ... f (...) ...
841
842 But unlocking the `u` box is a little more complicated.  As before, we
843 need to posit a state `s` that we can apply `u` to.  Once we do so,
844 however, we won't have an `'a`, we'll have a pair whose first element
845 is an `'a`.  So we have to unpack the pair:
846
847         ... let (a, s') = u s in ... (f a) ...
848
849 Abstracting over the `s` and adjusting the types gives the result:
850
851         let s_bind (u : 'a state) (f : 'a -> 'b state) : 'b state = 
852                 fun (s : store) -> let (a, s') = u s in f a s'
853
854 The **Option/Maybe Monad** doesn't follow the same pattern so closely, so we
855 won't pause to explore it here, though conceptually its unit and bind
856 follow just as naturally from its type constructor.
857
858 Our other familiar monad is the **List Monad**, which we were told
859 looks like this:
860
861     type 'a list = ['a];;
862     l_unit (a : 'a) = [a];;
863     l_bind u f = List.concat (List.map f u);;
864
865 Thinking through the list monad will take a little time, but doing so
866 will provide a connection with continuations.
867
868 Recall that `List.map` takes a function and a list and returns the
869 result to applying the function to the elements of the list:
870
871     List.map (fun i -> [i;i+1]) [1;2] ~~> [[1; 2]; [2; 3]]
872
873 and List.concat takes a list of lists and erases the embdded list
874 boundaries:
875
876     List.concat [[1; 2]; [2; 3]] ~~> [1; 2; 2; 3]
877
878 And sure enough, 
879
880     l_bind [1;2] (fun i -> [i, i+1]) ~~> [1; 2; 2; 3]
881
882 Now, why this unit, and why this bind?  Well, ideally a unit should
883 not throw away information, so we can rule out `fun x -> []` as an
884 ideal unit.  And units should not add more information than required,
885 so there's no obvious reason to prefer `fun x -> [x,x]`.  In other
886 words, `fun x -> [x]` is a reasonable choice for a unit.
887
888 As for bind, an `'a list` monadic object contains a lot of objects of
889 type `'a`, and we want to make some use of each of them (rather than
890 arbitrarily throwing some of them away).  The only
891 thing we know for sure we can do with an object of type `'a` is apply
892 the function of type `'a -> 'a list` to them.  Once we've done so, we
893 have a collection of lists, one for each of the `'a`'s.  One
894 possibility is that we could gather them all up in a list, so that
895 `bind' [1;2] (fun i -> [i;i]) ~~> [[1;1];[2;2]]`.  But that restricts
896 the object returned by the second argument of `bind` to always be of
897 type `'b list list`.  We can elimiate that restriction by flattening
898 the list of lists into a single list: this is
899 just List.concat applied to the output of List.map.  So there is some logic to the
900 choice of unit and bind for the list monad.  
901
902 Yet we can still desire to go deeper, and see if the appropriate bind
903 behavior emerges from the types, as it did for the previously
904 considered monads.  But we can't do that if we leave the list type 
905 as a primitive Ocaml type.  However, we know several ways of implementing
906 lists using just functions.  In what follows, we're going to use type
907 3 lists (the right fold implementation), though it's important to
908 wonder how things would change if we used some other strategy for
909 implementating lists.  These were the lists that made lists look like
910 Church numerals with extra bits embdded in them:
911
912     empty list:                fun f z -> z
913     list with one element:     fun f z -> f 1 z
914     list with two elements:    fun f z -> f 2 (f 1 z)
915     list with three elements:  fun f z -> f 3 (f 2 (f 1 z))
916
917 and so on.  To save time, we'll let the OCaml interpreter infer the
918 principle types of these functions (rather than inferring what the
919 types should be ourselves):
920
921         # fun f z -> z;;
922         - : 'a -> 'b -> 'b = <fun>
923         # fun f z -> f 1 z;;
924         - : (int -> 'a -> 'b) -> 'a -> 'b = <fun>
925         # fun f z -> f 2 (f 1 z);;
926         - : (int -> 'a -> 'a) -> 'a -> 'a = <fun>
927         # fun f z -> f 3 (f 2 (f 1 z))
928         - : (int -> 'a -> 'a) -> 'a -> 'a = <fun>
929
930 We can see what the consistent, general principle types are at the end, so we
931 can stop. These types should remind you of the simply-typed lambda calculus
932 types for Church numerals (`(o -> o) -> o -> o`) with one extra type
933 thrown in, the type of the element a the head of the list
934 (in this case, an int).
935
936 So here's our type constructor for our hand-rolled lists:
937
938     type 'b list' = (int -> 'b -> 'b) -> 'b -> 'b
939
940 Generalizing to lists that contain any kind of element (not just
941 ints), we have
942
943     type ('a, 'b) list' = ('a -> 'b -> 'b) -> 'b -> 'b
944
945 So an `('a, 'b) list'` is a list containing elements of type `'a`,
946 where `'b` is the type of some part of the plumbing.  This is more
947 general than an ordinary OCaml list, but we'll see how to map them
948 into OCaml lists soon.  We don't need to fully grasp the role of the `'b`'s
949 in order to proceed to build a monad:
950
951     l'_unit (a : 'a) : ('a, 'b) list = fun a -> fun f z -> f a z
952
953 No problem.  Arriving at bind is a little more complicated, but
954 exactly the same principles apply, you just have to be careful and
955 systematic about it.
956
957     l'_bind (u : ('a,'b) list') (f : 'a -> ('c, 'd) list') : ('c, 'd) list'  = ...
958
959 Unpacking the types gives:
960
961     l'_bind (u : ('a -> 'b -> 'b) -> 'b -> 'b)
962             (f : 'a -> ('c -> 'd -> 'd) -> 'd -> 'd)
963             : ('c -> 'd -> 'd) -> 'd -> 'd = ...
964
965 Perhaps a bit intimiating.
966 But it's a rookie mistake to quail before complicated types. You should
967 be no more intimiated by complex types than by a linguistic tree with
968 deeply embedded branches: complex structure created by repeated
969 application of simple rules.
970
971 [This would be a good time to try to build your own term for the types
972 just given.  Doing so (or attempting to do so) will make the next
973 paragraph much easier to follow.]
974
975 As usual, we need to unpack the `u` box.  Examine the type of `u`.
976 This time, `u` will only deliver up its contents if we give `u` an
977 argument that is a function expecting an `'a` and a `'b`. `u` will 
978 fold that function over its type `'a` members, and that's how we'll get the `'a`s we need. Thus:
979
980         ... u (fun (a : 'a) (b : 'b) -> ... f a ... ) ...
981
982 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)`:
983
984         ... u (fun (a : 'a) (b : 'b) -> ... f a k ... ) ...
985
986 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:
987
988         ... u (fun (a : 'a) (b : 'b) -> f a k b) ...
989
990 Now, we've used a `k` that we pulled out of nowhere, so we need to abstract over it:
991
992         fun (k : 'c -> 'b -> 'b) -> u (fun (a : 'a) (b : 'b) -> f a k b)
993
994 This whole expression has type `('c -> 'b -> 'b) -> 'b -> 'b`, which is exactly the type of a `('c, 'b) list'`. So we can hypothesize that we our bind is:
995
996     l'_bind (u : ('a -> 'b -> 'b) -> 'b -> 'b)
997             (f : 'a -> ('c -> 'b -> 'b) -> 'b -> 'b)
998             : ('c -> 'b -> 'b) -> 'b -> 'b = 
999       fun k -> u (fun a b -> f a k b)
1000
1001 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.
1002
1003 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:
1004
1005       fun k z -> u (fun a b -> f a k b) z
1006
1007 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?
1008
1009 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:
1010
1011         concat (map f u) =
1012         concat [[]; [2]; [2; 4]; [2; 4; 8]] =
1013         [2; 2; 4; 2; 4; 8]
1014
1015 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
1016
1017       fun k z -> u (fun a b -> f a k b) z
1018         
1019 do? Well, for each element `a` in `u`, it applies `f` to that `a`, getting one of the lists:
1020
1021         []
1022         [2]
1023         [2; 4]
1024         [2; 4; 8]
1025
1026 (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.
1027
1028 So if, for example, we let `k` be `+` and `z` be `0`, then the computation would proceed:
1029
1030         0 ==>
1031         right-fold + and 0 over [2; 4; 8] = 2+4+8+0 ==>
1032         right-fold + and 2+4+8+0 over [2; 4] = 2+4+2+4+8+0 ==>
1033         right-fold + and 2+4+2+4+8+0 over [2] = 2+2+4+2+4+8+0 ==>
1034         right-fold + and 2+2+4+2+4+8+0 over [] = 2+2+4+2+4+8+0
1035
1036 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:
1037
1038       fun k z -> u (fun a b -> f a k b) z
1039
1040 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
1041
1042         fun k z -> List.fold_right k (concat (map f u)) z
1043
1044 would.
1045
1046 For future reference, we might make two eta-reductions to our formula, so that we have instead:
1047
1048       let l'_bind = fun k -> u (fun a -> f a k);;
1049
1050 Let's make some more tests:
1051
1052
1053     l_bind [1;2] (fun i -> [i, i+1]) ~~> [1; 2; 2; 3]
1054
1055     l'_bind (fun f z -> f 1 (f 2 z)) 
1056             (fun i -> fun f z -> f i (f (i+1) z)) ~~> <fun>
1057
1058 Sigh.  OCaml won't show us our own list.  So we have to choose an `f`
1059 and a `z` that will turn our hand-crafted lists into standard OCaml
1060 lists, so that they will print out.
1061
1062         # let cons h t = h :: t;;  (* OCaml is stupid about :: *)
1063         # l'_bind (fun f z -> f 1 (f 2 z)) 
1064                           (fun i -> fun f z -> f i (f (i+1) z)) cons [];;
1065         - : int list = [1; 2; 2; 3]
1066
1067 Ta da!
1068
1069
1070 Montague's PTQ treatment of DPs as generalized quantifiers
1071 ----------------------------------------------------------
1072
1073 We've hinted that Montague's treatment of DPs as generalized
1074 quantifiers embodies the spirit of continuations (see de Groote 2001,
1075 Barker 2002 for lengthy discussion).  Let's see why.  
1076
1077 First, we'll need a type constructor.  As you probably know, 
1078 Montague replaced individual-denoting determiner phrases (with type `e`)
1079 with generalized quantifiers (with [extensional] type `(e -> t) -> t`.
1080 In particular, the denotation of a proper name like *John*, which
1081 might originally denote a object `j` of type `e`, came to denote a
1082 generalized quantifier `fun pred -> pred j` of type `(e -> t) -> t`.
1083 Let's write a general function that will map individuals into their
1084 corresponding generalized quantifier:
1085
1086    gqize (a : e) = fun (p : e -> t) -> p a
1087
1088 This function is what Partee 1987 calls LIFT, and it would be
1089 reasonable to use it here, but we will avoid that name, given that we
1090 use that word to refer to other functions.
1091
1092 This function wraps up an individual in a box.  That is to say,
1093 we are in the presence of a monad.  The type constructor, the unit and
1094 the bind follow naturally.  We've done this enough times that we won't
1095 belabor the construction of the bind function, the derivation is
1096 highly similar to the List monad just given:
1097
1098         type 'a continuation = ('a -> 'b) -> 'b
1099         c_unit (a : 'a) = fun (p : 'a -> 'b) -> p a
1100         c_bind (u : ('a -> 'b) -> 'b) (f : 'a -> ('c -> 'd) -> 'd) : ('c -> 'd) -> 'd =
1101           fun (k : 'a -> 'b) -> u (fun (a : 'a) -> f a k)
1102
1103 Note that `c_bind` is exactly the `gqize` function that Montague used
1104 to lift individuals into the continuation monad.
1105
1106 That last bit in `c_bind` looks familiar---we just saw something like
1107 it in the List monad.  How similar is it to the List monad?  Let's
1108 examine the type constructor and the terms from the list monad derived
1109 above:
1110
1111     type ('a, 'b) list' = ('a -> 'b -> 'b) -> 'b -> 'b
1112     l'_unit a = fun f -> f a                 
1113     l'_bind u f = fun k -> u (fun a -> f a k)
1114
1115 (We performed a sneaky but valid eta reduction in the unit term.)
1116
1117 The unit and the bind for the Montague continuation monad and the
1118 homemade List monad are the same terms!  In other words, the behavior
1119 of the List monad and the behavior of the continuations monad are
1120 parallel in a deep sense.
1121
1122 Have we really discovered that lists are secretly continuations?  Or
1123 have we merely found a way of simulating lists using list
1124 continuations?  Well, strictly speaking, what we have done is shown
1125 that one particular implementation of lists---the right fold
1126 implementation---gives rise to a continuation monad fairly naturally,
1127 and that this monad can reproduce the behavior of the standard list
1128 monad.  But what about other list implementations?  Do they give rise
1129 to monads that can be understood in terms of continuations?
1130
1131 Manipulating trees with monads
1132 ------------------------------
1133
1134 This thread develops an idea based on a detailed suggestion of Ken
1135 Shan's.  We'll build a series of functions that operate on trees,
1136 doing various things, including replacing leaves, counting nodes, and
1137 converting a tree to a list of leaves.  The end result will be an
1138 application for continuations.
1139
1140 From an engineering standpoint, we'll build a tree transformer that
1141 deals in monads.  We can modify the behavior of the system by swapping
1142 one monad for another.  (We've already seen how adding a monad can add
1143 a layer of funtionality without disturbing the underlying system, for
1144 instance, in the way that the reader monad allowed us to add a layer
1145 of intensionality to an extensional grammar, but we have not yet seen
1146 the utility of replacing one monad with other.)
1147
1148 First, we'll be needing a lot of trees during the remainder of the
1149 course.  Here's a type constructor for binary trees:
1150
1151     type 'a tree = Leaf of 'a | Node of ('a tree * 'a tree)
1152
1153 These are trees in which the internal nodes do not have labels.  [How
1154 would you adjust the type constructor to allow for labels on the
1155 internal nodes?]
1156
1157 We'll be using trees where the nodes are integers, e.g.,
1158
1159
1160 <pre>
1161 let t1 = Node ((Node ((Leaf 2), (Leaf 3))),
1162                (Node ((Leaf 5),(Node ((Leaf 7),
1163                                       (Leaf 11))))))
1164
1165     .
1166  ___|___
1167  |     |
1168  .     .
1169 _|__  _|__
1170 |  |  |  |
1171 2  3  5  .
1172         _|__
1173         |  |
1174         7  11
1175 </pre>
1176
1177 Our first task will be to replace each leaf with its double:
1178
1179 <pre>
1180 let rec treemap (newleaf:'a -> 'b) (t:'a tree):('b tree) =
1181   match t with Leaf x -> Leaf (newleaf x)
1182              | Node (l, r) -> Node ((treemap newleaf l),
1183                                     (treemap newleaf r));;
1184 </pre>
1185 `treemap` takes a function that transforms old leaves into new leaves, 
1186 and maps that function over all the leaves in the tree, leaving the
1187 structure of the tree unchanged.  For instance:
1188
1189 <pre>
1190 let double i = i + i;;
1191 treemap double t1;;
1192 - : int tree =
1193 Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
1194
1195     .
1196  ___|____
1197  |      |
1198  .      .
1199 _|__  __|__
1200 |  |  |   |
1201 4  6  10  .
1202         __|___
1203         |    |
1204         14   22
1205 </pre>
1206
1207 We could have built the doubling operation right into the `treemap`
1208 code.  However, because what to do to each leaf is a parameter, we can
1209 decide to do something else to the leaves without needing to rewrite
1210 `treemap`.  For instance, we can easily square each leaf instead by
1211 supplying the appropriate `int -> int` operation in place of `double`:
1212
1213 <pre>
1214 let square x = x * x;;
1215 treemap square t1;;
1216 - : int tree =ppp
1217 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
1218 </pre>
1219
1220 Note that what `treemap` does is take some global, contextual
1221 information---what to do to each leaf---and supplies that information
1222 to each subpart of the computation.  In other words, `treemap` has the
1223 behavior of a reader monad.  Let's make that explicit.  
1224
1225 In general, we're on a journey of making our treemap function more and
1226 more flexible.  So the next step---combining the tree transducer with
1227 a reader monad---is to have the treemap function return a (monadized)
1228 tree that is ready to accept any `int->int` function and produce the
1229 updated tree.
1230
1231 \tree (. (. (f2) (f3))(. (f5) (.(f7)(f11))))
1232 <pre>
1233 \f    .
1234   ____|____
1235   |       |
1236   .       .
1237 __|__   __|__
1238 |   |   |   |
1239 f2  f3  f5  .
1240           __|___
1241           |    |
1242           f7  f11
1243 </pre>
1244
1245 That is, we want to transform the ordinary tree `t1` (of type `int
1246 tree`) into a reader object of type `(int->int)-> int tree`: something 
1247 that, when you apply it to an `int->int` function returns an `int
1248 tree` in which each leaf `x` has been replaced with `(f x)`.
1249
1250 With previous readers, we always knew which kind of environment to
1251 expect: either an assignment function (the original calculator
1252 simulation), a world (the intensionality monad), an integer (the
1253 Jacobson-inspired link monad), etc.  In this situation, it will be
1254 enough for now to expect that our reader will expect a function of
1255 type `int->int`.
1256
1257 <pre>
1258 type 'a reader = (int->int) -> 'a;;  (* mnemonic: e for environment *)
1259 let reader_unit (x:'a): 'a reader = fun _ -> x;;
1260 let reader_bind (u: 'a reader) (f:'a -> 'c reader):'c reader = fun e -> f (u e) e;;
1261 </pre>
1262
1263 It's easy to figure out how to turn an `int` into an `int reader`:
1264
1265 <pre>
1266 let int2int_reader (x:'a): 'b reader = fun (op:'a -> 'b) -> op x;;
1267 int2int_reader 2 (fun i -> i + i);;
1268 - : int = 4
1269 </pre>
1270
1271 But what do we do when the integers are scattered over the leaves of a
1272 tree?  A binary tree is not the kind of thing that we can apply a
1273 function of type `int->int` to.
1274
1275 <pre>
1276 let rec treemonadizer (f:'a -> 'b reader) (t:'a tree):('b tree) reader =
1277   match t with Leaf x -> reader_bind (f x) (fun x' -> reader_unit (Leaf x'))
1278              | Node (l, r) -> reader_bind (treemonadizer f l) (fun x ->
1279                                 reader_bind (treemonadizer f r) (fun y ->
1280                                   reader_unit (Node (x, y))));;
1281 </pre>
1282
1283 This function says: give me a function `f` that knows how to turn
1284 something of type `'a` into an `'b reader`, and I'll show you how to 
1285 turn an `'a tree` into an `'a tree reader`.  In more fanciful terms, 
1286 the `treemonadizer` function builds plumbing that connects all of the
1287 leaves of a tree into one connected monadic network; it threads the
1288 monad through the leaves.
1289
1290 <pre>
1291 # treemonadizer int2int_reader t1 (fun i -> i + i);;
1292 - : int tree =
1293 Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
1294 </pre>
1295
1296 Here, our environment is the doubling function (`fun i -> i + i`).  If
1297 we apply the very same `int tree reader` (namely, `treemonadizer
1298 int2int_reader t1`) to a different `int->int` function---say, the
1299 squaring function, `fun i -> i * i`---we get an entirely different
1300 result:
1301
1302 <pre>
1303 # treemonadizer int2int_reader t1 (fun i -> i * i);;
1304 - : int tree =
1305 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
1306 </pre>
1307
1308 Now that we have a tree transducer that accepts a monad as a
1309 parameter, we can see what it would take to swap in a different monad.
1310 For instance, we can use a state monad to count the number of nodes in
1311 the tree.
1312
1313 <pre>
1314 type 'a state = int -> 'a * int;;
1315 let state_unit x i = (x, i+.5);;
1316 let state_bind u f i = let (a, i') = u i in f a (i'+.5);;
1317 </pre>
1318
1319 Gratifyingly, we can use the `treemonadizer` function without any
1320 modification whatsoever, except for replacing the (parametric) type
1321 `reader` with `state`:
1322
1323 <pre>
1324 let rec treemonadizer (f:'a -> 'b state) (t:'a tree):('b tree) state =
1325   match t with Leaf x -> state_bind (f x) (fun x' -> state_unit (Leaf x'))
1326              | Node (l, r) -> state_bind (treemonadizer f l) (fun x ->
1327                                 state_bind (treemonadizer f r) (fun y ->
1328                                   state_unit (Node (x, y))));;
1329 </pre>
1330
1331 Then we can count the number of nodes in the tree:
1332
1333 <pre>
1334 # treemonadizer state_unit t1 0;;
1335 - : int tree * int =
1336 (Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11))), 13)
1337
1338     .
1339  ___|___
1340  |     |
1341  .     .
1342 _|__  _|__
1343 |  |  |  |
1344 2  3  5  .
1345         _|__
1346         |  |
1347         7  11
1348 </pre>
1349
1350 Notice that we've counted each internal node twice---it's a good
1351 exercise to adjust the code to count each node once.
1352
1353 One more revealing example before getting down to business: replacing
1354 `state` everywhere in `treemonadizer` with `list` gives us
1355
1356 <pre>
1357 # treemonadizer (fun x -> [ [x; square x] ]) t1;;
1358 - : int list tree list =
1359 [Node
1360   (Node (Leaf [2; 4], Leaf [3; 9]),
1361    Node (Leaf [5; 25], Node (Leaf [7; 49], Leaf [11; 121])))]
1362 </pre>
1363
1364 Unlike the previous cases, instead of turning a tree into a function
1365 from some input to a result, this transformer replaces each `int` with
1366 a list of `int`'s.
1367
1368 Now for the main point.  What if we wanted to convert a tree to a list
1369 of leaves?  
1370
1371 <pre>
1372 type ('a, 'r) continuation = ('a -> 'r) -> 'r;;
1373 let continuation_unit x c = c x;;
1374 let continuation_bind u f c = u (fun a -> f a c);;
1375
1376 let rec treemonadizer (f:'a -> ('b, 'r) continuation) (t:'a tree):(('b tree), 'r) continuation =
1377   match t with Leaf x -> continuation_bind (f x) (fun x' -> continuation_unit (Leaf x'))
1378              | Node (l, r) -> continuation_bind (treemonadizer f l) (fun x ->
1379                                 continuation_bind (treemonadizer f r) (fun y ->
1380                                   continuation_unit (Node (x, y))));;
1381 </pre>
1382
1383 We use the continuation monad described above, and insert the
1384 `continuation` type in the appropriate place in the `treemonadizer` code.
1385 We then compute:
1386
1387 <pre>
1388 # treemonadizer (fun a c -> a :: (c a)) t1 (fun t -> []);;
1389 - : int list = [2; 3; 5; 7; 11]
1390 </pre>
1391
1392 We have found a way of collapsing a tree into a list of its leaves.
1393
1394 The continuation monad is amazingly flexible; we can use it to
1395 simulate some of the computations performed above.  To see how, first
1396 note that an interestingly uninteresting thing happens if we use the
1397 continuation unit as our first argument to `treemonadizer`, and then
1398 apply the result to the identity function:
1399
1400 <pre>
1401 # treemonadizer continuation_unit t1 (fun x -> x);;
1402 - : int tree =
1403 Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11)))
1404 </pre>
1405
1406 That is, nothing happens.  But we can begin to substitute more
1407 interesting functions for the first argument of `treemonadizer`:
1408
1409 <pre>
1410 (* Simulating the tree reader: distributing a operation over the leaves *)
1411 # treemonadizer (fun a c -> c (square a)) t1 (fun x -> x);;
1412 - : int tree =
1413 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
1414
1415 (* Simulating the int list tree list *)
1416 # treemonadizer (fun a c -> c [a; square a]) t1 (fun x -> x);;
1417 - : int list tree =
1418 Node
1419  (Node (Leaf [2; 4], Leaf [3; 9]),
1420   Node (Leaf [5; 25], Node (Leaf [7; 49], Leaf [11; 121])))
1421
1422 (* Counting leaves *)
1423 # treemonadizer (fun a c -> 1 + c a) t1 (fun x -> 0);;
1424 - : int = 5
1425 </pre>
1426
1427 We could simulate the tree state example too, but it would require
1428 generalizing the type of the continuation monad to 
1429
1430     type ('a -> 'b -> 'c) continuation = ('a -> 'b) -> 'c;;
1431
1432 The binary tree monad
1433 ---------------------
1434
1435 Of course, by now you may have realized that we have discovered a new
1436 monad, the binary tree monad:
1437
1438 <pre>
1439 type 'a tree = Leaf of 'a | Node of ('a tree) * ('a tree);;
1440 let tree_unit (x:'a) = Leaf x;;
1441 let rec tree_bind (u:'a tree) (f:'a -> 'b tree):'b tree = 
1442   match u with Leaf x -> f x 
1443              | Node (l, r) -> Node ((tree_bind l f), (tree_bind r f));;
1444 </pre>
1445
1446 For once, let's check the Monad laws.  The left identity law is easy:
1447
1448     Left identity: bind (unit a) f = bind (Leaf a) f = fa
1449
1450 To check the other two laws, we need to make the following
1451 observation: it is easy to prove based on `tree_bind` by a simple
1452 induction on the structure of the first argument that the tree
1453 resulting from `bind u f` is a tree with the same strucure as `u`,
1454 except that each leaf `a` has been replaced with `fa`:
1455
1456 \tree (. (fa1) (. (. (. (fa2)(fa3)) (fa4)) (fa5)))
1457 <pre>
1458                 .                         .       
1459               __|__                     __|__   
1460               |   |                     |   |   
1461               a1  .                    fa1  .   
1462                  _|__                     __|__ 
1463                  |  |                     |   | 
1464                  .  a5                    .  fa5
1465    bind         _|__       f   =        __|__   
1466                 |  |                    |   |   
1467                 .  a4                   .  fa4  
1468               __|__                   __|___   
1469               |   |                   |    |   
1470               a2  a3                 fa2  fa3         
1471 </pre>   
1472
1473 Given this equivalence, the right identity law
1474
1475     Right identity: bind u unit = u
1476
1477 falls out once we realize that
1478
1479     bind (Leaf a) unit = unit a = Leaf a
1480
1481 As for the associative law,
1482
1483     Associativity: bind (bind u f) g = bind u (\a. bind (fa) g)
1484
1485 we'll give an example that will show how an inductive proof would
1486 proceed.  Let `f a = Node (Leaf a, Leaf a)`.  Then
1487
1488 \tree (. (. (. (. (a1)(a2)))))
1489 \tree (. (. (. (. (a1) (a1)) (. (a1) (a1)))  ))
1490 <pre>
1491                                            .
1492                                        ____|____
1493           .               .            |       |
1494 bind    __|__   f  =    __|_    =      .       .
1495         |   |           |   |        __|__   __|__
1496         a1  a2         fa1 fa2       |   |   |   |
1497                                      a1  a1  a1  a1  
1498 </pre>
1499
1500 Now when we bind this tree to `g`, we get
1501
1502 <pre>
1503            .
1504        ____|____
1505        |       |
1506        .       .
1507      __|__   __|__
1508      |   |   |   |
1509     ga1 ga1 ga1 ga1  
1510 </pre>
1511
1512 At this point, it should be easy to convince yourself that
1513 using the recipe on the right hand side of the associative law will
1514 built the exact same final tree.
1515
1516 So binary trees are a monad.
1517
1518 Haskell combines this monad with the Option monad to provide a monad
1519 called a
1520 [SearchTree](http://hackage.haskell.org/packages/archive/tree-monad/0.2.1/doc/html/src/Control-Monad-SearchTree.html#SearchTree)
1521 that is intended to 
1522 represent non-deterministic computations as a tree.
1523
1524