d0ecb7045ab4307fe1bbb9ba3ed67fda3ba891bb
[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 ##[[Tree and List Zippers]]##
5
6 ##[[Coroutines and Aborts]]##
7
8 ##[[From Lists to Continuations]]##
9
10 ##Same-fringe using a zipper-based coroutine##
11
12 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):
13
14             .                .
15            / \              / \
16           .   3            1   .
17          / \                  / \
18         1   2                2   3
19
20 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.
21
22
23 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:
24
25             .                .
26            / \              / \
27           .   3            1   .
28          / \                  / \
29         1   2                2   3
30
31 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.
32
33 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.
34
35 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.
36
37 First, we define a type for leaf-labeled, binary trees:
38
39         type 'a tree = Leaf of 'a | Node of ('a tree * 'a tree)
40
41 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:
42
43         # type blah = Blah of (int * int * (char -> bool));;
44
45 and then having to remember which element in the triple was which:
46
47         # let b1 = Blah (1, (fun c -> c = 'M'), 2);;
48         Error: This expression has type int * (char -> bool) * int
49        but an expression was expected of type int * int * (char -> bool)
50         # (* damnit *)
51         # let b1 = Blah (1, 2, (fun c -> c = 'M'));;
52         val b1 : blah = Blah (1, 2, <fun>)
53
54 records let you attach descriptive labels to the components of the tuple:
55
56         # type blah_record = { height : int; weight : int; char_tester : char -> bool };;
57         # let b2 = { height = 1; weight = 2; char_tester = fun c -> c = 'M' };;
58         val b2 : blah_record = {height = 1; weight = 2; char_tester = <fun>}
59         # let b3 = { height = 1; char_tester = (fun c -> c = 'K'); weight = 3 };; (* also works *)
60         val b3 : blah_record = {height = 1; weight = 3; char_tester = <fun>}
61
62 These were the strategies to extract the components of an unlabeled tuple:
63
64         let h = fst some_pair;; (* accessor functions fst and snd are only predefined for pairs *)
65
66         let (h, w, test) = b1;; (* works for arbitrary tuples *)
67
68         match b1 with
69         | (h, w, test) -> ...;; (* same as preceding *)
70
71 Here is how you can extract the components of a labeled record:
72
73         let h = b2.height;; (* handy! *)
74
75         let {height = h; weight = w; char_tester = test} = b2
76         in (* go on to use h, w, and test ... *)
77
78         match test with
79         | {height = h; weight = w; char_tester = test} ->
80                 (* go on to use h, w, and test ... *)
81
82 Anyway, using record types, we might define the tree zipper interface like so:
83
84         type 'a starred_level = Root | Starring_Left of 'a starred_nonroot | Starring_Right of 'a starred_nonroot
85         and 'a starred_nonroot = { parent : 'a starred_level; sibling: 'a tree };;
86
87         type 'a zipper = { level : 'a starred_level; filler: 'a tree };;
88
89         let rec move_botleft (z : 'a zipper) : 'a zipper =
90             (* returns z if the targetted node in z has no children *)
91             (* else returns move_botleft (zipper which results from moving down and left in z) *)
92
93 <!--
94             let {level; filler} = z
95             in match filler with
96             | Leaf _ -> z
97             | Node(left, right) ->
98                 let zdown = {level = Starring_Left {parent = level; sibling = right}; filler = left}
99                 in move_botleft zdown
100             ;;
101 -->
102
103         let rec move_right_or_up (z : 'a zipper) : 'a zipper option =
104             (* if it's possible to move right in z, returns Some (the result of doing so) *)
105             (* else if it's not possible to move any further up in z, returns None *)
106             (* else returns move_right_or_up (result of moving up in z) *)
107
108 <!--
109             let {level; filler} = z
110             in match level with
111             | Starring_Left {parent; sibling = right} -> Some {level = Starring_Right {parent; sibling = filler}; filler = right}
112             | Root -> None
113             | Starring_Right {parent; sibling = left} ->
114                 let z' = {level = parent; filler = Node(left, filler)}
115                 in move_right_or_up z'
116             ;;
117 -->
118
119 The following function takes an 'a tree and returns an 'a zipper focused on its root:
120
121         let new_zipper (t : 'a tree) : 'a zipper =
122             {level = Root; filler = t}
123             ;;
124
125 Finally, we can use a mutable reference cell to define a function that enumerates a tree's fringe until it's exhausted:
126
127         let make_fringe_enumerator (t: 'a tree) =
128             (* create a zipper targetting the botleft of t *)
129             let zbotleft = move_botleft (new_zipper t)
130             (* create a refcell initially pointing to zbotleft *)
131             in let zcell = ref (Some zbotleft)
132             (* construct the next_leaf function *)
133             in let next_leaf () : 'a option =
134                 match !zcell with
135                 | Some z -> (
136                     (* extract label of currently-targetted leaf *)
137                     let Leaf current = z.filler
138                     (* update zcell to point to next leaf, if there is one *)
139                     in let () = zcell := match move_right_or_up z with
140                         | None -> None
141                         | Some z' -> Some (move_botleft z')
142                     (* return saved label *)
143                     in Some current
144                 | None -> (* we've finished enumerating the fringe *)
145                     None
146                 )
147             (* return the next_leaf function *)
148             in next_leaf
149             ;;
150
151 Here's an example of `make_fringe_enumerator` in action:
152
153         # let tree1 = Leaf 1;;
154         val tree1 : int tree = Leaf 1
155         # let next1 = make_fringe_enumerator tree1;;
156         val next1 : unit -> int option = <fun>
157         # next1 ();;
158         - : int option = Some 1
159         # next1 ();;
160         - : int option = None
161         # next1 ();;
162         - : int option = None
163         # let tree2 = Node (Node (Leaf 1, Leaf 2), Leaf 3);;
164         val tree2 : int tree = Node (Node (Leaf 1, Leaf 2), Leaf 3)
165         # let next2 = make_fringe_enumerator tree2;;
166         val next2 : unit -> int option = <fun>
167         # next2 ();;
168         - : int option = Some 1
169         # next2 ();;
170         - : int option = Some 2
171         # next2 ();;
172         - : int option = Some 3
173         # next2 ();;
174         - : int option = None
175         # next2 ();;
176         - : int option = None
177
178 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`.
179
180 Using these fringe enumerators, we can write our `same_fringe` function like this:
181
182         let same_fringe (t1 : 'a tree) (t2 : 'a tree) : bool =
183                 let next1 = make_fringe_enumerator t1
184                 in let next2 = make_fringe_enumerator t2
185                 in let rec loop () : bool =
186                         match next1 (), next2 () with
187                         | Some a, Some b when a = b -> loop ()
188                         | None, None -> true
189                         | _ -> false
190                 in loop ()
191                 ;;
192
193 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.
194
195 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*.
196
197 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:
198
199         main program            next1 thread            next2 thread
200         ------------            ------------            ------------
201         start next1
202         (paused)                        starting
203         (paused)                        calculate first leaf
204         (paused)                        <--- return it
205         start next2                     (paused)                        starting
206         (paused)                        (paused)                        calculate first leaf
207         (paused)                        (paused)                        <-- return it
208         compare leaves          (paused)                        (paused)
209         call loop again         (paused)                        (paused)
210         call next1 again        (paused)                        (paused)
211         (paused)                        calculate next leaf     (paused)
212         (paused)                        <-- return it           (paused)
213         ... and so on ...
214
215 If you want to read more about these kinds of threads, here are some links:
216
217 <!-- *  [[!wikipedia Computer_multitasking]]
218 *       [[!wikipedia Thread_(computer_science)]] -->
219
220 *       [[!wikipedia Coroutine]]
221 *       [[!wikipedia Iterator]]
222 *       [[!wikipedia Generator_(computer_science)]]
223 *       [[!wikipedia Fiber_(computer_science)]]
224 <!-- *  [[!wikipedia Green_threads]]
225 *       [[!wikipedia Protothreads]] -->
226
227 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.
228
229 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:
230
231         > function fringe_enumerator (tree)
232             if tree.leaf then
233                 coroutine.yield (tree.leaf)
234             else
235                 fringe_enumerator (tree.left)
236                 fringe_enumerator (tree.right)
237             end
238         end
239         
240         > function same_fringe (tree1, tree2)
241             local next1 = coroutine.wrap (fringe_enumerator)
242             local next2 = coroutine.wrap (fringe_enumerator)
243             local function loop (leaf1, leaf2)
244                 if leaf1 or leaf2 then
245                     return leaf1 == leaf2 and loop( next1(), next2() )
246                 elseif not leaf1 and not leaf2 then
247                     return true
248                 else
249                     return false
250                 end
251             end
252             return loop (next1(tree1), next2(tree2))
253         end
254         
255         > return same_fringe ( {leaf=1}, {leaf=2})
256         false
257         
258         > return same_fringe ( {leaf=1}, {leaf=1})
259         true
260         
261         > return same_fringe ( {left = {leaf=1}, right = {left = {leaf=2}, right = {leaf=3}}},
262             {left = {left = {leaf=1}, right = {leaf=2}}, right = {leaf=3}} )
263         true
264
265 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.
266
267
268 ##Exceptions and Aborts##
269
270 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.
271
272 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:
273
274         # let lst = [1; 2] in
275           "a" :: lst;;
276         Error: This expression has type int list
277                    but an expression was expected of type string list
278
279 But you may also have encountered other kinds of error, that arise while your program is running. For example:
280
281         # 1/0;;
282         Exception: Division_by_zero.
283         # List.nth [1;2] 10;;
284         Exception: Failure "nth".
285
286 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`:
287
288         let nth l n =
289           if n < 0 then invalid_arg "List.nth" else
290           let rec nth_aux l n =
291                 match l with
292                 | [] -> failwith "nth"
293                 | a::l -> if n = 0 then a else nth_aux l (n-1)
294           in nth_aux l n
295
296 Notice the two clauses `invalid_arg "List.nth"` and `failwith "nth"`. These are two helper functions which are shorthand for:
297
298         raise (Invalid_argument "List.nth");;
299         raise (Failure "nth");;
300
301 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:
302
303         raise ex
304
305 the effect is for the program to immediately stop without evaluating any further code:
306
307         # let xcell = ref 0;;
308         val xcell : int ref = {contents = 0}
309         # let ex = Failure "test"
310           in let _ = raise ex
311           in xcell := 1;;
312         Exception: Failure "test".
313         # !xcell;;
314         - : int = 0
315
316 Notice that the line `xcell := 1` was never evaluated, so the contents of `xcell` are still `0`.
317
318 I said when you evaluate the expression:
319
320         raise ex
321
322 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:
323
324         # let foo x =
325             try
326                 if x = 1 then 10
327                 else if x = 2 then raise (Failure "two")
328                 else raise (Failure "three")
329             with Failure "two" -> 20
330             ;;
331         val foo : int -> int = <fun>
332         # foo 1;;
333         - : int = 10
334         # foo 2;;
335         - : int = 20
336         # foo 3;;
337         Exception: Failure "three".
338
339 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.
340
341 So what I should have said is that when you evaluate the expression:
342
343         raise ex
344
345 *and that exception is never caught*, then the effect is for the program to immediately stop.
346
347 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.
348
349 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:
350
351         # try
352             try
353                 raise (Failure "blah")
354             with Failure "fooey" -> 10
355           with Failure "blah" -> 20;;
356         - : int = 20
357
358 The matching `try ... with ...` block need not *lexically surround* the site where the error was raised:
359
360         # let foo b x =
361             try
362                 b x
363             with Failure "blah" -> 20
364         in let bar x =
365             raise (Failure "blah")
366         in foo bar 0;;
367         - : int = 20
368
369 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`.
370
371 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:
372
373         # let foo x =
374             try
375                 (if x = 1 then 10
376                 else abort 20) + 1
377             end
378             ;;
379
380 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.
381
382 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:
383
384         > function foo(x)
385             local value
386             if (x == 1) then
387                 value = 10
388             else
389                 return 20
390             end
391             return value + 1
392         end
393         
394         > return foo(1)
395         11
396         
397         > return foo(2)
398         20
399
400 Okay, so that's our second execution pattern.
401
402 ##What do these have in common?##
403
404 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.
405
406 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:
407
408         let foo x =
409             try
410                 (if x = 1 then 10
411                 else abort 20) + 1
412             end
413         in (foo 2) + 1;;
414
415 we can imagine a box:
416
417         let foo x =
418         +---------------------------+
419         |   try                     |
420         |       (if x = 1 then 10   |
421         |       else abort 20) + 1  |
422         |   end                     |
423         +---------------------------+
424         in (foo 2) + 1;;
425
426 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.
427
428 <!--
429 # #require "delimcc";;
430 # open Delimcc;;
431 # let reset body = let p = new_prompt () in push_prompt p (body p);;
432 val reset : ('a Delimcc.prompt -> unit -> 'a) -> 'a = <fun>
433 # let foo x = reset(fun p () -> (shift p (fun k -> if x = 1 then k 10 else 20)) + 1) in (foo 1) + 100;;
434 - : int = 111
435 # let foo x = reset(fun p () -> (shift p (fun k -> if x = 1 then k 10 else 20)) + 1) in (foo 2) + 100;;
436 - : int = 120
437 -->
438
439
440
441
442 --------------------------------------
443
444 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.
445
446
447 ##Introducing Continuations##
448
449 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."
450
451 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.
452
453 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.
454
455 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.
456
457 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.
458
459 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:
460
461         \handler. handler x y
462
463 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.
464
465 Consider a complex computation, such as:
466
467         1 + 2 * (1 - g (3 + 4))
468
469 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:
470
471         \result. 1 + 2 * (1 - result)
472
473 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.
474
475 Go back and read the material on "Aborting a Search Through a List" in [[Week4]] for an example of doing this.
476
477 In very general terms, the strategy is to work with functions like this:
478
479         let g' k (i : int) =
480                 ... do stuff ...
481                 ... if you want to abort early, supply an argument to k ...
482                 ... do more stuff ...
483                 ... normal result
484         in let gcon = fun result -> 1 + 2 * (1 - result)
485         in gcon (g' gcon (3 + 4))
486
487 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.
488
489 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:
490
491         let g' k (i : int) =
492                 ... do stuff ...
493                 ... if you want to abort early, supply an argument to k ...
494                 ... do more stuff ...
495                 ... normal result
496         in let gcon = fun result ->
497                 let final_value = 1 + 2 * (1 - result)
498                 in end_program_with final_value
499         in gcon (g' gcon (3 + 4))
500
501 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.)
502
503 So now, guess what would be the result of doing the following:
504
505         let g' k (i : int) =
506                 1 + k i
507         in let gcon = fun result ->
508                 let final_value = (1, result)
509                 in end_program_with final_value
510         in gcon (g' gcon (3 + 4))
511
512 <!-- (1, 7) ... explain why not (1, 8) -->
513
514 Manipulating trees with monads
515 ------------------------------
516
517 This topic develops an idea based on a detailed suggestion of Ken
518 Shan's.  We'll build a series of functions that operate on trees,
519 doing various things, including replacing leaves, counting nodes, and
520 converting a tree to a list of leaves.  The end result will be an
521 application for continuations.
522
523 From an engineering standpoint, we'll build a tree transformer that
524 deals in monads.  We can modify the behavior of the system by swapping
525 one monad for another.  We've already seen how adding a monad can add
526 a layer of funtionality without disturbing the underlying system, for
527 instance, in the way that the reader monad allowed us to add a layer
528 of intensionality to an extensional grammar, but we have not yet seen
529 the utility of replacing one monad with other.
530
531 First, we'll be needing a lot of trees during the remainder of the
532 course.  Here's a type constructor for binary trees:
533
534     type 'a tree = Leaf of 'a | Node of ('a tree * 'a tree)
535
536 These are trees in which the internal nodes do not have labels.  [How
537 would you adjust the type constructor to allow for labels on the
538 internal nodes?]
539
540 We'll be using trees where the nodes are integers, e.g.,
541
542
543 <pre>
544 let t1 = Node ((Node ((Leaf 2), (Leaf 3))),
545                (Node ((Leaf 5),(Node ((Leaf 7),
546                                       (Leaf 11))))))
547
548     .
549  ___|___
550  |     |
551  .     .
552 _|__  _|__
553 |  |  |  |
554 2  3  5  .
555         _|__
556         |  |
557         7  11
558 </pre>
559
560 Our first task will be to replace each leaf with its double:
561
562 <pre>
563 let rec treemap (newleaf:'a -> 'b) (t:'a tree):('b tree) =
564   match t with Leaf x -> Leaf (newleaf x)
565              | Node (l, r) -> Node ((treemap newleaf l),
566                                     (treemap newleaf r));;
567 </pre>
568 `treemap` takes a function that transforms old leaves into new leaves, 
569 and maps that function over all the leaves in the tree, leaving the
570 structure of the tree unchanged.  For instance:
571
572 <pre>
573 let double i = i + i;;
574 treemap double t1;;
575 - : int tree =
576 Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
577
578     .
579  ___|____
580  |      |
581  .      .
582 _|__  __|__
583 |  |  |   |
584 4  6  10  .
585         __|___
586         |    |
587         14   22
588 </pre>
589
590 We could have built the doubling operation right into the `treemap`
591 code.  However, because what to do to each leaf is a parameter, we can
592 decide to do something else to the leaves without needing to rewrite
593 `treemap`.  For instance, we can easily square each leaf instead by
594 supplying the appropriate `int -> int` operation in place of `double`:
595
596 <pre>
597 let square x = x * x;;
598 treemap square t1;;
599 - : int tree =ppp
600 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
601 </pre>
602
603 Note that what `treemap` does is take some global, contextual
604 information---what to do to each leaf---and supplies that information
605 to each subpart of the computation.  In other words, `treemap` has the
606 behavior of a reader monad.  Let's make that explicit.  
607
608 In general, we're on a journey of making our treemap function more and
609 more flexible.  So the next step---combining the tree transducer with
610 a reader monad---is to have the treemap function return a (monadized)
611 tree that is ready to accept any `int->int` function and produce the
612 updated tree.
613
614 \tree (. (. (f2) (f3))(. (f5) (.(f7)(f11))))
615 <pre>
616 \f    .
617   ____|____
618   |       |
619   .       .
620 __|__   __|__
621 |   |   |   |
622 f2  f3  f5  .
623           __|___
624           |    |
625           f7  f11
626 </pre>
627
628 That is, we want to transform the ordinary tree `t1` (of type `int
629 tree`) into a reader object of type `(int->int)-> int tree`: something 
630 that, when you apply it to an `int->int` function returns an `int
631 tree` in which each leaf `x` has been replaced with `(f x)`.
632
633 With previous readers, we always knew which kind of environment to
634 expect: either an assignment function (the original calculator
635 simulation), a world (the intensionality monad), an integer (the
636 Jacobson-inspired link monad), etc.  In this situation, it will be
637 enough for now to expect that our reader will expect a function of
638 type `int->int`.
639
640 <pre>
641 type 'a reader = (int->int) -> 'a;;  (* mnemonic: e for environment *)
642 let reader_unit (x:'a): 'a reader = fun _ -> x;;
643 let reader_bind (u: 'a reader) (f:'a -> 'c reader):'c reader = fun e -> f (u e) e;;
644 </pre>
645
646 It's easy to figure out how to turn an `int` into an `int reader`:
647
648 <pre>
649 let int2int_reader (x:'a): 'b reader = fun (op:'a -> 'b) -> op x;;
650 int2int_reader 2 (fun i -> i + i);;
651 - : int = 4
652 </pre>
653
654 But what do we do when the integers are scattered over the leaves of a
655 tree?  A binary tree is not the kind of thing that we can apply a
656 function of type `int->int` to.
657
658 <pre>
659 let rec treemonadizer (f:'a -> 'b reader) (t:'a tree):('b tree) reader =
660   match t with Leaf x -> reader_bind (f x) (fun x' -> reader_unit (Leaf x'))
661              | Node (l, r) -> reader_bind (treemonadizer f l) (fun x ->
662                                 reader_bind (treemonadizer f r) (fun y ->
663                                   reader_unit (Node (x, y))));;
664 </pre>
665
666 This function says: give me a function `f` that knows how to turn
667 something of type `'a` into an `'b reader`, and I'll show you how to 
668 turn an `'a tree` into an `'a tree reader`.  In more fanciful terms, 
669 the `treemonadizer` function builds plumbing that connects all of the
670 leaves of a tree into one connected monadic network; it threads the
671 monad through the leaves.
672
673 <pre>
674 # treemonadizer int2int_reader t1 (fun i -> i + i);;
675 - : int tree =
676 Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
677 </pre>
678
679 Here, our environment is the doubling function (`fun i -> i + i`).  If
680 we apply the very same `int tree reader` (namely, `treemonadizer
681 int2int_reader t1`) to a different `int->int` function---say, the
682 squaring function, `fun i -> i * i`---we get an entirely different
683 result:
684
685 <pre>
686 # treemonadizer int2int_reader t1 (fun i -> i * i);;
687 - : int tree =
688 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
689 </pre>
690
691 Now that we have a tree transducer that accepts a monad as a
692 parameter, we can see what it would take to swap in a different monad.
693 For instance, we can use a state monad to count the number of nodes in
694 the tree.
695
696 <pre>
697 type 'a state = int -> 'a * int;;
698 let state_unit x i = (x, i+.5);;
699 let state_bind u f i = let (a, i') = u i in f a (i'+.5);;
700 </pre>
701
702 Gratifyingly, we can use the `treemonadizer` function without any
703 modification whatsoever, except for replacing the (parametric) type
704 `reader` with `state`:
705
706 <pre>
707 let rec treemonadizer (f:'a -> 'b state) (t:'a tree):('b tree) state =
708   match t with Leaf x -> state_bind (f x) (fun x' -> state_unit (Leaf x'))
709              | Node (l, r) -> state_bind (treemonadizer f l) (fun x ->
710                                 state_bind (treemonadizer f r) (fun y ->
711                                   state_unit (Node (x, y))));;
712 </pre>
713
714 Then we can count the number of nodes in the tree:
715
716 <pre>
717 # treemonadizer state_unit t1 0;;
718 - : int tree * int =
719 (Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11))), 13)
720
721     .
722  ___|___
723  |     |
724  .     .
725 _|__  _|__
726 |  |  |  |
727 2  3  5  .
728         _|__
729         |  |
730         7  11
731 </pre>
732
733 Notice that we've counted each internal node twice---it's a good
734 exercise to adjust the code to count each node once.
735
736 One more revealing example before getting down to business: replacing
737 `state` everywhere in `treemonadizer` with `list` gives us
738
739 <pre>
740 # treemonadizer (fun x -> [ [x; square x] ]) t1;;
741 - : int list tree list =
742 [Node
743   (Node (Leaf [2; 4], Leaf [3; 9]),
744    Node (Leaf [5; 25], Node (Leaf [7; 49], Leaf [11; 121])))]
745 </pre>
746
747 Unlike the previous cases, instead of turning a tree into a function
748 from some input to a result, this transformer replaces each `int` with
749 a list of `int`'s.
750
751 Now for the main point.  What if we wanted to convert a tree to a list
752 of leaves?  
753
754 <pre>
755 type ('a, 'r) continuation = ('a -> 'r) -> 'r;;
756 let continuation_unit x c = c x;;
757 let continuation_bind u f c = u (fun a -> f a c);;
758
759 let rec treemonadizer (f:'a -> ('b, 'r) continuation) (t:'a tree):(('b tree), 'r) continuation =
760   match t with Leaf x -> continuation_bind (f x) (fun x' -> continuation_unit (Leaf x'))
761              | Node (l, r) -> continuation_bind (treemonadizer f l) (fun x ->
762                                 continuation_bind (treemonadizer f r) (fun y ->
763                                   continuation_unit (Node (x, y))));;
764 </pre>
765
766 We use the continuation monad described above, and insert the
767 `continuation` type in the appropriate place in the `treemonadizer` code.
768 We then compute:
769
770 <pre>
771 # treemonadizer (fun a c -> a :: (c a)) t1 (fun t -> []);;
772 - : int list = [2; 3; 5; 7; 11]
773 </pre>
774
775 We have found a way of collapsing a tree into a list of its leaves.
776
777 The continuation monad is amazingly flexible; we can use it to
778 simulate some of the computations performed above.  To see how, first
779 note that an interestingly uninteresting thing happens if we use the
780 continuation unit as our first argument to `treemonadizer`, and then
781 apply the result to the identity function:
782
783 <pre>
784 # treemonadizer continuation_unit t1 (fun x -> x);;
785 - : int tree =
786 Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11)))
787 </pre>
788
789 That is, nothing happens.  But we can begin to substitute more
790 interesting functions for the first argument of `treemonadizer`:
791
792 <pre>
793 (* Simulating the tree reader: distributing a operation over the leaves *)
794 # treemonadizer (fun a c -> c (square a)) t1 (fun x -> x);;
795 - : int tree =
796 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
797
798 (* Simulating the int list tree list *)
799 # treemonadizer (fun a c -> c [a; square a]) t1 (fun x -> x);;
800 - : int list tree =
801 Node
802  (Node (Leaf [2; 4], Leaf [3; 9]),
803   Node (Leaf [5; 25], Node (Leaf [7; 49], Leaf [11; 121])))
804
805 (* Counting leaves *)
806 # treemonadizer (fun a c -> 1 + c a) t1 (fun x -> 0);;
807 - : int = 5
808 </pre>
809
810 We could simulate the tree state example too, but it would require
811 generalizing the type of the continuation monad to 
812
813     type ('a -> 'b -> 'c) continuation = ('a -> 'b) -> 'c;;
814
815 The binary tree monad
816 ---------------------
817
818 Of course, by now you may have realized that we have discovered a new
819 monad, the binary tree monad:
820
821 <pre>
822 type 'a tree = Leaf of 'a | Node of ('a tree) * ('a tree);;
823 let tree_unit (x:'a) = Leaf x;;
824 let rec tree_bind (u:'a tree) (f:'a -> 'b tree):'b tree = 
825   match u with Leaf x -> f x 
826              | Node (l, r) -> Node ((tree_bind l f), (tree_bind r f));;
827 </pre>
828
829 For once, let's check the Monad laws.  The left identity law is easy:
830
831     Left identity: bind (unit a) f = bind (Leaf a) f = fa
832
833 To check the other two laws, we need to make the following
834 observation: it is easy to prove based on `tree_bind` by a simple
835 induction on the structure of the first argument that the tree
836 resulting from `bind u f` is a tree with the same strucure as `u`,
837 except that each leaf `a` has been replaced with `fa`:
838
839 \tree (. (fa1) (. (. (. (fa2)(fa3)) (fa4)) (fa5)))
840 <pre>
841                 .                         .       
842               __|__                     __|__   
843               |   |                     |   |   
844               a1  .                    fa1  .   
845                  _|__                     __|__ 
846                  |  |                     |   | 
847                  .  a5                    .  fa5
848    bind         _|__       f   =        __|__   
849                 |  |                    |   |   
850                 .  a4                   .  fa4  
851               __|__                   __|___   
852               |   |                   |    |   
853               a2  a3                 fa2  fa3         
854 </pre>   
855
856 Given this equivalence, the right identity law
857
858     Right identity: bind u unit = u
859
860 falls out once we realize that
861
862     bind (Leaf a) unit = unit a = Leaf a
863
864 As for the associative law,
865
866     Associativity: bind (bind u f) g = bind u (\a. bind (fa) g)
867
868 we'll give an example that will show how an inductive proof would
869 proceed.  Let `f a = Node (Leaf a, Leaf a)`.  Then
870
871 \tree (. (. (. (. (a1)(a2)))))
872 \tree (. (. (. (. (a1) (a1)) (. (a1) (a1)))  ))
873 <pre>
874                                            .
875                                        ____|____
876           .               .            |       |
877 bind    __|__   f  =    __|_    =      .       .
878         |   |           |   |        __|__   __|__
879         a1  a2         fa1 fa2       |   |   |   |
880                                      a1  a1  a1  a1  
881 </pre>
882
883 Now when we bind this tree to `g`, we get
884
885 <pre>
886            .
887        ____|____
888        |       |
889        .       .
890      __|__   __|__
891      |   |   |   |
892     ga1 ga1 ga1 ga1  
893 </pre>
894
895 At this point, it should be easy to convince yourself that
896 using the recipe on the right hand side of the associative law will
897 built the exact same final tree.
898
899 So binary trees are a monad.
900
901 Haskell combines this monad with the Option monad to provide a monad
902 called a
903 [SearchTree](http://hackage.haskell.org/packages/archive/tree-monad/0.2.1/doc/html/src/Control-Monad-SearchTree.html#SearchTree)
904 that is intended to 
905 represent non-deterministic computations as a tree.
906
907 ##[[List Monad as Continuation Monad]]##
908
909 ##[[Manipulating Trees with Monads]]##
910