add some old files
authorJim <jim.pryor@nyu.edu>
Thu, 23 Apr 2015 08:57:10 +0000 (04:57 -0400)
committerJim <jim.pryor@nyu.edu>
Thu, 23 Apr 2015 08:57:10 +0000 (04:57 -0400)
exercises/_assignment12.mdwn [new file with mode: 0644]
exercises/_assignment13.mdwn [new file with mode: 0644]
exercises/_assignment14.mdwn [new file with mode: 0644]
topics/_coroutines_and_aborts.mdwn [new file with mode: 0644]
topics/_cps.mdwn [new file with mode: 0644]
topics/_cps_and_continuation_operators.mdwn [new file with mode: 0644]
topics/_from_list_zippers_to_continuations.mdwn [new file with mode: 0644]
topics/_list_monad_as_continuation_monad.mdwn [new file with mode: 0644]
topics/_manipulating_trees_with_monads.mdwn [new file with mode: 0644]
topics/week12_abortable_traversals [new file with mode: 0644]
topics/week12_list_and_tree_zippers.mdwn [new file with mode: 0644]

diff --git a/exercises/_assignment12.mdwn b/exercises/_assignment12.mdwn
new file mode 100644 (file)
index 0000000..f09556f
--- /dev/null
@@ -0,0 +1,135 @@
+1.     Complete the definitions of `move_botleft` and `move_right_or_up` from the same-fringe solution in the [[week11]] notes. **Test your attempts** against some example trees to see if the resulting `make_fringe_enumerator` and `same_fringe` functions work as expected. Show us some of your tests.
+
+               type 'a tree = Leaf of 'a | Node of ('a tree * 'a tree)
+
+               type 'a starred_level = Root | Starring_Left of 'a starred_nonroot | Starring_Right of 'a starred_nonroot
+               and 'a starred_nonroot = { parent : 'a starred_level; sibling: 'a tree };;
+
+               type 'a zipper = { level : 'a starred_level; filler: 'a tree };;
+
+               let rec move_botleft (z : 'a zipper) : 'a zipper =
+                       (* returns z if the targetted node in z has no children *)
+                       (* else returns move_botleft (zipper which results from moving down from z to the leftmost child) *)
+                       _____
+                       (* YOU SUPPLY THE DEFINITION *)
+
+
+               let rec move_right_or_up (z : 'a zipper) : 'a zipper option =
+                       (* if it's possible to move right in z, returns Some (the result of doing so) *)
+                       (* else if it's not possible to move any further up in z, returns None *)
+                       (* else returns move_right_or_up (result of moving up in z) *)
+                       _____
+                       (* YOU SUPPLY THE DEFINITION *)
+
+
+               let new_zipper (t : 'a tree) : 'a zipper =
+                       {level = Root; filler = t}
+                       ;;
+
+       &nbsp;
+
+               let make_fringe_enumerator (t: 'a tree) =
+                       (* create a zipper targetting the botleft of t *)
+                       let zbotleft = move_botleft (new_zipper t)
+                       (* create a refcell initially pointing to zbotleft *)
+                       in let zcell = ref (Some zbotleft)
+                       (* construct the next_leaf function *)
+                       in let next_leaf () : 'a option =
+                               match !zcell with
+                               | Some z -> (
+                                       (* extract label of currently-targetted leaf *)
+                                       let Leaf current = z.filler
+                                       (* update zcell to point to next leaf, if there is one *)
+                                       in let () = zcell := match move_right_or_up z with
+                                               | None -> None
+                                               | Some z' -> Some (move_botleft z')
+                                       (* return saved label *)
+                                       in Some current
+                                   )
+                               | None -> (* we've finished enumerating the fringe *)
+                                       None
+                       (* return the next_leaf function *)
+                       in next_leaf
+                       ;;
+
+               let same_fringe (t1 : 'a tree) (t2 : 'a tree) : bool =
+                       let next1 = make_fringe_enumerator t1
+                       in let next2 = make_fringe_enumerator t2
+                       in let rec loop () : bool =
+                               match next1 (), next2 () with
+                               | Some a, Some b when a = b -> loop ()
+                               | None, None -> true
+                               | _ -> false
+                       in loop ()
+                       ;;
+
+
+2.     Here's another implementation of the same-fringe function, in Scheme. It's taken from <http://c2.com/cgi/wiki?SameFringeProblem>. It uses thunks to delay the evaluation of code that computes the tail of a list of a tree's fringe. It also involves passing "the rest of the enumeration of the fringe" as a thunk argument (`tail-thunk` below). Your assignment is to fill in the blanks in the code, **and also to supply comments to the code,** to explain what every significant piece is doing. Don't forget to supply the comments, this is an important part of the assignment.
+
+       This code uses Scheme's `cond` construct. That works like this;
+
+               (cond
+                       ((test1 argument argument) result1)
+                       ((test2 argument argument) result2)
+                       ((test3 argument argument) result3)
+                       (else result4))
+
+       is equivalent to:
+
+               (if (test1 argument argument)
+                       ; then
+                       result1
+                       ; else
+                       (if (test2 argument argument)
+                               ; then
+                               result2
+                               ; else
+                               (if (test3 argument argument)
+                                       ; then
+                                       result3
+                                       ; else
+                                       result4)))
+
+       Some other Scheme details:
+
+       *       `#t` is true and `#f` is false
+       *       `(lambda () ...)` constructs a thunk
+       *       there is no difference in meaning between `[...]` and `(...)`; we just sometimes use the square brackets for clarity
+       *       `'(1 . 2)` and `(cons 1 2)` are pairs (the same pair)
+       *       `(list)` and `'()` both evaluate to the empty list
+       *       `(null? lst)` tests whether `lst` is the empty list
+       *       non-empty lists are implemented as pairs whose second member is a list
+       *       `'()` `'(1)` `'(1 2)` `'(1 2 3)` are all lists
+       *       `(list)` `(list 1)` `(list 1 2)` `(list 1 2 3)` are the same lists as the preceding
+       *       `'(1 2 3)` and `(cons 1 '(2 3))` are both pairs and lists (the same list)
+       *       `(pair? lst)` tests whether `lst` is a pair; if `lst` is a non-empty list, it will also pass this test; if `lst` fails this test, it may be because `lst` is the empty list, or because it's not a list or pair at all
+       *       `(car lst)` extracts the first member of a pair / head of a list
+       *       `(cdr lst)` extracts the second member of a pair / tail of a list
+
+       Here is the implementation:
+
+               (define (lazy-flatten tree)
+                 (letrec ([helper (lambda (tree tail-thunk)
+                                 (cond
+                                   [(pair? tree)
+                                     (helper (car tree) (lambda () (helper _____ tail-thunk)))]
+                                   [else (cons tree tail-thunk)]))])
+                   (helper tree (lambda () _____))))
+               
+               (define (stream-equal? stream1 stream2)
+                 (cond
+                   [(and (null? stream1) (null? stream2)) _____]
+                   [(and (pair? stream1) (pair? stream2))
+                    (and (equal? (car stream1) (car stream2))
+                         _____)]
+                   [else #f]))
+               
+               (define (same-fringe? tree1 tree2)
+                 (stream-equal? (lazy-flatten tree1) (lazy-flatten tree2)))
+               
+               (define tree1 '(((1 . 2) . (3 . 4)) . (5 . 6)))
+               (define tree2 '(1 . (((2 . 3) . (4 . 5)) . 6)))
+               
+               (same-fringe? tree1 tree2)
+
+
diff --git a/exercises/_assignment13.mdwn b/exercises/_assignment13.mdwn
new file mode 100644 (file)
index 0000000..3ec13ae
--- /dev/null
@@ -0,0 +1,181 @@
+Using continuations to solve the same-fringe problem
+----------------------------------------------------
+
+The problem
+-----------
+
+The problem, recall, is to take two trees and decide whether they have
+the same leaves in the same order.
+
+<pre>
+ ta            tb          tc
+ .             .           .
+_|__          _|__        _|__
+|  |          |  |        |  |
+1  .          .  3        1  .
+  _|__       _|__           _|__
+  |  |       |  |           |  |
+  2  3       1  2           3  2
+
+let ta = Node (Leaf 1, Node (Leaf 2, Leaf 3));;
+let tb = Node (Node (Leaf 1, Leaf 2), Leaf 3);;
+let tc = Node (Leaf 1, Node (Leaf 3, Leaf 2));;
+</pre>
+
+So `ta` and `tb` are different trees that have the same fringe, but
+`ta` and `tc` are not.
+
+We've seen two solutions to the same fringe problem so far.  
+The simplest solution is to map each tree to a list of its leaves,
+then compare the lists.  But because we will have computed the entire
+fringe before starting the comparison, if the fringes differ in an
+early position, we've wasted our time examining the rest of the trees.
+
+The second solution was to use tree zippers and mutable state to
+simulate coroutines (see [[coroutines and aborts]], and
+[[assignment8]]).  In that solution, we pulled the zipper on the first
+tree until we found the next leaf, then stored the zipper structure in
+a mutable variable while we turned our attention to the other tree.
+This solution is efficient: the zipper doesn't visit any leaves beyond
+the first mismatch.
+
+Since zippers are just continuations reified, we expect that the
+solution in terms of zippers can be reworked using continuations, and
+this is indeed the case.  Your assignment is to show how.
+
+The first step is to review your answer to [[assignment8]], and make
+sure you understand what is going on.
+
+
+Two strategies for solving the problem
+--------------------------------------
+
+
+1.  Review the list-zipper/list-continuation example given in
+    class in [[from list zippers to continuations]]; then
+    figure out how to re-functionalize the zippers used in the zipper
+    solution.
+
+2.  Review how the continuation-flavored `tree_monadizer` managed to
+    map a tree to a list of its leaves, in [[manipulating trees with monads]].
+    Spend some time trying to understand exactly what it
+    does: compute the tree-to-list transformation for a tree with two
+    leaves, performing all beta reduction by hand using the
+    definitions for `continuation_bind`, `continuation_unit` and so on.
+    If you take this route, study the description of **streams** (a
+    particular kind of data structure) below.  The goal will be to
+    arrange for the continuation-flavored `tree_monadizer` to transform
+    a tree into a stream instead of into a list.  Once you've done
+    that, completing the same-fringe problem will be easy.
+
+-------------------------------------
+
+Whichever method you choose, here are some goals to consider.
+
+1.  Make sure that your solution gives the right results on the trees
+given above (`ta`, `tb`, and `tc`).
+
+2.  Make sure your function works on trees that contain only a single
+leaf, as well as when the two trees have different numbers of leaves.
+
+3.  Figure out a way to prove that your solution satisfies the main
+requirement of the problem; in particular, that when the trees differ
+in an early position, your code does not waste time visiting the rest
+of the tree.  One way to do this is to add print statements to your
+functions so that every time you visit a leaf (say), a message is
+printed on the output. (In OCaml: `print_int 1` prints an `int`, `print_string "foo"` prints a `string`, `print_newline ()` prints a line break, and `print_endline "foo"` prints a string followed by a line break.) If two trees differ in the middle of their fringe, you should show that your solution prints debugging information for the first half of the fringe, but then stops.
+
+4.  What if you had some reason to believe that the trees you were
+going to compare were more likely to differ in the rightmost region?
+What would you have to change in your solution so that it worked from
+right to left?
+
+Streams
+-------
+
+A stream is like a list in that it wraps a series of elements of a single type.
+It differs from a list in that the tail of the series is left uncomputed
+until needed.  We will turn the stream on and off by thunking it (see
+class notes for [[week6]] on thunks, as well as [[assignment5]]).
+
+    type 'a stream = End | Next of 'a * (unit -> 'a stream);;
+
+There is a special stream called `End` that represents a stream that
+contains no (more) elements, analogous to the empty list `[]`.
+Streams that are not empty contain a first object, paired with a
+thunked stream representing the rest of the series.  In order to get
+access to the next element in the stream, we must *force* the thunk by
+applying it to the unit.  Watch the behavior of this stream in detail.
+This stream delivers the natural numbers, in order: 1, 2, 3, ...
+
+<pre>
+# let rec make_int_stream i = Next (i, fun () -> make_int_stream (i + 1));;
+val make_int_stream : int -> int stream = [fun]
+
+# let int_stream = make_int_stream 1;;
+val int_stream : int stream = Next (1, [fun])         (* First element: 1 *)
+
+# let tail = match int_stream with Next (i, rest) -> rest;;      
+val tail : unit -> int stream = [fun]                 (* Tail: a thunk *)
+
+(* Force the thunk to compute the second element *)
+# tail ();;
+- : int stream = Next (2, [fun])                      (* Second element: 2 *)
+
+# match tail () with Next (_, rest) -> rest ();;
+- : int stream = Next (3, [fun])                      (* Third element: 3 *)
+</pre>
+
+You can think of `int_stream` as a functional object that provides
+access to an infinite sequence of integers, one at a time.  It's as if
+we had written `[1;2;...]` where `...` meant "continue for as long as
+some other process needs new integers".
+
+
+<!--
+With streams in hand, we need only rewrite our continuation tree
+monadizer so that instead of mapping trees to lists, it maps them to 
+streams.  Instead of 
+
+       # tree_monadize (fun a k -> a :: k a) t1 (fun t -> []);;
+       - : int list = [2; 3; 5; 7; 11]
+
+as above, we have 
+
+        # tree_monadize (fun i k -> Next (i, fun () -> k ())) t1 (fun _ -> End);;
+        - : int stream = Next (2, <fun>)
+
+We can see the first element in the stream, the first leaf (namely,
+2), but in order to see the next, we'll have to force a thunk.
+
+Then to complete the same-fringe function, we simply convert both
+trees into leaf-streams, then compare the streams element by element.
+The code is entirely routine, but for the sake of completeness, here it is:
+
+       let rec compare_streams stream1 stream2 =
+               match stream1, stream2 with 
+               | End, End -> true (* Done!  Fringes match. *)
+               | Next (next1, rest1), Next (next2, rest2) when next1 = next2 -> compare_streams (rest1 ()) (rest2 ())
+               | _ -> false;;
+
+       let same_fringe t1 t2 =
+         let stream1 = tree_monadize (fun i k -> Next (i, fun () -> k ())) t1 (fun _ -> End) in 
+         let stream2 = tree_monadize (fun i k -> Next (i, fun () -> k ())) t2 (fun _ -> End) in 
+         compare_streams stream1 stream2;;
+
+Notice the forcing of the thunks in the recursive call to
+`compare_streams`.  So indeed:
+
+       # same_fringe ta tb;;
+       - : bool = true
+       # same_fringe ta tc;;
+       - : bool = false
+
+Now, you might think that this implementation is a bit silly, since in
+order to convert the trees to leaf streams, our `tree_monadizer`
+function has to visit every node in the tree, so we'd have to traverse
+the entire tree at some point.  But you'd be wrong: part of what gets
+suspended in the thunking of the stream is the computation of the rest
+of the monadized tree.
+
+-->
diff --git a/exercises/_assignment14.mdwn b/exercises/_assignment14.mdwn
new file mode 100644 (file)
index 0000000..ba4df37
--- /dev/null
@@ -0,0 +1,179 @@
+***Non-required but strongly suggested work***: Here are some
+additional homework problems that will consolidate your understanding
+of what we've covered in the last weeks of the seminar. Those who are
+taking the class for credit: since we're so late to post these, and
+they add up to a substantial chunk of thinking, we won't officially
+require you to do them, since we don't want to get into a bureaucratic
+bind if you've planned your next month in a way that would not permit
+you to get the work done.  But ***we strongly encourage*** you to work on
+the problem set: solving these problems will produce a qualitatively
+deeper understanding of continuations.  If you plan to do some or all
+of these problems, and would like us to take them into account in our
+evaluation of your work for the course, please let us know when to
+expect to see them.  (Up to the start of next term, which begins on 24
+January 2011, would be viable.)
+
+Of course, if you need help or want us to review your efforts, we'll be glad to discuss with you at any later point as well.
+
+
+1.     This problem is taken from _The Craft of Functional Programming_ by Simon Thompson, Addison-Wesley 1999 <http://www.cs.kent.ac.uk/people/staff/sjt/>:
+
+       >       Given an arbitrary tree, transform it to a
+       >       tree of integers in which the original elements are replaced by
+       >       natural numbers, starting from 0.  The same element has to be
+       >       replaced by the same number at every occurrence, and when we meet
+       >       an as-yet-unvisited element we have to find a "new" number to match
+       >       it with.
+
+
+       As Ken Shan points out, this is an instance of the algorithm
+       for converting name/year citations (like 'see Montague 1970')
+       to numerals corresponding to their position in the
+       bibliography ('see [24]').  Except that bibliographic numerals
+       don't start with zero.
+
+       Give some thought to efficiency: there are straightforward
+       solutions that involve traversing the tree once (in order to,
+       say, construct a suitable mapping from leafs to ints), then
+       traversing it again to do the conversion.  Can you find a
+       solution that traverses the tree exactly once, replacing each
+       leaf as soon as you see it?
+
+       You can assume that the tree is binary, leaf-labeled (no
+       labels on the internal nodes), and that the leafs are, say,
+       chars.
+
+       Here is [a hint](/hints/assignment_10_hint_1).
+
+       Consider a variation in which you must replace each leaf with
+       its number of occurrences in the tree.  Is there any way to do
+       that with a single traversal? (Here is [a hint](/hints/assignment_10_hint_2).)
+
+
+
+2.     Armed with your solution to problem 1, try this: you have as input a leaf-labeled, binary tree whose labels are strings. You also have as input an interpretation function from strings to meanings. Let the meanings of your strings be primitive elements, for instance:
+
+               type meaning = John | Bill | Sally | Zachariah | Swam | Likes | ...
+
+       If you want to get fancy and have different strings be interpreted to meanings of different types, go ahead. But that won't be essential to this problem. What is essential is that sometimes different strings might map onto the same meaning. For instance, both `"John"` and `"Hannes"` might map to `John`.
+
+       Your task is to return a tree with the same structure as the original tree, but with all string labels replaced with a pair of a meaning and an int. The meaning should be the meaning your interpretation function assigns to the string. Two leaves that get the same meaning should get the same int as well iff the leaves originally were labelled with the same string. So if `"John"` is replaced with `(John, 1)`, then `"Hannes"` should be replaced with `(John, j)` where `j` is an `int` other than `1`. We don't care whether you ever use the same `int`s for leafs with different associated meanings.
+
+       If you solve this, congratulations! You're most of the way to implementing a hyper-evaluative semantics, of the sort Jim discussed around Week 10.
+
+3.     Our notes on [[monad transformers]] give you most of the pieces you need to implement a StateT monad transformer. The only crucial piece that's missing is a definition for StateT's `elevate` function. Here are the earlier pieces repeated, together with that missing piece:
+
+               type 'a stateT(M) =
+                 store -> ('a * store) M;;
+               
+               let unit (a : 'a) : 'a stateT(M) =
+                 fun s -> M.unit (a, s);;
+                 (* can in general be defined as `fun a -> elevate (M.unit a)` *)
+               
+               let bind (u : 'a stateT(M)) (f : 'a -> 'b stateT(M)) : 'b stateT(M) =
+                 fun s -> M.bind (u s) (fun (a, s') -> f a s');;
+               
+               let elevate (m : 'a M) : 'a stateT(M) =
+                 fun s -> M.bind w (fun a -> M.unit (a, s));;
+
+       That won't compile in OCaml because we use the `M`s in a way that's intuitive but unrecognized by OCaml. What OCaml will recognize is more complex. Don't worry; you won't need to code a general implementation of StateT.
+
+       What we do want you to do is to implement StateT(List). That is, plug in the implementations of the List monad's type, unit, and bind into the preceding definitions. That will be a monad, consisting of an inner List monad with StateT packaging around it. Choose sensible names for the type, and unit, bind, and elevate functions of your StateT(List) monad.
+
+       You may want to write some operations for your List monad, such as:
+
+               either (u : 'a list) (v : 'a list) : 'a list
+               (* appends list v to list u *)
+               
+               foreach (u : 'a list) (v : 'a list) : 'a list
+               (* returns a list of lists, each member of which consists of u followed
+                 by a single member of v; there is one for each member of v *)
+
+       and so on. These are just suggestions; you decide which List operations you'll need. For each of these, use your StateT(List)'s `elevate` function to convert them into operations in your combined, State-around-List monad.
+
+       Now, go back to the GS&V assignment from [[assignment7]]. Does the monad you've now crafted enable you to code your implementation of that semantics more elegantly? You can begin by using a composite store of the same sort we used in the hints: a pair of an assignment function `r` and some `h` that associates pegs with entities.
+
+       Are the pegs and the `h` really essential to your solution? Or could you do everything with a store consisting of a single mapping from variables to entities? (You'd still be working with a State monad, but without the pegs.) Explain why or why not.
+
+4.     The next two exercises were taken from _The Little Schemer_ Chapter 8.
+
+       Suppose `lst` is a list of Scheme symbols (`'symbols 'are 'things 'written 'like 'this`; a list of them is `'(written like this)`). And suppose that the behavior of `(remove 'sym lst)` is to remove every occurrence of `'sym` from `lst`.
+
+       Now we define a function `remove-co` which has the following behavior. It accepts as arguments a symbol, a list, and a handler `k` (I wonder why we named it that). `remove-co` calls `k` with two arguments: first, a list of all the symbols in `lst` that aren't equal to `'sym`, and second, a list of all the symbols in `lst` that are equal to `'sym` (the handler might want to, for example, see what the length of the latter list is).
+
+       Here is a partial implementation. You should fill in the blanks. If you get stuck, you can consult the walkthough in _The Little Schemer_, or talk to us.
+
+               (define remove-co
+                 (lambda (a lst k)
+                   (cond
+                     ((null? lst)
+                      (k ___  ___))
+                     ((eq? (car lst) a)
+                      (remove-co a (cdr lst) (lambda (left right) ________)))
+                     (else
+                      (remove-co a (cdr lst) (lambda (left right) ________))))))
+
+       What would be a helper function you could supply as a `k` that would report `#t` iff the original `lst` contained more instances of some symbol than non-instances?
+
+       <!--
+               (define remove-co
+                 (lambda (a lst k)
+                   (cond
+                     ((null? lst)
+                      (k '() '()))
+                     ((eq? (car lst) a)
+                      (remove-co a (cdr lst) (lambda (left right) (k left (cons (car lst) right)))))
+                     (else
+                      (remove-co a (cdr lst) (lambda (left right) (k (cons (car lst) left) right)))))))
+       -->
+
+5.     Now we define a function `insert-co` which has the following behavior. It accepts as arguments three symbols, a list, and a handler. The first symbol is inserted before (to the left of) any occurrences in the list of the second symbol, and after (to the right of) any occurrences of the third symbol. The handler is then called with three arguments: the new list (with the insertions made), the number of "to-the-left" insertions that were made, and the number of "to-the-right" insertions that were made.
+
+       Here is a partial implementation. You should fill in the blanks. If you get stuck, you can consult the walkthough in _The Little Schemer_, or talk to us.
+
+               (define insert-co
+                 (lambda (new before after lst k)
+                   (cond
+                     ((null? lst)
+                      (k ___  ___ ___))
+                     ((eq? (car lst) before)
+                      (insert-co new before after (cdr lst) (lambda (new-lst lefts rights) ________)))
+                     ((eq? (car lst) after)
+                      (insert-co new before after (cdr lst) (lambda (new-lst lefts rights) ________)))
+                     (else
+                      (insert-co new before after (cdr lst) (lambda (new-lst lefts rights) ________))))))
+
+       <!--
+               (define insert-co
+                 (lambda (new before after lst k)
+                   (cond
+                     ((null? lst)
+                      (k '() 0 0))
+                     ((eq? (car lst) before)
+                      (insert-co new before after (cdr lst) (lambda (new-lst lefts rights) (k (cons new (cons before new-lst)) (succ lefts) rights))))
+                     ((eq? (car lst) after)
+                      (insert-co new before after (cdr lst) (lambda (new-lst lefts rights) (k (cons after (cons new new-lst)) lefts (succ rights)))))
+                     (else
+                      (insert-co new before after (cdr lst) (lambda (new-lst lefts rights) (k (cons (car lst) new-lst) lefts rights)))))))
+       -->
+
+
+6.     Go back to the "abSd" problem we presented in [[From List Zippers to Continuations]]. Consider the "tc" solution which uses
+explicitly passed continuations. Try to reimplement this using reset
+and shift instead of having an explicit `k` argument. This will likely
+be challenging but rewarding. The notes on [[CPS and Continuation Operators]], especially the examples at the end, should be helpful. We
+are of course also glad to help you out.
+
+    Consider adding a special symbol `'#'` (pronounced 'prompt') to the
+    mini-language such that
+
+    `"ab#cdSef"` ~~> `"abcdcdef"`
+
+    That is, the rule for `'S'` is to copy the preceding string, but
+    only up to the closest enclosing `'#'` symbol.
+
+7.     Can you reimplement your solution to [[assignment9]] using reset and shift?
+
+These are challenging questions, don't get frustrated if you get stuck, seek help.
+
+
diff --git a/topics/_coroutines_and_aborts.mdwn b/topics/_coroutines_and_aborts.mdwn
new file mode 100644 (file)
index 0000000..4b2b5da
--- /dev/null
@@ -0,0 +1,613 @@
+[[!toc]]
+
+##Same-fringe using a zipper-based coroutine##
+
+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):
+
+           .                .
+          / \              / \
+         .   3            1   .
+        / \                  / \
+       1   2                2   3
+
+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.
+
+
+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), move 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:
+
+           .                .
+          / \              / \
+         .   3            1   .
+        / \                  / \
+       1   2                2   3
+
+you won't move upwards at the same steps. Keep comparing "the next leaves" until they are different, or you exhaust the leaves of only one of the trees (then again the trees have different fringes), or you exhaust the leaves of both trees at the same time, without having found leaves with different labels. In this last case, the trees have the same fringe.
+
+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.
+
+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.
+
+First, we define a type for leaf-labeled, binary trees:
+
+       type 'a tree = Leaf of 'a | Node of ('a tree * 'a tree)
+
+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:
+
+       # type blah = Blah of (int * int * (char -> bool));;
+
+and then having to remember which element in the triple was which:
+
+       # let b1 = Blah (1, (fun c -> c = 'M'), 2);;
+       Error: This expression has type int * (char -> bool) * int
+       but an expression was expected of type int * int * (char -> bool)
+       # (* damnit *)
+       # let b1 = Blah (1, 2, (fun c -> c = 'M'));;
+       val b1 : blah = Blah (1, 2, <fun>)
+
+records let you attach descriptive labels to the components of the tuple:
+
+       # type blah_record = { height : int; weight : int; char_tester : char -> bool };;
+       # let b2 = { height = 1; weight = 2; char_tester = (fun c -> c = 'M') };;
+       val b2 : blah_record = {height = 1; weight = 2; char_tester = <fun>}
+       # let b3 = { height = 1; char_tester = (fun c -> c = 'K'); weight = 3 };; (* also works *)
+       val b3 : blah_record = {height = 1; weight = 3; char_tester = <fun>}
+
+These were the strategies to extract the components of an unlabeled tuple:
+
+       let h = fst some_pair;; (* accessor functions fst and snd are only predefined for pairs *)
+
+       let (h, w, test) = b1;; (* works for arbitrary tuples *)
+
+       match b1 with
+       | (h, w, test) -> ...;; (* same as preceding *)
+
+Here is how you can extract the components of a labeled record:
+
+       let h = b2.height;; (* handy! *)
+
+       let {height = h; weight = w; char_tester = test} = b2
+       in (* go on to use h, w, and test ... *)
+
+       match test with
+       | {height = h; weight = w; char_tester = test} ->
+         (* same as preceding *)
+
+Anyway, using record types, we might define the tree zipper interface like so:
+
+       type 'a starred_level = Root | Starring_Left of 'a starred_nonroot | Starring_Right of 'a starred_nonroot
+       and 'a starred_nonroot = { parent : 'a starred_level; sibling: 'a tree };;
+
+       type 'a zipper = { level : 'a starred_level; filler: 'a tree };;
+
+       let rec move_botleft (z : 'a zipper) : 'a zipper =
+           (* returns z if the targetted node in z has no children *)
+           (* else returns move_botleft (zipper which results from moving down and left in z) *)
+
+<!--
+           let {level; filler} = z
+           in match filler with
+           | Leaf _ -> z
+           | Node(left, right) ->
+               let zdown = {level = Starring_Left {parent = level; sibling = right}; filler = left}
+               in move_botleft zdown
+           ;;
+-->
+
+       let rec move_right_or_up (z : 'a zipper) : 'a zipper option =
+           (* if it's possible to move right in z, returns Some (the result of doing so) *)
+           (* else if it's not possible to move any further up in z, returns None *)
+           (* else returns move_right_or_up (result of moving up in z) *)
+
+<!--
+           let {level; filler} = z
+           in match level with
+           | Starring_Left {parent; sibling = right} -> Some {level = Starring_Right {parent; sibling = filler}; filler = right}
+           | Root -> None
+           | Starring_Right {parent; sibling = left} ->
+               let z' = {level = parent; filler = Node(left, filler)}
+               in move_right_or_up z'
+           ;;
+-->
+
+The following function takes an `'a tree` and returns an `'a zipper` focused on its root:
+
+       let new_zipper (t : 'a tree) : 'a zipper =
+           {level = Root; filler = t}
+           ;;
+
+Finally, we can use a mutable reference cell to define a function that enumerates a tree's fringe until it's exhausted:
+
+       let make_fringe_enumerator (t: 'a tree) =
+           (* create a zipper targetting the botleft of t *)
+           let zbotleft = move_botleft (new_zipper t)
+           (* create a refcell initially pointing to zbotleft *)
+           in let zcell = ref (Some zbotleft)
+           (* construct the next_leaf function *)
+           in let next_leaf () : 'a option =
+               match !zcell with
+               | Some z -> (
+                   (* extract label of currently-targetted leaf *)
+                   let Leaf current = z.filler
+                   (* update zcell to point to next leaf, if there is one *)
+                   in let () = zcell := match move_right_or_up z with
+                       | None -> None
+                       | Some z' -> Some (move_botleft z')
+                   (* return saved label *)
+                   in Some current
+               | None -> (* we've finished enumerating the fringe *)
+                   None
+               )
+           (* return the next_leaf function *)
+           in next_leaf
+           ;;
+
+Here's an example of `make_fringe_enumerator` in action:
+
+       # let tree1 = Leaf 1;;
+       val tree1 : int tree = Leaf 1
+       # let next1 = make_fringe_enumerator tree1;;
+       val next1 : unit -> int option = <fun>
+       # next1 ();;
+       - : int option = Some 1
+       # next1 ();;
+       - : int option = None
+       # next1 ();;
+       - : int option = None
+       # let tree2 = Node (Node (Leaf 1, Leaf 2), Leaf 3);;
+       val tree2 : int tree = Node (Node (Leaf 1, Leaf 2), Leaf 3)
+       # let next2 = make_fringe_enumerator tree2;;
+       val next2 : unit -> int option = <fun>
+       # next2 ();;
+       - : int option = Some 1
+       # next2 ();;
+       - : int option = Some 2
+       # next2 ();;
+       - : int option = Some 3
+       # next2 ();;
+       - : int option = None
+       # next2 ();;
+       - : int option = None
+
+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`.
+
+Using these fringe enumerators, we can write our `same_fringe` function like this:
+
+       let same_fringe (t1 : 'a tree) (t2 : 'a tree) : bool =
+           let next1 = make_fringe_enumerator t1
+           in let next2 = make_fringe_enumerator t2
+           in let rec loop () : bool =
+               match next1 (), next2 () with
+               | Some a, Some b when a = b -> loop ()
+               | None, None -> true
+               | _ -> false
+           in loop ()
+           ;;
+
+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.
+
+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*.
+
+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:
+
+       main program        next1 thread        next2 thread
+       ------------        ------------        ------------
+       start next1
+       (paused)            starting
+       (paused)            calculate first leaf
+       (paused)            <--- return it
+       start next2         (paused)            starting
+       (paused)            (paused)            calculate first leaf
+       (paused)            (paused)            <-- return it
+       compare leaves      (paused)            (paused)
+       call loop again     (paused)            (paused)
+       call next1 again    (paused)            (paused)
+       (paused)            calculate next leaf (paused)
+       (paused)            <-- return it       (paused)
+       ... and so on ...
+
+If you want to read more about these kinds of threads, here are some links:
+
+<!-- * [[!wikipedia Computer_multitasking]]
+*      [[!wikipedia Thread_(computer_science)]] -->
+
+*      [[!wikipedia Coroutine]]
+*      [[!wikipedia Iterator]]
+*      [[!wikipedia Generator_(computer_science)]]
+*      [[!wikipedia Fiber_(computer_science)]]
+<!-- * [[!wikipedia Green_threads]]
+*      [[!wikipedia Protothreads]] -->
+
+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.
+
+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:
+
+       > function fringe_enumerator (tree)
+           if tree.leaf then
+               coroutine.yield (tree.leaf)
+           else
+               fringe_enumerator (tree.left)
+               fringe_enumerator (tree.right)
+           end
+       end
+       
+       > function same_fringe (tree1, tree2)
+           local next1 = coroutine.wrap (fringe_enumerator)
+           local next2 = coroutine.wrap (fringe_enumerator)
+           local function loop (leaf1, leaf2)
+               if leaf1 or leaf2 then
+                   return leaf1 == leaf2 and loop( next1(), next2() )
+               elseif not leaf1 and not leaf2 then
+                   return true
+               else
+                   return false
+               end
+           end
+           return loop (next1(tree1), next2(tree2))
+       end
+       
+       > return same_fringe ( {leaf=1}, {leaf=2} )
+       false
+       
+       > return same_fringe ( {leaf=1}, {leaf=1} )
+       true
+       
+       > return same_fringe ( {left = {leaf=1}, right = {left = {leaf=2}, right = {leaf=3}}},
+           {left = {left = {leaf=1}, right = {leaf=2}}, right = {leaf=3}} )
+       true
+
+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 or dedicated native syntax to rely on.
+
+
+##Exceptions and Aborts##
+
+To get a better understanding of how that execution pattern works, we'll add yet a second execution pattern to our plate, and then think about what they have in common.
+
+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:
+
+       # let lst = [1; 2] in
+         "a" :: lst;;
+       Error: This expression has type int list
+              but an expression was expected of type string list
+
+But you may also have encountered other kinds of error, that arise while your program is running. For example:
+
+       # 1/0;;
+       Exception: Division_by_zero.
+       # List.nth [1;2] 10;;
+       Exception: Failure "nth".
+
+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`:
+
+       let nth l n =
+         if n < 0 then invalid_arg "List.nth" else
+         let rec nth_aux l n =
+           match l with
+           | [] -> failwith "nth"
+           | a::l -> if n = 0 then a else nth_aux l (n-1)
+         in nth_aux l n
+
+Notice the two clauses `invalid_arg "List.nth"` and `failwith "nth"`. These are two helper functions which are shorthand for:
+
+       raise (Invalid_argument "List.nth");;
+       raise (Failure "nth");;
+
+where `Invalid_argument "List.nth"` is a value of type `exn`, and so too `Failure "nth"`. When you have some value `bad` of type `exn` and evaluate the expression:
+
+       raise bad
+
+the effect is for the program to immediately stop without evaluating any further code:
+
+       # let xcell = ref 0;;
+       val xcell : int ref = {contents = 0}
+       # let bad = Failure "test"
+         in let _ = raise bad
+         in xcell := 1;;
+       Exception: Failure "test".
+       # !xcell;;
+       - : int = 0
+
+Notice that the line `xcell := 1` was never evaluated, so the contents of `xcell` are still `0`.
+
+I said when you evaluate the expression:
+
+       raise bad
+
+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:
+
+       # let foo x =
+           try
+               (if x = 1 then 10
+               else if x = 2 then raise (Failure "two")
+               else raise (Failure "three")
+               ) + 100
+           with Failure "two" -> 20
+           ;;
+       val foo : int -> int = <fun>
+       # foo 1;;
+       - : int = 110
+       # foo 2;;
+       - : int = 20
+       # foo 3;;
+       Exception: Failure "three".
+
+Notice what happens here. If we call `foo 1`, then the code between `try` and `with` evaluates to `110`, 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.
+
+So what I should have said is that when you evaluate the expression:
+
+       raise bad
+
+*and that exception is never caught*, then the effect is for the program to immediately stop.
+
+Trivia: what's the type of the `raise (Failure "two")` in:
+
+       if x = 1 then 10
+       else raise (Failure "two")
+
+What's its type in:
+
+       if x = 1 then "ten"
+       else raise (Failure "two")
+
+So now what do you expect the type of this to be:
+
+       fun x -> raise (Failure "two")
+
+How about this:
+
+       (fun x -> raise (Failure "two") : 'a -> 'a)
+
+Remind you of anything we discussed earlier? /Trivia.
+
+Of course, it's possible to handle errors in other ways too. There's no reason why the implementation of `List.nth` *had* to raise an exception. 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 the exception-raising pattern now.
+
+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:
+
+       # try
+           try
+               (raise (Failure "blah")
+               ) + 100
+           with Failure "fooey" -> 10
+         with Failure "blah" -> 20;;
+       - : int = 20
+
+The matching `try ... with ...` block need not *lexically surround* the site where the error was raised:
+
+       # let foo b x =
+           try
+               (b x
+               ) + 100
+           with Failure "blah" -> 20
+       in let bar x =
+           raise (Failure "blah")
+       in foo bar 0;;
+       - : int = 20
+
+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 that function, and we find a matching `try ... with ...` block in `foo`. This catches the error and so then the `try ... with ...` block in `foo` (the code that called `bar` in the first place) will evaluate to `20`.
+
+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:
+
+       # let foo x =
+           try begin
+               (if x = 1 then 10
+               else abort 20
+               ) + 100
+           end
+           ;;
+
+then if we called `foo 1`, we'd get the result `110`. If we called `foo 2`, on the other hand, we'd get `20` (note, not `120`). 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.
+
+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`. In Lua, the preceding example would be written:
+
+       > function foo(x)
+           local value
+           if (x == 1) then
+               value = 10
+           else
+               return 20         -- abort early
+           end
+           return value + 100    -- in Lua, a function's normal value
+                                 -- must always also be explicitly returned
+       end
+       
+       > return foo(1)
+       110
+       
+       > return foo(2)
+       20
+
+Okay, so that's our second execution pattern.
+
+##What do these have in common?##
+
+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 data structure 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.
+
+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:
+
+       let foo x =
+           try begin
+               (if x = 1 then 10
+               else abort 20
+               ) + 100
+           end
+       in (foo 2) + 1;;
+
+we can imagine a box:
+
+       let foo x =
+       +---try begin----------------+
+       |       (if x = 1 then 10    |
+       |       else abort 20        |
+       |       ) + 100              |
+       +---end----------------------+
+       in (foo 2) + 1000;;
+
+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.
+
+
+What would a "snapshot of the code outside the box" look like? Well, let's rearrange the code somewhat. It should be equivalent to this:
+
+       let x = 2
+       in let foo_result =
+       +---try begin----------------+
+       |       (if x = 1 then 10    |
+       |       else abort 20        |
+       |       ) + 100              |
+       +---end----------------------+
+       in (foo_result) + 1000;;
+
+and we can think of the code starting with `let foo_result = ...` as a function, with the box being its parameter, like this:
+
+       fun box ->
+           let foo_result = box
+           in (foo_result) + 1000
+
+That function is our "snapshot". Normally what happens is that code *inside* the box delivers up a value, and that value gets supplied as an argument to the snapshot-function just described. That is, our code is essentially working like this:
+
+       let x = 2
+       in let snapshot = fun box ->
+           let foo_result = box
+           in (foo_result) + 1000
+       in let value =
+           (if x = 1 then 10
+           else ... (* we'll come back to this part *)
+           ) + 100
+       in shapshot value;;
+
+But now how should the `abort 20` part, that we ellided here, work? What should happen when we try to evaluate that?
+
+Well, that's when we use the snapshot code in an unusual way. If we encounter an `abort 20`, we should abandon the code we're currently executing, and instead just supply `20` to the snapshot we saved when we entered the box. That is, something like this:
+
+       let x = 2
+       in let snapshot = fun box ->
+           let foo_result = box
+           in (foo_result) + 1000
+       in let value =
+           (if x = 1 then 10
+           else snapshot 20
+           ) + 100
+       in shapshot value;;
+
+Except that isn't quite right, yet---in this fragment, after the `snapshot 20` code is finished, we'd pick up again inside `let value = (...) + 100 in snapshot value`. That's not what we want. We don't want to pick up again there. We want instead to do this:
+
+       let x = 2
+       in let snapshot = fun box ->
+           let foo_result = box
+           in (foo_result) + 1000
+       in let value =
+           (if x = 1 then 10
+           else snapshot 20 THEN STOP
+           ) + 100
+       in shapshot value;;
+
+We can get that by some further rearranging of the code:
+
+       let x = 2
+       in let snapshot = fun box ->
+           let foo_result = box
+           in (foo_result) + 1000
+       in let continue_normally = fun from_value ->
+           let value = from_value + 100
+           in snapshot value
+       in
+           if x = 1 then continue_normally 10
+           else snapshot 20;;
+
+And this is indeed what is happening, at a fundamental level, when you use an expression like `abort 20`.
+
+<!--
+# #require "delimcc";;
+# open Delimcc;;
+# let reset body = let p = new_prompt () in push_prompt p (body p);;
+# let test_cps x =
+      let snapshot = fun box ->
+          let foo_result = box
+          in (foo_result) + 1000
+      in let continue_normally = fun from_value ->
+          let value = from_value + 100
+          in snapshot value
+      in if x = 1 then continue_normally 10
+      else snapshot 20;;
+
+       let foo x =
+       +===try begin================+
+       |       (if x = 1 then 10    |
+       |       else abort 20        |
+       |       ) + 100              |
+       +===end======================+
+       in (foo 2) + 1000;;
+
+# let test_shift x =
+    let foo x = reset(fun p () ->
+        (shift p (fun k ->
+            if x = 1 then k 10 else 20)
+        ) + 100)
+    in foo z + 1000;;
+
+# test_cps 1;;
+- : int = 1110
+# test_shift 1;;
+- : int = 1110
+# test_cps 2;;
+- : int = 1020
+# test_shift 2;;
+- : int = 1020
+-->
+
+A similar kind of "snapshotting" lets coroutines keep track of where they left off, so that they can start up again at that same place.
+
+##Continuations, finally##
+
+These snapshots are called **continuations** because they represent how the computation will "continue" once some target code (in our example, the code in the box) delivers up a value.
+
+You can think of them as functions that represent "how the rest of the computation proposes to continue." Except that, once we're able to get our hands on those functions, we can do exotic and unwholesome things with them. Like use them to suspend and resume a thread. Or to abort from deep inside a sub-computation: one function might pass the command to abort *it* to a subfunction, so that the subfunction has the power to jump directly to the outside caller. Or a function might *return* its continuation function to the outside caller, giving *the outside caller* the ability to "abort" the function (the function that has already returned its value---so what should happen then?) Or we may call the same continuation function *multiple times* (what should happen then?). All of these weird and wonderful possibilities await us.
+
+The key idea behind working with continuations is that we're *inverting control*. In the fragment above, the code `(if x = 1 then ... else snapshot 20) + 100`---which is written as if it were to supply a value to the outside context that we snapshotted---itself *makes non-trivial use of* that snapshot. So it has to be able to refer to that snapshot; the snapshot has to somehow be available to our inside-the-box code as an *argument* or bound variable. That is: the code that is *written* like it's supplying an argument to the outside context is instead *getting that context as its own argument*. He who is written as value-supplying slave is instead become the outer context's master.
+
+In fact you've already seen this several times this semester---recall how in our implementation of pairs in the untyped lambda-calculus, the handler who wanted to use the pair's components had *in the first place to be supplied to the pair as an argument*. So the exotica from the end of the seminar was already on the scene in some of our earliest steps. Recall also what we did with v2 and v5 lists. Version 5 lists were the ones that let us abort a fold early: 
+go back and re-read the material on "Aborting a Search Through a List" in [[Week4]].
+
+This inversion of control should also remind you of Montague's treatment of determiner phrases in ["The Proper Treatment of Quantification in Ordinary English"](http://www.blackwellpublishing.com/content/BPL_Images/Content_store/Sample_chapter/0631215417%5CPortner.pdf) (PTQ).
+
+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.
+
+Monatague proposed we instead take the subject term 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.
+
+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.
+
+This inversion of who is the argument and who is the function receiving the argument is paradigmatic of working with continuations.
+
+Continuations come in many varieties. There are **undelimited continuations**, expressed in Scheme via `(call/cc (lambda (k) ...))` or the shorthand `(let/cc k ...)`. (`call/cc` is itself shorthand for `call-with-current-continuation`.) These capture "the entire rest of the computation." There are also **delimited continuations**, expressed in Scheme via `(reset ... (shift k ...) ...)` or `(prompt ... (control k ...) ...)` or any of several other operations. There are subtle differences between those that we won't be exploring in the seminar. Ken Shan has done terrific work exploring the relations of these operations to each other.
+
+When working with continuations, it's easiest in the first place to write them out explicitly, the way that we explicitly wrote out the `snapshot` continuation when we transformed this:
+
+       let foo x =
+           try begin
+               (if x = 1 then 10
+               else abort 20
+               ) + 100
+           end
+       in (foo 2) + 1000;;
+
+into this:
+
+       let x = 2
+       in let snapshot = fun box ->
+           let foo_result = box
+           in (foo_result) + 1000
+       in let continue_normally = fun from_value ->
+           let value = from_value + 100
+           in snapshot value
+       in
+           if x = 1 then continue_normally 10
+           else snapshot 20;;
+
+Code written in the latter form is said to be written in **explicit continuation-passing style** or CPS. Later we'll talk about algorithms that mechanically convert an entire program into CPS.
+
+There are also different kinds of "syntactic sugar" we can use to hide the continuation plumbing. Of course we'll be talking about how to manipulate continuations **with a Continuation monad.** We'll also talk about a style of working with continuations where they're **mostly implicit**, but special syntax allows us to distill the implicit continuaton into a first-class value (the `k` in `(let/cc k ...)` and `(shift k ...)`.
+
+Various of the tools we've been introducing over the past weeks are inter-related. We saw coroutines implemented first with zippers; here we've talked in the abstract about their being implemented with continuations. Oleg says that "Zipper can be viewed as a delimited continuation reified as a data structure." Ken expresses the same idea in terms of a zipper being a "defunctionalized" continuation---that is, take something implemented as a function (a continuation) and implement the same thing as an inert data structure (a zipper).
+
+Mutation, delimited continuations, and monads can also be defined in terms of each other in various ways. We find these connections fascinating but the seminar won't be able to explore them very far.
+
+We recommend reading [the Yet Another Haskell Tutorial on Continuation Passing Style](http://en.wikibooks.org/wiki/Haskell/YAHT/Type_basics#Continuation_Passing_Style)---though the target language is Haskell, this discussion is especially close to material we're discussing in the seminar.
+
diff --git a/topics/_cps.mdwn b/topics/_cps.mdwn
new file mode 100644 (file)
index 0000000..d7752f4
--- /dev/null
@@ -0,0 +1,286 @@
+Gaining control over order of evaluation
+----------------------------------------
+
+We know that evaluation order matters.  We're beginning to learn how
+to gain some control over order of evaluation (think of Jim's abort handler).
+We continue to reason about order of evaluation.
+
+A lucid discussion of evaluation order in the
+context of the lambda calculus can be found here:
+[Sestoft: Demonstrating Lambda Calculus Reduction](http://www.itu.dk/~sestoft/papers/mfps2001-sestoft.pdf).
+Sestoft also provides a lovely on-line lambda evaluator:
+[Sestoft: Lambda calculus reduction workbench](http://www.itu.dk/~sestoft/lamreduce/index.html),
+which allows you to select multiple evaluation strategies, 
+and to see reductions happen step by step.
+
+Evaluation order matters
+------------------------
+
+We've seen this many times.  For instance, consider the following
+reductions.  It will be convenient to use the abbreviation `w =
+\x.xx`.  I'll
+indicate which lambda is about to be reduced with a * underneath:
+
+<pre>
+(\x.y)(ww)
+ *
+y
+</pre>
+
+Done!  We have a normal form.  But if we reduce using a different
+strategy, things go wrong:
+
+<pre>
+(\x.y)(ww) =
+(\x.y)((\x.xx)w) =
+        *
+(\x.y)(ww) =
+(\x.y)((\x.xx)w) =
+        *
+(\x.y)(ww) 
+</pre>
+
+Etc.  
+
+As a second reminder of when evaluation order matters, consider using
+`Y = \f.(\h.f(hh))(\h.f(hh))` as a fixed point combinator to define a recursive function:
+
+<pre>
+Y (\f n. blah) =
+(\f.(\h.f(hh))(\h.f(hh))) (\f n. blah) 
+     *
+(\f.f((\h.f(hh))(\h.f(hh)))) (\f n. blah) 
+       *
+(\f.f(f((\h.f(hh))(\h.f(hh))))) (\f n. blah) 
+         *
+(\f.f(f(f((\h.f(hh))(\h.f(hh)))))) (\f n. blah) 
+</pre>
+
+And we never get the recursion off the ground.
+
+
+Using a Continuation Passing Style transform to control order of evaluation
+---------------------------------------------------------------------------
+
+We'll present a technique for controlling evaluation order by transforming a lambda term
+using a Continuation Passing Style transform (CPS), then we'll explore
+what the CPS is doing, and how.
+
+In order for the CPS to work, we have to adopt a new restriction on
+beta reduction: beta reduction does not occur underneath a lambda.
+That is, `(\x.y)z` reduces to `z`, but `\u.(\x.y)z` does not reduce to
+`\u.z`, because the `\u` protects the redex in the body from
+reduction.  (In this context, a "redex" is a part of a term that matches
+the pattern `...((\xM)N)...`, i.e., something that can potentially be
+the target of beta reduction.)
+
+Start with a simple form that has two different reduction paths:
+
+reducing the leftmost lambda first: `(\x.y)((\x.z)u)  ~~> y`
+
+reducing the rightmost lambda first: `(\x.y)((\x.z)u)  ~~> (\x.y)z ~~> y`
+
+After using the following call-by-name CPS transform---and assuming
+that we never evaluate redexes protected by a lambda---only the first
+reduction path will be available: we will have gained control over the
+order in which beta reductions are allowed to be performed.
+
+Here's the CPS transform defined:
+
+    [x] = x
+    [\xM] = \k.k(\x[M])
+    [MN] = \k.[M](\m.m[N]k)
+
+Here's the result of applying the transform to our simple example:
+
+    [(\x.y)((\x.z)u)] =
+    \k.[\x.y](\m.m[(\x.z)u]k) =
+    \k.(\k.k(\x.[y]))(\m.m(\k.[\x.z](\m.m[u]k))k) =
+    \k.(\k.k(\x.y))(\m.m(\k.(\k.k(\x.z))(\m.muk))k)
+
+Because the initial `\k` protects (i.e., takes scope over) the entire
+transformed term, we can't perform any reductions.  In order to watch
+the computation unfold, we have to apply the transformed term to a
+trivial continuation, usually the identity function `I = \x.x`.
+
+    [(\x.y)((\x.z)u)] I =
+    (\k.[\x.y](\m.m[(\x.z)u]k)) I
+     *
+    [\x.y](\m.m[(\x.z)u] I) =
+    (\k.k(\x.y))(\m.m[(\x.z)u] I)
+     *           *
+    (\x.y)[(\x.z)u] I           --A--
+     *
+    y I
+
+The application to `I` unlocks the leftmost functor.  Because that
+functor (`\x.y`) throws away its argument (consider the reduction in the
+line marked (A)), we never need to expand the
+CPS transform of the argument.  This means that we never bother to
+reduce redexes inside the argument.
+
+Compare with a call-by-value xform:
+
+    {x} = \k.kx
+    {\aM} = \k.k(\a{M})
+    {MN} = \k.{M}(\m.{N}(\n.mnk))
+
+This time the reduction unfolds in a different manner:
+
+    {(\x.y)((\x.z)u)} I =
+    (\k.{\x.y}(\m.{(\x.z)u}(\n.mnk))) I
+     *
+    {\x.y}(\m.{(\x.z)u}(\n.mnI)) =
+    (\k.k(\x.{y}))(\m.{(\x.z)u}(\n.mnI))
+     *             *
+    {(\x.z)u}(\n.(\x.{y})nI) =
+    (\k.{\x.z}(\m.{u}(\n.mnk)))(\n.(\x.{y})nI)
+     *
+    {\x.z}(\m.{u}(\n.mn(\n.(\x.{y})nI))) =
+    (\k.k(\x.{z}))(\m.{u}(\n.mn(\n.(\x.{y})nI)))
+     *             *
+    {u}(\n.(\x.{z})n(\n.(\x.{y})nI)) =
+    (\k.ku)(\n.(\x.{z})n(\n.(\x.{y})nI))
+     *      *
+    (\x.{z})u(\n.(\x.{y})nI)       --A--
+     *
+    {z}(\n.(\x.{y})nI) =
+    (\k.kz)(\n.(\x.{y})nI)
+     *      *
+    (\x.{y})zI
+     *
+    {y}I =
+    (\k.ky)I
+     *
+    I y
+
+In this case, the argument does get evaluated: consider the reduction
+in the line marked (A).
+
+Both xforms make the following guarantee: as long as redexes
+underneath a lambda are never evaluated, there will be at most one
+reduction available at any step in the evaluation.
+That is, all choice is removed from the evaluation process.
+
+Now let's verify that the CBN CPS avoids the infinite reduction path
+discussed above (remember that `w = \x.xx`):
+
+    [(\x.y)(ww)] I =
+    (\k.[\x.y](\m.m[ww]k)) I
+     *
+    [\x.y](\m.m[ww]I) =
+    (\k.k(\x.y))(\m.m[ww]I)
+     *             *
+    (\x.y)[ww]I
+     *
+    y I
+
+
+Questions and exercises:
+
+1. Prove that {(\x.y)(ww)} does not terminate.
+
+2. Why is the CBN xform for variables `[x] = x` instead of something
+involving kappas (i.e., `k`'s)?  
+
+3. Write an Ocaml function that takes a lambda term and returns a
+CPS-xformed lambda term.  You can use the following data declaration:
+
+    type form = Var of char | Abs of char * form | App of form * form;;
+
+4. The discussion above talks about the "leftmost" redex, or the
+"rightmost".  But these words apply accurately only in a special set
+of terms.  Characterize the order of evaluation for CBN (likewise, for
+CBV) more completely and carefully.
+
+5. What happens (in terms of evaluation order) when the application
+rule for CBV CPS is changed to `{MN} = \k.{N}(\n.{M}(\m.mnk))`?
+
+6. A term and its CPS xform are different lambda terms.  Yet in some
+sense they "do" the same thing computationally.  Make this sense
+precise.
+
+
+Thinking through the types
+--------------------------
+
+This discussion is based on [Meyer and Wand 1985](http://citeseer.ist.psu.edu/viewdoc/download?doi=10.1.1.44.7943&rep=rep1&type=pdf).
+
+Let's say we're working in the simply-typed lambda calculus.
+Then if the original term is well-typed, the CPS xform will also be
+well-typed.  But what will the type of the transformed term be?
+
+The transformed terms all have the form `\k.blah`.  The rule for the
+CBN xform of a variable appears to be an exception, but instead of
+writing `[x] = x`, we can write `[x] = \k.xk`, which is
+eta-equivalent.  The `k`'s are continuations: functions from something
+to a result.  Let's use &sigma; as the result type.  The each `k` in
+the transform will be a function of type &rho; --> &sigma; for some
+choice of &rho;.
+
+We'll need an ancilliary function ': for any ground type a, a' = a;
+for functional types a->b, (a->b)' = ((a' -> &sigma;) -> &sigma;) -> (b' -> &sigma;) -> &sigma;.
+
+    Call by name transform
+
+    Terms                            Types
+
+    [x] = \k.xk                      [a] = (a'->o)->o
+    [\xM] = \k.k(\x[M])              [a->b] = ((a->b)'->o)->o
+    [MN] = \k.[M](\m.m[N]k)          [b] = (b'->o)->o
+
+Remember that types associate to the right.  Let's work through the
+application xform and make sure the types are consistent.  We'll have
+the following types:
+
+    M:a->b
+    N:a
+    MN:b 
+    k:b'->o
+    [N]:(a'->o)->o
+    m:((a'->o)->o)->(b'->o)->o
+    m[N]:(b'->o)->o
+    m[N]k:o 
+    [M]:((a->b)'->o)->o = ((((a'->o)->o)->(b'->o)->o)->o)->o
+    [M](\m.m[N]k):o
+    [MN]:(b'->o)->o
+
+Be aware that even though the transform uses the same symbol for the
+translation of a variable (i.e., `[x] = x`), in general the variable
+in the transformed term will have a different type than in the source
+term.
+
+Excercise: what should the function ' be for the CBV xform?  Hint: 
+see the Meyer and Wand abstract linked above for the answer.
+
+
+Other CPS transforms
+--------------------
+
+It is easy to think that CBN and CBV are the only two CPS transforms.
+(We've already seen a variant on call-by-value one of the excercises above.) 
+
+In fact, the number of distinct transforms is unbounded.  For
+instance, here is a variant of CBV that uses the same types as CBN:
+
+    <x> = x
+    <\xM> = \k.k(\x<M>)
+    <MN> = \k.<M>(\m.<N>(\n.m(\k.kn)k))
+
+Try reducing `<(\x.x) ((\y.y) (\z.z))> I` to convince yourself that
+this is a version of call-by-value.
+
+Once we have two evaluation strategies that rely on the same types, we
+can mix and match:
+
+    [x] = x
+    <x> = x
+    [\xM] = \k.k(\x<M>)
+    <\xM] = \k.k(\x[M])
+    [MN] = \k.<M>(\m.m<N>k)
+    <MN> = \k.[M](\m.[N](\n.m(\k.kn)k))
+
+This xform interleaves call-by-name and call-by-value in layers,
+according to the depth of embedding.
+(Cf. page 4 of Reynold's 1974 paper ftp://ftp.cs.cmu.edu/user/jcr/reldircont.pdf (equation (4) and the
+explanation in the paragraph below.)
diff --git a/topics/_cps_and_continuation_operators.mdwn b/topics/_cps_and_continuation_operators.mdwn
new file mode 100644 (file)
index 0000000..72b0034
--- /dev/null
@@ -0,0 +1,672 @@
+[[!toc]]
+
+CPS Transforms
+==============
+
+We've already approached some tasks now by programming in **continuation-passing style.** We first did that with tuples at the start of term, and then with the v5 lists in [[week4]], and now more recently and self-consciously when discussing [aborts](/couroutines_and_aborts), 
+and [the "abSd" task](/from_list_zippers_to_continuations). and the use of `tree_monadize` specialized to the Continuation monad, which required us to supply an initial continuation.
+
+In our discussion of aborts, we showed how to rearrange code like this:
+
+
+       let foo x =
+       +---try begin----------------+
+       |       (if x = 1 then 10    |
+       |       else abort 20        |
+       |       ) + 100              |
+       +---end----------------------+
+       in (foo 2) + 1000;;
+
+into a form like this:
+
+       let x = 2
+       in let snapshot = fun box ->
+           let foo_result = box
+           in (foo_result) + 1000
+       in let continue_normally = fun from_value ->
+           let value = from_value + 100
+           in snapshot value
+       in
+           if x = 1 then continue_normally 10
+           else snapshot 20;;
+
+<!--
+# #require "delimcc";;
+# open Delimcc;;
+# let reset body = let p = new_prompt () in push_prompt p (body p);;
+# let test_cps x =
+      let snapshot = fun box ->
+          let foo_result = box
+          in (foo_result) + 1000
+      in let continue_normally = fun from_value ->
+          let value = from_value + 100
+          in snapshot value
+      in if x = 1 then continue_normally 10
+      else snapshot 20;;
+
+       let foo x =
+       +===try begin================+
+       |       (if x = 1 then 10    |
+       |       else abort 20        |
+       |       ) + 100              |
+       +===end======================+
+       in (foo 2) + 1000;;
+
+# let test_shift x =
+    let foo x = reset(fun p () ->
+        (shift p (fun k ->
+            if x = 1 then k 10 else 20)
+        ) + 100)
+    in foo z + 1000;;
+
+# test_cps 1;;
+- : int = 1110
+# test_shift 1;;
+- : int = 1110
+# test_cps 2;;
+- : int = 1020
+# test_shift 2;;
+- : int = 1020
+-->
+
+How did we figure out how to rearrange that code? There are algorithms that can do this for us mechanically. These algorithms are known as **CPS transforms**, because they transform code that might not yet be in CPS form into that form.
+
+We won't attempt to give a full CPS transform for OCaml; instead we'll just focus on the lambda calculus and a few extras, to be introduced as we proceed.
+
+In fact there are multiple ways to do a CPS transform. Here is one:
+
+       [x]     --> x
+       [\x. M] --> \k. k (\x. [M])
+       [M N]   --> \k. [M] (\m. m [N] k)
+
+And here is another:
+
+       [x]     --> \k. k x
+       [\x. M] --> \k. k (\x. [M])
+       [M N]   --> \k. [M] (\m. [N] (\n. m n k))
+
+These transforms have some interesting properties. One is that---assuming we never reduce inside a lambda term, but only when redexes are present in the outermost level---the formulas generated by these transforms will always only have a single candidate redex to be reduced at any stage. In other words, the generated expressions dictate in what order the components from the original expressions will be evaluated. As it happens, the first transform above forces a *call-by-name* reduction order: assuming `M N` to be a redex, redexes inside `N` will be evaluated only after `N` has been substituted into `M`. And the second transform forces a *call-by-value* reduction order. These reduction orders will be forced no matter what the native reduction order of the interpreter is, just so long as we're only allowed to reduce redexes not underneath lambdas.
+
+Plotkin did important early work with CPS transforms, and they are now a staple of academic computer science. (See the end of his 1975 paper [Call-by-name, call-by-value, and the lambda-calculus](http://homepages.inf.ed.ac.uk/gdp/publications/cbn_cbv_lambda.pdf).)
+
+Here's another interesting fact about these transforms. Compare the translations for variables and applications in the call-by-value transform:
+
+       [x]     --> \k. k x
+       [M N]   --> \k. [M] (\m. [N] (\n. m n k))
+
+to the implementations we proposed for `unit` and `bind` when developing a Continuation monads, for example [here](/list_monad_as_continuation_monad). I'll relabel some of the variable names to help the comparison:
+
+       let cont_unit x = fun k -> k x
+       let cont_bind N M = fun k -> N (fun n -> M n k)
+
+The transform for `x` is just `cont_unit x`! And the transform for `M N` is, though not here exactly the same as `cont_bind N M`, quite reminiscent of it. (I don't yet know whether there's an easy and satisfying explanation of why these two are related as they are.) <!-- FIXME -->
+
+Doing CPS transforms by hand is very cumbersome. (Try it.) But you can leverage our lambda evaluator to help you out. Here's how to do it. From here on out, we'll be working with and extending the call-by-value CPS transform set out above:
+
+       let var = \x (\k. k x) in
+       let lam = \x_body (\k. k (\x. x_body x)) in
+       let app = \m n. (\k. m (\m. n (\n. m n k))) in
+       ...
+
+Then if you want to use [x], you'd write `var x`. If you want to use [\x. body], you'd write `lam (\x. BODY)`, where `BODY` is whatever [body] amounts to. If you want to use [m n], you'd write `app M N`, where M and N are whatever [m] and [n] amount to.
+
+To play around with this, you'll also want to help yourself to some primitives already in CPS form. (You won't want to rebuild everything again from scratch.) For a unary function like `succ`, you can take its primitive CPS analogue [succ] to be `\u. u (\a k. k (succ a))` (where `succ` in this expansion is the familiar non-CPS form of `succ`). Then for example:
+
+       [succ x]
+                 = \k. [succ] (\m. [x] (\n. m n k))
+               ~~> ...
+               ~~> \k. k (succ x)
+
+Or, using the lambda evaluator, that is:
+
+       ...
+       let op1 = \op. \u. u (\a k. k (op a)) in
+       app (op1 succ) (var x)
+       ~~> \k. k (succ x)
+
+Some other handy tools: 
+
+       let app2 = \a b c. app (app a b) c in
+       let app3 = \a b c d. app (app (app a b) c) d in
+       let op2 = \op. \u. u (\a v. v (\b k. k (op a b))) in
+       let op3 = \op. \u. u (\a v. v (\b w. w (\c k. k (op a b c)))) in
+       ...
+
+Then, for instance, [plus x y] would be rendered in the lambda evaluator as:
+
+       app2 (op2 plus) (var x) (var y)
+       ~~> \k. k (plus x y)
+
+To finish off a CPS computation, you have to supply it with an "initial" or "outermost" continuation. (This is somewhat like "running" a monadic computation.) Usually you'll give the identity function, representing that nothing further happens to the continuation-expecting value.
+
+If the program you're working with is already in CPS form, then some elegant and powerful computational patterns become available, as we've been seeing. But it's tedious to convert to and work in fully-explicit CPS form. Usually you'll just want to be using the power of continuations at some few points in your program. It'd be nice if we had some way to make use of those patterns without having to convert our code explicitly into CPS form.
+
+Callcc
+======
+
+Well, we can. Consider the space of lambda formulas. Consider their image under a CPS transform. There will be many well-formed lambda expressions not in that image---that is, expressions that aren't anybody's CPS transform. Some of these will be useful levers in the CPS patterns we want to make use of. We can think of them as being the CPS transforms of some new syntax in the original language. For example, the expression `callcc` is explained as a new bit of syntax having some of that otherwise unclaimed CPS real-estate. The meaning of the new syntax can be understood in terms of how the CPS transform we specify for it behaves, when the whole language is in CPS form.
+
+I won't give the CPS transform for `callcc` itself, but instead for the complex form:
+
+       [callcc (\k. body)] = \outk. (\k. [body] outk) (\v localk. outk v)
+
+The behavior of `callcc` is this. The whole expression `callcc (\k. body)`, call it C, is being evaluated in a context, call it E[\_]. When we convert to CPS form, the continuation of this occurrence of C will be bound to the variable `outk`. What happens then is that we bind the expression `\v localk. outk v` to the variable `k` and evaluate [body], passing through to it the existing continuation `outk`. Now if `body` is just, for example, `x`, then its CPS transform [x] will be `\j. j x` and this will accept the continuation `outk` and feed it `x`, and we'll continue on with nothing unusual occurring. If on the other hand `body` makes use of the variable `k`, what happens then? For example, suppose `body` includes `foo (k v)`. In the reduction of the CPS transform `[foo (k v)]`, `v` will be passed to `k` which as we said is now `\v localk. outk v`. The continuation of that application---what is scheduled to happen to `k v` after it's evaluated and `foo` gets access to it---will be bound next to `localk`. But notice that this `localk` is discarded. The computation goes on without it. Instead, it just continues evaluating `outk v`, where as we said `outk` is the outside continuation E[\_] of the whole `callcc (\k. body)` invocation.
+
+So in other words, since the continuation in which `foo` was to be applied to the value of `k v` was discarded, that application never gets evaluated. We escape from that whole block of code.
+
+It's important to understand that `callcc` binds `k` to a pipe into the continuation as still then installed. Not just to a function that performs the same computation as the context E[\_] does---that has the same normal form and extension. But rather, a pipe into E[\_] *in its continuation-playing role*. This is manifested by the fact that when `k v` finishes evaluating, that value is not delivered to `foo` for the computation to proceed. Instead, when `k v` finishes evaluating, the program will then be done. Not because of some "stop here" block attached to `k`, but rather because of what it is that `k` represents. Walking through the explanation above several times may help you understand this better.
+
+So too will examples. We'll give some examples, and show you how to try them out in a variety of formats:
+
+1.     using the lambda evaluator to check how the CPS transforms reduce
+
+       To do this, you can use the following helper function:
+
+               let callcc = \k_body. \outk. (\k. (k_body k) outk) (\v localk. outk v) in
+               ...
+
+       Used like this: [callcc (\k. body)] = `callcc (\k. BODY)`, where `BODY` is [body].
+
+2.     using a `callcc` operation on our Continuation monad
+
+       This is implemented like this:
+
+               let callcc body = fun outk -> body (fun v localk -> outk v) outk
+
+       <!-- GOTCHAS?? -->
+
+3.     `callcc` was originally introduced in Scheme. There it's written `call/cc` and is an abbreviation of `call-with-current-continuation`. Instead of the somewhat bulky form:
+
+               (call/cc (lambda (k) ...))
+
+       I prefer instead to use the lighter, and equivalent, shorthand:
+
+               (let/cc k ...)
+
+
+Callcc/letcc examples
+---------------------
+
+First, here are two examples in Scheme:
+
+       (+ 100 (let/cc k (+ 10 1)))
+              |-----------------|
+
+This binds the continuation `outk` of the underlined expression to `k`, then computes `(+ 10 1)` and delivers that to `outk` in the normal way (not through `k`). No unusual behavior. It evaluates to `111`.
+
+What if we do instead:
+
+       (+ 100 (let/cc k (+ 10 (k 1))))
+              |---------------------|
+
+This time, during the evaluation of `(+ 10 (k 1))`, we supply `1` to `k`. So then the local continuation, which delivers the value up to `(+ 10 [_])` and so on, is discarded. Instead `1` gets supplied to the outer continuation in place when `let/cc` was invoked. That will be `(+ 100 [_])`. When `(+ 100 1)` is evaluated, there's no more of the computation left to evaluate. So the answer here is `101`.
+
+You are not restricted to calling a bound continuation only once, nor are you restricted to calling it only inside of the `call/cc` (or `let/cc`) block. For example, you can do this:
+
+       (let ([p (let/cc k (cons 1 k))])
+         (cons (car p) ((cdr p) (cons 2 (lambda (x) x)))))
+       ; evaluates to '(2 2 . #<procedure>)
+
+What happens here? First, we capture the continuation where `p` is about to be assigned a value. Inside the `let/cc` block, we create a pair consisting of `1` and the captured continuation. This pair is bound to p. We then proceed to extract the components of the pair. The head (`car`) goes into the start of a tuple we're building up. To get the next piece of the tuple, we extract the second component of `p` (this is the bound continuation `k`) and we apply it to a pair consisting of `2` and the identity function. Supplying arguments to `k` takes us back to the point where `p` is about to be assigned a value. The tuple we had formerly been building, starting with `1`, will no longer be accessible because we didn't bring along with us any way to refer to it, and we'll never get back to the context where we supplied an argument to `k`. Now `p` gets assigned not the result of `(let/cc k (cons 1 k))` again, but instead, the new pair that we provided: `'(2 . #<identity procedure>)`. Again we proceed to build up a tuple: we take the first element `2`, then we take the second element (now the identity function), and feed it a pair `'(2 . #<identity procedure>)`, and since it's an argument to the identity procedure that's also the result. So our final result is a nested pair, whose first element is `2` and whose second element is the pair `'(2 . #<identity procedure>)`. Racket displays this nested pair like this:
+
+       '(2 2 . #<procedure>)
+
+Ok, so now let's see how to perform these same computations via CPS.
+
+In the lambda evaluator:
+
+       let var = \x (\k. k x) in
+       let lam = \x_body (\k. k (\x. x_body x)) in
+       let app = \m n. (\k. m (\m. n (\n. m n k))) in
+       let app2 = \a b c. app (app a b) c in
+       let app3 = \a b c d. app (app (app a b) c) d in
+       let op1 = \op. \u. u (\a k. k (op a)) in
+       let op2 = \op. \u. u (\a v. v (\b k. k (op a b))) in
+       let op3 = \op. \u. u (\a v. v (\b w. w (\c k. k (op a b c)))) in
+       let callcc = \k_body. \outk. (\k. (k_body k) outk) (\v localk. outk v) in
+
+       ; (+ 100 (let/cc k (+ 10 1))) ~~> 111
+       app2 (op2 plus) (var hundred) (callcc (\k. app2 (op2 plus) (var ten) (var one)))
+       ; evaluates to \k. k (plus hundred (plus ten one))
+
+Next:
+
+       ; (+ 100 (let/cc k (+ 10 (k 1)))) ~~> 101
+       app2 (op2 plus) (var hundred) (callcc (\k. app2 (op2 plus) (var ten) (app (var k) (var one))))
+       ; evaluates to \k. k (plus hundred one)
+
+We won't try to do the third example in this framework.
+
+Finally, using the Continuation monad from our OCaml monad library. We begin:
+
+       # #use "path/to/monads.ml"
+       # module C = Continuation_monad;;
+
+Now what we want to do is something like this:
+
+       # C.(run0 (100 + callcc (fun k -> 10 + 1)));;
+
+`run0` is a special function in the Continuation monad that runs a value of that monad using the identity function as its initial continuation. The above expression won't type-check, for several reasons. First, we're trying to add 100 to `callcc (...)` but the latter is a `Continuation.m` value, not an `int`. So we have to do this instead:
+
+       # C.(run0 (callcc (fun k -> 10 + 1) >>= fun i -> 100 + i));;
+
+Except that's still no good, because `10 + 1` and `100 + i` are of type `int`, but their context demands Continuation monadic values. So we have to throw in some `unit`s:
+
+       # C.(run0 (callcc (fun k -> unit (10 + 1)) >>= fun i -> unit (100 + i)));;
+       - : int = 111
+
+This works and as you can see, delivers the same answer `111` that we got by the other methods.
+
+Next we try:
+
+       # C.(run0 (callcc (fun k -> unit (10 + (k 1))) >>= fun i -> unit (100 + i)));;
+
+That won't work because `k 1` doesn't have type `int`, but we're trying to add it to `10`. So we have to do instead:
+
+       # C.(run0 (callcc (fun k -> k 1 >>= fun j -> unit (10 + j)) >>= fun i -> unit (100 + i)));;
+       - : int = 101
+
+This also works and as you can see, delivers the expected answer `101`.
+
+The third example is more difficult to make work with the monadic library, because its types are tricky. I was able to get this to work, which uses OCaml's "polymorphic variants." These are generally more relaxed about typing. There may be a version that works with regular OCaml types, but I haven't yet been able to identify it. Here's what does work:
+
+       # C.(run0 (callcc (fun k -> unit (1,`Box k)) >>= fun (p1,`Box p2) -> p2 (2,`Box unit) >>= fun p2' -> unit (p1,p2')));;
+       - : int * (int * [ `Box of 'b -> ('a, 'b) C.m ] as 'b) as 'a =
+       (2, (2, `Box <fun>))
+
+<!-- FIXME -->
+
+Some callcc/letcc exercises
+---------------------------
+
+Here are a series of examples from *The Seasoned Schemer*, which we recommended at the start of term. It's not necessary to have the book to follow the exercises, though if you do have it, its walkthroughs will give you useful assistance.
+
+For reminders about Scheme syntax, see [here](/assignment8/) and [here](/week1/) and [here](/translating_between_ocaml_scheme_and_haskell). Other resources are on our [[Learning Scheme]] page.
+
+Most of the examples assume the following preface:
+
+       #lang racket
+
+       (define (atom? x)
+         (and (not (pair? x)) (not (null? x))))
+
+Now try to figure out what this function does:
+
+       (define alpha
+         (lambda (a lst)
+           (let/cc k ; now what will happen when k is called?
+             (letrec ([aux (lambda (l)
+                             (cond
+                               [(null? l) '()]
+                               [(eq? (car l) a) (k (aux (cdr l)))]
+                               [else (cons (car l) (aux (cdr l)))]))])
+               (aux lst)))))
+       
+Here is [the answer](/hints/cps_hint_1), but try to figure it out for yourself.
+
+Next, try to figure out what this function does:
+
+       (define beta
+         (lambda (lst)
+           (let/cc k ; now what will happen when k is called?
+             (letrec ([aux (lambda (l)
+                             (cond
+                               [(null? l) '()]
+                               [(atom? (car l)) (k (car l))]
+                               [else (begin
+                                       ; what will the value of the next line be? why is it ignored?
+                                       (aux (car l))
+                                       (aux (cdr l)))]))])
+               (aux lst)))))
+
+Here is [the answer](/hints/cps_hint_2), but try to figure it out for yourself.
+
+Next, try to figure out what this function does:
+
+       (define gamma
+         (lambda (a lst)
+           (letrec ([aux (lambda (l k)
+                           (cond
+                             [(null? l) (k 'notfound)]
+                             [(eq? (car l) a) (cdr l)]
+                             [(atom? (car l)) (cons (car l) (aux (cdr l) k))]
+                             [else
+                              ; what happens when (car l) exists but isn't an atom?
+                              (let ([car2 (let/cc k2 ; now what will happen when k2 is called?
+                                            (aux (car l) k2))])
+                                (cond
+                                  ; when will the following condition be met? what happens then?
+                                  [(eq? car2 'notfound) (cons (car l) (aux (cdr l) k))]
+                                  [else (cons car2 (cdr l))]))]))]
+                    [lst2 (let/cc k1 ; now what will happen when k1 is called?
+                            (aux lst k1))])
+             (cond
+               ; when will the following condition be met?
+               [(eq? lst2 'notfound) lst]
+               [else lst2]))))
+
+Here is [the answer](/hints/cps_hint_3), but try to figure it out for yourself.
+
+Here is the hardest example. Try to figure out what this function does:
+
+       (define delta
+         (letrec ([yield (lambda (x) x)]
+                  [resume (lambda (x) x)]
+                  [walk (lambda (l)
+                          (cond
+                            ; is this the only case where walk returns a non-atom?
+                            [(null? l) '()]
+                            [(atom? (car l)) (begin
+                                               (let/cc k2 (begin
+                                                 (set! resume k2) ; now what will happen when resume is called?
+                                                 ; when the next line is executed, what will yield be bound to?
+                                                 (yield (car l))))
+                                               ; when will the next line be executed?
+                                               (walk (cdr l)))]
+                            [else (begin
+                                    ; what will the value of the next line be? why is it ignored?
+                                    (walk (car l))
+                                    (walk (cdr l)))]))]
+                  [next (lambda () ; next is a thunk
+                          (let/cc k3 (begin
+                            (set! yield k3) ; now what will happen when yield is called?
+                            ; when the next line is executed, what will resume be bound to?
+                            (resume 'blah))))]
+                  [check (lambda (prev)
+                           (let ([n (next)])
+                             (cond
+                               [(eq? n prev) #t]
+                               [(atom? n) (check n)]
+                               ; when will n fail to be an atom?
+                               [else #f])))])
+           (lambda (lst)
+             (let ([fst (let/cc k1 (begin
+                          (set! yield k1) ; now what will happen when yield is called?
+                          (walk lst)
+                          ; when will the next line be executed?
+                          (yield '())))])
+               (cond
+                 [(atom? fst) (check fst)]
+                 ; when will fst fail to be an atom?
+                 [else #f])
+               ))))
+
+Here is [the answer](/hints/cps_hint_4), but again, first try to figure it out for yourself.
+
+
+Delimited control operators
+===========================
+
+Here again is the CPS transform for `callcc`:
+
+       [callcc (\k. body)] = \outk. (\k. [body] outk) (\v localk. outk v)
+
+`callcc` is what's known as an *undelimited control operator*. That is, the continuations `outk` that get bound into our `k`s include all the code from the `call/cc ...` out to *and including* the end of the program. Calling such a continuation will never return any value to the call site.
+
+(See the technique employed in the `delta` example above, with the `(begin (let/cc k2 ...) ...)`, for a work-around. Also. if you've got a copy of *The Seasoned Schemer*, see the comparison of let/cc vs. "collector-using" (that is, partly CPS) functions at pp. 155-164.)
+
+Often times it's more useful to use a different pattern, where we instead capture only the code from the invocation of our control operator out to a certain boundary, not including the end of the program. These are called *delimited control operators*. A variety of these have been formulated. The most well-behaved from where we're coming from is the pair `reset` and `shift`. `reset` sets the boundary, and `shift` binds the continuation from the position where it's invoked out to that boundary.
+
+It works like this:
+
+       (1) outer code
+       ------- reset -------
+       | (2)               |
+       | +----shift k ---+ |
+       | | (3)           | |
+       | |               | |
+       | |               | |
+       | +---------------+ |
+       | (4)               |
+       +-------------------+
+       (5) more outer code
+
+First, the code in position (1) runs. Ignore position (2) for the moment. When we hit the `shift k`, the continuation between the `shift` and the `reset` will be captured and bound to `k`. Then the code in position (3) will run, with `k` so bound. The code in position (4) will never run, unless it's invoked through `k`. If the code in position (3) just ends with a regular value, and doesn't apply `k`, then the value returned by (3) is passed to (5) and the computation continues.
+
+So it's as though the middle box---the (2) and (4) region---is by default not evaluated. This code is instead bound to `k`, and it's up to other code whether and when to apply `k` to any argument. If `k` is applied to an argument, then what happens? Well it will be as if that were the argument supplied by (3) only now that argument does go to the code (4) syntactically enclosing (3). When (4) is finished, that value also goes to (5) (just as (3)'s value did when it ended with a regular value). `k` can be applied repeatedly, and every time the computation will traverse that same path from (4) into (5).
+
+I set (2) aside a moment ago. The story we just told is a bit too simple because the code in (2) needs to be evaluated because some of it may be relied on in (3).
+
+For instance, in Scheme this:
+
+       (require racket/control)
+       
+       (reset
+        (let ([x 1])
+          (+ 10 (shift k x))))
+
+will return 1. The `(let ([x 1]) ...` part is evaluated, but the `(+ 10 ...` part is not.
+
+Notice we had to preface the Scheme code with `(require racket/control)`. You don't have to do anything special to use `call/cc` or `let/cc`; but to use the other control operators we'll discuss you do have to include that preface in Racket.
+
+This pattern should look somewhat familiar. Recall from our discussion of aborts, and repeated at the top of this page:
+
+       let foo x =
+       +---try begin----------------+
+       |       (if x = 1 then 10    |
+       |       else abort 20        |
+       |       ) + 100              |
+       +---end----------------------+
+       in (foo 2) + 1000;;
+
+The box is working like a reset. The `abort` is implemented with a `shift`. Earlier, we refactored our code into a more CPS form:
+
+       let x = 2
+       in let snapshot = fun box ->
+           let foo_result = box
+           in (foo_result) + 1000
+       in let continue_normally = fun from_value ->
+           let value = from_value + 100
+           in snapshot value
+       in
+           if x = 1 then continue_normally 10
+           else snapshot 20;;
+
+`snapshot` here corresponds to the code outside the `reset`. `continue_normally` is the middle block of code, between the `shift` and its surrounding `reset`. This is what gets bound to the `k` in our `shift`. The `if...` statement is inside a `shift`. Notice there that we invoke the bound continuation to "continue normally". We just invoke the outer continuation, saved in `snapshot` when we placed the `reset`, to skip the "continue normally" code and immediately abort to outside the box.
+
+Using `shift` and `reset` operators in OCaml, this would look like this:
+
+       #require "delimcc";;
+       let p = Delimcc.new_prompt ();;
+       let reset = Delimcc.push_prompt p;;
+       let shift = Delimcc.shift p;;
+       let abort = Delimcc.abort p;;
+       
+       let foo x =
+         reset(fun () ->
+           shift(fun continue ->
+               if x = 1 then continue 10
+               else 20
+           ) + 100
+         )
+       in foo 2 + 1000;;
+       - : int = 1020
+
+If instead at the end we did `... foo 1 + 1000`, we'd get the result `1110`.
+
+The above OCaml code won't work out of the box; you have to compile and install a special library that Oleg wrote. We discuss it on our [translation page](/translating_between_ocaml_scheme_and_haskell). If you can't get it working, then you can play around with `shift` and `reset` in Scheme instead. Or in the Continuation monad. Or using CPS transforms of your code, with the help of the lambda evaluator.
+
+You can make the lambda evaluator perform the required CPS transforms with these helper functions:
+
+       let reset = \body. \outk. outk (body (\i i)) in
+       let shift = \k_body. \midk. (\k. (k_body k) (\i i)) (\a localk. localk (midk a)) in
+       let abort = \body. \midk. body (\i i) in
+       ...
+
+You use these like so:
+
+*      [reset body] is `reset BODY` where `BODY` is [body]
+*      [shift k body] is `shift (\k. BODY)` where `BODY` is [body]
+*      and [abort value] is `abort VALUE` where `VALUE` is [value]
+       
+There are also `reset` and `shift` and `abort` operations in the Continuation monad in our OCaml [[monad library]]. You can check the code for details.
+
+
+As we said, there are many varieties of delimited continuations. Another common pair is `prompt` and `control`. There's no difference in meaning between `prompt` and `reset`; it's just that people tend to say `reset` when talking about `shift`, and `prompt` when talking about `control`. `control` acts subtly differently from `shift`. In the uses you're likely to make as you're just learning about continuations, you won't see any difference. If you'll do more research in this vicinity, you'll soon enough learn about the differences.
+
+(You can start by reading [the Racket docs](http://docs.racket-lang.org/reference/cont.html?q=shift&q=do#%28part._.Classical_.Control_.Operators%29).)
+
+
+Ken Shan has done terrific work exploring the relations of `shift` and `control` and other control operators to each other.
+
+In collecting these CPS transforms and implementing the monadic versions, we've been helped by Ken and by Oleg and by these papers:
+
+*      Danvy and Filinski, "Representing control: a study of the CPS transformation" (1992)
+*      Sabry, "Note on axiomatizing the semantics of control operators" (1996)
+
+
+Examples of shift/reset/abort
+-----------------------------
+
+Here are some more examples of using delimited control operators. We present each example three ways: first a Scheme formulation; then we compute the same result using CPS and the lambda evaluator; then we do the same using the Continuation monad in OCaml. (We don't demonstrate the use of Oleg's delimcc library.)
+
+
+Example 1:
+
+       ; (+ 1000 (+ 100 (abort 11))) ~~> 11
+       
+       app2 (op2 plus) (var thousand)
+         (app2 (op2 plus) (var hundred) (abort (var eleven)))
+       
+       # Continuation_monad.(run0(
+           abort 11 >>= fun i ->
+           unit (100+i) >>= fun j ->
+           unit (1000+j)));;
+       - : int = 11
+
+When no `reset` is specified, there's understood to be an implicit one surrounding the entire computation (but unlike in the case of `callcc`, you still can't capture up to *and including* the end of the computation). So it makes no difference if we say instead:
+
+       # Continuation_monad.(run0(
+           reset (
+             abort 11 >>= fun i ->
+             unit (100+i) >>= fun j ->
+             unit (1000+j))));;
+       - : int = 11
+
+
+Example 2:
+       
+       ; (+ 1000 (reset (+ 100 (abort 11)))) ~~> 1011
+       
+       app2 (op2 plus) (var thousand)
+         (reset (app2 (op2 plus) (var hundred) (abort (var eleven))))
+       
+       # Continuation_monad.(run0(
+           reset (
+             abort 11 >>= fun i ->
+             unit (100+i)
+           ) >>= fun j ->
+           unit (1000+j)));;
+       - : int = 1011
+
+Example 3:
+
+       ; (+ 1000 (reset (+ 100 (shift k (+ 10 1))))) ~~> 1011
+
+       app2 (op2 plus) (var thousand)
+         (reset (app2 (op2 plus) (var hundred)
+           (shift (\k. ((op2 plus) (var ten) (var one))))))
+
+       Continuation_monad.(
+         let v = reset (
+           let u = shift (fun k -> unit (10 + 1))
+           in u >>= fun x -> unit (100 + x)
+         ) in let w = v >>= fun x -> unit (1000 + x)
+         in run0 w);;
+       - : int = 1011
+
+Example 4:
+
+       ; (+ 1000 (reset (+ 100 (shift k (k (+ 10 1)))))) ~~> 1111
+       
+       app2 (op2 plus) (var thousand)
+         (reset (app2 (op2 plus) (var hundred)
+           (shift (\k. (app (var k) ((op2 plus) (var ten) (var one)))))))
+       
+       Continuation_monad.(
+         let v = reset (
+           let u = shift (fun k -> k (10 :: [1]))
+           in u >>= fun x -> unit (100 :: x)
+         ) in let w = v >>= fun x -> unit (1000 :: x)
+         in run0 w);;
+       - : int list = [1000; 100; 10; 1]
+
+To demonstrate the different adding order between Examples 4 and 5, we use `::` in the OCaml version instead of `+`. Here is Example 5:
+
+       ; (+ 1000 (reset (+ 100 (shift k (+ 10 (k 1)))))) ~~> 1111 but added differently
+
+       app2 (op2 plus) (var thousand)
+         (reset (app2 (op2 plus) (var hundred)
+           (shift (\k. ((op2 plus) (var ten) (app (var k) (var one)))))))
+       
+       Continuation_monad.(let v = reset (
+           let u = shift (fun k -> k [1] >>= fun x -> unit (10 :: x))
+           in u >>= fun x -> unit (100 :: x)
+         ) in let w = v >>= fun x -> unit (1000 :: x)
+         in run0  w);;
+       - : int list = [1000; 10; 100; 1]
+
+
+Example 6:
+
+       ; (+ 100 ((reset (+ 10 (shift k k))) 1)) ~~> 111
+       
+       app2 (op2 plus) (var hundred)
+         (app (reset (app2 (op2 plus) (var ten)
+           (shift (\k. (var k))))) (var one))
+       
+       (* not sure if this example can be typed as-is in OCaml... this is the best I an do at the moment... *)
+
+       # type 'x either = Left of (int -> ('x,'x either) Continuation_monad.m) | Right of int;;
+       # Continuation_monad.(let v = reset (
+           shift (fun k -> unit (Left k)) >>= fun i -> unit (Right (10+i))
+         ) in let w = v >>= fun (Left k) ->
+             k 1 >>= fun (Right i) ->
+             unit (100+i)
+         in run0 w);;
+       - : int = 111
+
+<!--
+# type either = Left of (int -> either) | Right of int;;
+# let getleft e = match e with Left lft -> lft | Right _ -> failwith "not a Left";;
+# let getright e = match e with Right rt -> rt | Left _ -> failwith "not a Right";;
+# 100 + getright (let v = reset (fun p () -> Right (10 + shift p (fun k -> Left k))) in getleft v 1);;
+-->
+
+Example 7:
+
+       ; (+ 100 (reset (+ 10 (shift k (k (k 1)))))) ~~> 121
+       
+       app2 (op2 plus) (var hundred)
+         (reset (app2 (op2 plus) (var ten)
+           (shift (\k. app (var k) (app (var k) (var one))))))
+       
+       Continuation_monad.(let v = reset (
+           let u = shift (fun k -> k 1 >>= fun x -> k x)
+           in u >>= fun x -> unit (10 + x)
+         ) in let w = v >>= fun x -> unit (100 + x)
+         in run0 w)
+       - : int = 121
+
+<!--
+
+       print_endline "=== pa_monad's Continuation Tests ============";;
+
+       (1, 5 = C.(run0 (unit 1 >>= fun x -> unit (x+4))) );;
+       (2, 9 = C.(run0 (reset (unit 5 >>= fun x -> unit (x+4)))) );;
+       (3, 9 = C.(run0 (reset (abort 5 >>= fun y -> unit (y+6)) >>= fun x -> unit (x+4))) );;
+       (4, 9 = C.(run0 (reset (reset (abort 5 >>= fun y -> unit (y+6))) >>= fun x -> unit (x+4))) );;
+       (5, 27 = C.(run0 (
+                                 let c = reset(abort 5 >>= fun y -> unit (y+6))
+                                 in reset(c >>= fun v1 -> abort 7 >>= fun v2 -> unit (v2+10) ) >>= fun x -> unit (x+20))) );;
+
+       (7, 117 = C.(run0 (reset (shift (fun sk -> sk 3 >>= sk >>= fun v3 -> unit (v3+100) ) >>= fun v1 -> unit (v1+2)) >>= fun x -> unit (x+10))) );;
+
+       (8, 115 = C.(run0 (reset (shift (fun sk -> sk 3 >>= fun v3 -> unit (v3+100)) >>= fun v1 -> unit (v1+2)) >>= fun x -> unit (x+10))) );;
+
+       (12, ["a"] = C.(run0 (reset (shift (fun f -> f [] >>= fun t -> unit ("a"::t)  ) >>= fun xv -> shift (fun _ -> unit xv)))) );;
+
+
+       (0, 15 = C.(run0 (let f k = k 10 >>= fun v-> unit (v+100) in reset (callcc f >>= fun v -> unit (v+5)))) );;
+
+-->
diff --git a/topics/_from_list_zippers_to_continuations.mdwn b/topics/_from_list_zippers_to_continuations.mdwn
new file mode 100644 (file)
index 0000000..dcd11ce
--- /dev/null
@@ -0,0 +1,222 @@
+Refunctionalizing zippers: from lists to continuations
+------------------------------------------------------
+
+If zippers are continuations reified (defuntionalized), then one route
+to continuations is to re-functionalize a zipper.  Then the
+concreteness and understandability of the zipper provides a way of
+understanding an equivalent treatment using continuations.
+
+Let's work with lists of `char`s for a change.  We'll sometimes write
+"abSd" as an abbreviation for  
+`['a'; 'b'; 'S'; 'd']`.
+
+We will set out to compute a deceptively simple-seeming **task: given a
+string, replace each occurrence of 'S' in that string with a copy of
+the string up to that point.**
+
+We'll define a function `t` (for "task") that maps strings to their
+updated version.
+
+Expected behavior:
+
+       t "abSd" ~~> "ababd"
+
+
+In linguistic terms, this is a kind of anaphora
+resolution, where `'S'` is functioning like an anaphoric element, and
+the preceding string portion is the antecedent.
+
+This task can give rise to considerable complexity.
+Note that it matters which 'S' you target first (the position of the *
+indicates the targeted 'S'):
+
+           t "aSbS"
+               *
+       ~~> t "aabS"
+                 *
+       ~~> "aabaab"
+
+versus
+
+           t "aSbS"
+                 *
+       ~~> t "aSbaSb"
+               *
+       ~~> t "aabaSb"
+                  *
+       ~~> "aabaaabab"
+
+versus
+
+           t "aSbS"
+                 *
+       ~~> t "aSbaSb"
+                  *
+       ~~> t "aSbaaSbab"
+                   *
+       ~~> t "aSbaaaSbaabab"
+                    *
+       ~~> ...
+
+Apparently, this task, as simple as it is, is a form of computation,
+and the order in which the `'S'`s get evaluated can lead to divergent
+behavior.
+
+For now, we'll agree to always evaluate the leftmost `'S'`, which
+guarantees termination, and a final string without any `'S'` in it.
+
+This is a task well-suited to using a zipper.  We'll define a function
+`tz` (for task with zippers), which accomplishes the task by mapping a
+`char list zipper` to a `char list`.  We'll call the two parts of the
+zipper `unzipped` and `zipped`; we start with a fully zipped list, and
+move elements to the unzipped part by pulling the zipper down until the
+entire list has been unzipped, at which point the zipped half of the
+zipper will be empty.
+
+       type 'a list_zipper = ('a list) * ('a list);;
+       
+       let rec tz (z : char list_zipper) =
+          match z with
+            | (unzipped, []) -> List.rev(unzipped) (* Done! *)
+            | (unzipped, 'S'::zipped) -> tz ((List.append unzipped unzipped), zipped)
+            | (unzipped, target::zipped) -> tz (target::unzipped, zipped);; (* Pull zipper *)
+       
+       # tz ([], ['a'; 'b'; 'S'; 'd']);;
+       - : char list = ['a'; 'b'; 'a'; 'b'; 'd']
+       
+       # tz ([], ['a'; 'S'; 'b'; 'S']);;
+       - : char list = ['a'; 'a'; 'b'; 'a'; 'a'; 'b']
+
+Note that the direction in which the zipper unzips enforces the
+evaluate-leftmost rule.  Task completed.
+
+One way to see exactly what is going on is to watch the zipper in
+action by tracing the execution of `tz`.  By using the `#trace`
+directive in the OCaml interpreter, the system will print out the
+arguments to `tz` each time it is called, including when it is called
+recursively within one of the `match` clauses.  Note that the
+lines with left-facing arrows (`<--`) show (both initial and recursive) calls to `tz`,
+giving the value of its argument (a zipper), and the lines with
+right-facing arrows (`-->`) show the output of each recursive call, a
+simple list.
+
+       # #trace tz;;
+       t1 is now traced.
+       # tz ([], ['a'; 'b'; 'S'; 'd']);;
+       tz <-- ([], ['a'; 'b'; 'S'; 'd'])       (* Initial call *)
+       tz <-- (['a'], ['b'; 'S'; 'd'])         (* Pull zipper *)
+       tz <-- (['b'; 'a'], ['S'; 'd'])         (* Pull zipper *)
+       tz <-- (['b'; 'a'; 'b'; 'a'], ['d'])    (* Special 'S' step *)
+       tz <-- (['d'; 'b'; 'a'; 'b'; 'a'], [])  (* Pull zipper *)
+       tz --> ['a'; 'b'; 'a'; 'b'; 'd']        (* Output reversed *)
+       tz --> ['a'; 'b'; 'a'; 'b'; 'd']
+       tz --> ['a'; 'b'; 'a'; 'b'; 'd']
+       tz --> ['a'; 'b'; 'a'; 'b'; 'd']
+       tz --> ['a'; 'b'; 'a'; 'b'; 'd']
+       - : char list = ['a'; 'b'; 'a'; 'b'; 'd']
+
+The nice thing about computations involving lists is that it's so easy
+to visualize them as a data structure.  Eventually, we want to get to
+a place where we can talk about more abstract computations.  In order
+to get there, we'll first do the exact same thing we just did with
+concrete zipper using procedures instead.
+
+Think of a list as a procedural recipe: `['a'; 'b'; 'c'; 'd']` is the result of
+the computation `'a'::('b'::('c'::('d'::[])))` (or, in our old style,
+`make_list 'a' (make_list 'b' (make_list 'c' (make_list 'd' empty)))`). The
+recipe for constructing the list goes like this:
+
+>      (0)  Start with the empty list []  
+>      (1)  make a new list whose first element is 'd' and whose tail is the list constructed in step (0)  
+>      (2)  make a new list whose first element is 'c' and whose tail is the list constructed in step (1)  
+>      -----------------------------------------  
+>      (3)  make a new list whose first element is 'b' and whose tail is the list constructed in step (2)  
+>      (4)  make a new list whose first element is 'a' and whose tail is the list constructed in step (3)
+
+What is the type of each of these steps?  Well, it will be a function
+from the result of the previous step (a list) to a new list: it will
+be a function of type `char list -> char list`.  We'll call each step
+(or group of steps) a **continuation** of the previous steps.  So in this
+context, a continuation is a function of type `char list -> char
+list`.  For instance, the continuation corresponding to the portion of
+the recipe below the horizontal line is the function `fun (tail : char
+list) -> 'a'::('b'::tail)`. What is the continuation of the 4th step? That is, after we've built up `'a'::('b'::('c'::('d'::[])))`, what more has to happen to that for it to become the list `['a'; 'b'; 'c'; 'd']`? Nothing! Its continuation is the function that does nothing: `fun tail -> tail`.
+
+In what follows, we'll be thinking about the result list that we're building up in this procedural way. We'll treat our input list just as a plain old static list data structure, that we recurse through in the normal way we're accustomed to. We won't need a zipper data structure, because the continuation-based representation of our result list will take over the same role.
+
+So our new function `tc` (for task with continuations) takes an input list (not a zipper) and a also takes a continuation `k` (it's conventional to use `k` for continuation variables). `k` is a function that represents how the result list is going to continue being built up after this invocation of `tc` delivers up a value. When we invoke `tc` for the first time, we expect it to deliver as a value the very de-S'd list we're seeking, so the way for the list to continue being built up is for nothing to happen to it. That is, our initial invocation of `tc` will supply `fun tail -> tail` as the value for `k`. Here is the whole `tc` function. Its structure and behavior follows `tz` from above, which we've repeated here to facilitate detailed comparison:
+
+       let rec tz (z : char list_zipper) =
+           match z with
+           | (unzipped, []) -> List.rev(unzipped) (* Done! *)
+           | (unzipped, 'S'::zipped) -> tz ((List.append unzipped unzipped), zipped)
+           | (unzipped, target::zipped) -> tz (target::unzipped, zipped);; (* Pull zipper *)
+       
+       let rec tc (l: char list) (k: (char list) -> (char list)) =
+           match l with
+           | [] -> List.rev (k [])
+           | 'S'::zipped -> tc zipped (fun tail -> k (k tail))
+           | target::zipped -> tc zipped (fun tail -> target::(k tail));;
+       
+       # tc ['a'; 'b'; 'S'; 'd'] (fun tail -> tail);;
+       - : char list = ['a'; 'b'; 'a'; 'b']
+       
+       # tc ['a'; 'S'; 'b'; 'S'] (fun tail -> tail);;
+       - : char list = ['a'; 'a'; 'b'; 'a'; 'a'; 'b']
+
+To emphasize the parallel, we've re-used the names `zipped` and
+`target`.  The trace of the procedure will show that these variables
+take on the same values in the same series of steps as they did during
+the execution of `tz` above: there will once again be one initial and
+four recursive calls to `tc`, and `zipped` will take on the values
+`"bSd"`, `"Sd"`, `"d"`, and `""` (and, once again, on the final call,
+the first `match` clause will fire, so the the variable `zipped` will
+not be instantiated).
+
+We have not named the continuation argument `unzipped`, although that is
+what the parallel would suggest.  The reason is that `unzipped` (in
+`tz`) is a list, but `k` (in `tc`) is a function.  That's the most crucial 
+difference between the solutions---it's the
+point of the excercise, and it should be emphasized.  For instance,
+you can see this difference in the fact that in `tz`, we have to glue
+together the two instances of `unzipped` with an explicit (and,
+computationally speaking, relatively inefficient) `List.append`.
+In the `tc` version of the task, we simply compose `k` with itself:
+`k o k = fun tail -> k (k tail)`.
+
+A call `tc ['a'; 'b'; 'S'; 'd']` would yield a partially-applied function; it would still wait for another argument, a continuation of type `char list -> char list`. So we have to give it an "initial continuation" to get started. As mentioned above, we supply *the identity function* as the initial continuation. Why did we choose that? Again, if
+you have already constructed the result list `"ababd"`, what's the desired continuation? What's the next step in the recipe to produce the desired result, i.e, the very same list, `"ababd"`?  Clearly, the identity function.
+
+A good way to test your understanding is to figure out what the
+continuation function `k` must be at the point in the computation when
+`tc` is applied to the argument `"Sd"`.  Two choices: is it
+`fun tail -> 'a'::'b'::tail`, or it is `fun tail -> 'b'::'a'::tail`?  The way to see if you're right is to execute the following command and see what happens:
+
+    tc ['S'; 'd'] (fun tail -> 'a'::'b'::tail);;
+
+There are a number of interesting directions we can go with this task.
+The reason this task was chosen is because the task itself (as opposed
+to the functions used to implement the task) can be viewed as a
+simplified picture of a computation using continuations, where `'S'`
+plays the role of a continuation operator. (It works like the Scheme
+operators `shift` or `control`; the differences between them don't
+manifest themselves in this example.
+See Ken Shan's paper [Shift to control](http://www.cs.rutgers.edu/~ccshan/recur/recur.pdf),
+which inspired some of the discussion in this topic.)
+In the analogy, the input list portrays a
+sequence of functional applications, where `[f1; f2; f3; x]` represents
+`f1(f2(f3 x))`.  The limitation of the analogy is that it is only
+possible to represent computations in which the applications are
+always right-branching, i.e., the computation `((f1 f2) f3) x` cannot
+be directly represented.
+
+One way to extend this exercise would be to add a special symbol `'#'`,
+and then the task would be to copy from the target `'S'` only back to
+the closest `'#'`.  This would allow our task to simulate delimited
+continuations with embedded `prompt`s (also called `reset`s).
+
+The reason the task is well-suited to the list zipper is in part
+because the List monad has an intimate connection with continuations.
+We'll explore this next.
+
+
diff --git a/topics/_list_monad_as_continuation_monad.mdwn b/topics/_list_monad_as_continuation_monad.mdwn
new file mode 100644 (file)
index 0000000..53bbde1
--- /dev/null
@@ -0,0 +1,382 @@
+[[!toc]]
+
+We're going to come at continuations from three different directions, and each
+time we're going to end up at the same place: a particular monad, which we'll
+call the Continuation monad.
+
+Rethinking the List monad
+-------------------------
+
+To construct a monad, the key element is to settle on how to implement its type, and
+the monad more or less naturally follows from that.
+We'll remind you of some examples of how monads follow from their types
+in a moment.  This will involve some review of familiar
+material, but it's worth doing for two reasons: it will set up a
+pattern for the new discussion further below, and it will tie together
+some previously unconnected elements of the course (more specifically,
+version 3 lists and monads).
+
+For instance, take the **Reader monad**.  Once we decide to define its type as:
+
+       type 'a reader = env -> 'a
+
+then the choice of unit and bind is natural:
+
+       let r_unit (a : 'a) : 'a reader = fun (e : env) -> a
+
+The reason this is a fairly natural choice is that because the type of
+an `'a reader` is `env -> 'a` (by definition), the type of the
+`r_unit` function is `'a -> env -> 'a`, which is an instance of the
+type of the **K** combinator.  So it makes sense that **K** is the unit
+for the Reader monad.
+
+Since the type of the `bind` operator is required to be
+
+       r_bind : 'a reader -> ('a -> 'b reader) -> 'b reader
+
+We can reason our way to the traditional reader `bind` function as
+follows. We start by declaring the types determined by the definition
+of a bind operation:
+
+       let r_bind (u : 'a reader) (f : 'a -> 'b reader) : 'b reader = ...
+
+Now we have to open up the `u` box and get out the `'a` object in order to
+feed it to `f`.  Since `u` is a function from environments to
+objects of type `'a`, the way we open a box in this monad is
+by applying it to an environment:
+
+       ... f (u e) ...
+
+This subexpression types to `'b reader`, which is good.  The only
+problem is that we made use of an environment `e` that we didn't already have,
+so we must abstract over that variable to balance the books:
+
+       fun e -> f (u e) ...
+
+[To preview the discussion of the Curry-Howard correspondence, what
+we're doing here is constructing an intuitionistic proof of the type,
+and using the Curry-Howard labeling of the proof as our bind term.]
+
+This types to `env -> 'b reader`, but we want to end up with `env ->
+'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:
+
+       r_bind (u : 'a reader) (f : 'a -> 'b reader) : 'b reader =
+           fun e -> f (u e) e
+
+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.
+
+[The bind we cite here is a condensed version of the careful `let a = u e in ...`
+constructions we provided in earlier lectures.  We use the condensed
+version here in order to emphasize similarities of structure across
+monads.]
+
+The **State monad** is similar.  Once we've decided to use the following type constructor:
+
+       type 'a state = store -> ('a, store)
+
+Then our unit is naturally:
+
+       let s_unit (a : 'a) : 'a state = fun (s : store) -> (a, s)
+
+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:
+
+       let s_bind (u : 'a state) (f : 'a -> 'b state) : 'b state =
+           ... f (...) ...
+
+But unlocking the `u` box is a little more complicated.  As before, we
+need to posit a store `s` that we can apply `u` to.  Once we do so,
+however, we won't have an `'a`; we'll have a pair whose first element
+is an `'a`.  So we have to unpack the pair:
+
+       ... let (a, s') = u s in ... f a ...
+
+Abstracting over the `s` and adjusting the types gives the result:
+
+       let s_bind (u : 'a state) (f : 'a -> 'b state) : 'b state =
+           fun (s : store) -> let (a, s') = u s in f a s'
+
+The **Option/Maybe monad** doesn't follow the same pattern so closely, so we
+won't pause to explore it here, though conceptually its unit and bind
+follow just as naturally from its type constructor.
+
+Our other familiar monad is the **List monad**, which we were told
+looks like this:
+
+       (* type 'a list = ['a];; *)
+       l_unit (a : 'a) = [a];;
+       l_bind u f = List.concat (List.map f u);;
+
+Thinking through the List monad will take a little time, but doing so
+will provide a connection with continuations.
+
+Recall that `List.map` takes a function and a list and returns the
+result of applying the function to the elements of the list:
+
+       List.map (fun i -> [i; i+1]) [1; 2] ~~> [[1; 2]; [2; 3]]
+
+and `List.concat` takes a list of lists and erases one level of embedded list
+boundaries:
+
+       List.concat [[1; 2]; [2; 3]] ~~> [1; 2; 2; 3]
+
+And sure enough,
+
+       l_bind [1; 2] (fun i -> [i; i+1]) ~~> [1; 2; 2; 3]
+
+Now, why this unit, and why this bind?  Well, ideally a unit should
+not throw away information, so we can rule out `fun x -> []` as an
+ideal unit.  And units should not add more information than required,
+so there's no obvious reason to prefer `fun x -> [x; x]`.  In other
+words, `fun x -> [x]` is a reasonable choice for a unit.
+
+As for bind, an `'a list` monadic object contains a lot of objects of
+type `'a`, and we want to make use of each of them (rather than
+arbitrarily throwing some of them away).  The only
+thing we know for sure we can do with an object of type `'a` is apply
+the function of type `'a -> 'b list` to them.  Once we've done so, we
+have a collection of lists, one for each of the `'a`'s.  One
+possibility is that we could gather them all up in a list, so that
+`bind' [1; 2] (fun i -> [i; i]) ~~> [[1; 1]; [2; 2]]`.  But that restricts
+the object returned by the second argument of `bind` to always be of
+type `('something list) list`.  We can eliminate that restriction by flattening
+the list of lists into a single list: this is
+just `List.concat` applied to the output of `List.map`.  So there is some logic to the
+choice of unit and bind for the List monad.
+
+Yet we can still desire to go deeper, and see if the appropriate bind
+behavior emerges from the types, as it did for the previously
+considered monads.  But we can't do that if we leave the list type as
+a primitive OCaml type.  However, we know several ways of implementing
+lists using just functions.  In what follows, we're going to use version
+3 lists, the right fold implementation (though it's important and
+intriguing to wonder how things would change if we used some other
+strategy for implementing lists).  These were the lists that made
+lists look like Church numerals with extra bits embedded in them:
+
+       empty list:                fun f z -> z
+       list with one element:     fun f z -> f 1 z
+       list with two elements:    fun f z -> f 2 (f 1 z)
+       list with three elements:  fun f z -> f 3 (f 2 (f 1 z))
+
+and so on.  To save time, we'll let the OCaml interpreter infer the
+principle types of these functions (rather than inferring what the
+types should be ourselves):
+
+       # fun f z -> z;;
+       - : 'a -> 'b -> 'b = <fun>
+       # fun f z -> f 1 z;;
+       - : (int -> 'a -> 'b) -> 'a -> 'b = <fun>
+       # fun f z -> f 2 (f 1 z);;
+       - : (int -> 'a -> 'a) -> 'a -> 'a = <fun>
+       # fun f z -> f 3 (f 2 (f 1 z))
+       - : (int -> 'a -> 'a) -> 'a -> 'a = <fun>
+
+We can see what the consistent, general principle types are at the end, so we
+can stop. These types should remind you of the simply-typed lambda calculus
+types for Church numerals (`(o -> o) -> o -> o`) with one extra type
+thrown in, the type of the element at the head of the list
+(in this case, an `int`).
+
+So here's our type constructor for our hand-rolled lists:
+
+       type 'b list' = (int -> 'b -> 'b) -> 'b -> 'b
+
+Generalizing to lists that contain any kind of element (not just
+`int`s), we have
+
+       type ('a, 'b) list' = ('a -> 'b -> 'b) -> 'b -> 'b
+
+So an `('a, 'b) list'` is a list containing elements of type `'a`,
+where `'b` is the type of some part of the plumbing.  This is more
+general than an ordinary OCaml list, but we'll see how to map them
+into OCaml lists soon.  We don't need to fully grasp the role of the `'b`s
+in order to proceed to build a monad:
+
+       l'_unit (a : 'a) : ('a, 'b) list = fun a -> fun k z -> k a z
+
+Take an `'a` and return its v3-style singleton. No problem.  Arriving at bind
+is a little more complicated, but exactly the same principles apply, you just
+have to be careful and systematic about it.
+
+       l'_bind (u : ('a, 'b) list') (f : 'a -> ('c, 'd) list') : ('c, 'd) list'  = ...
+
+Unpacking the types gives:
+
+       l'_bind (u : ('a -> 'b -> 'b) -> 'b -> 'b)
+               (f : 'a -> ('c -> 'd -> 'd) -> 'd -> 'd)
+                  : ('c -> 'd -> 'd) -> 'd -> 'd = ...
+
+Perhaps a bit intimidating.
+But it's a rookie mistake to quail before complicated types. You should
+be no more intimidated by complex types than by a linguistic tree with
+deeply embedded branches: complex structure created by repeated
+application of simple rules.
+
+[This would be a good time to try to reason your way to your own term having the type just specified.  Doing so (or attempting to do so) will make the next
+paragraph much easier to follow.]
+
+As usual, we need to unpack the `u` box.  Examine the type of `u`.
+This time, `u` will only deliver up its contents if we give `u` an
+argument that is a function expecting an `'a` and a `'b`. `u` will
+fold that function over its type `'a` members, and that's where we can get at the `'a`s we need. Thus:
+
+       ... u (fun (a : 'a) (b : 'b) -> ... f a ... ) ...
+
+In order for `u` to have the kind of argument it needs, the `fun a b -> ... f a ...` has to have type `'a -> 'b -> 'b`; so 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`:
+
+       ... u (fun (a : 'a) (b : 'b) -> ... f a k ... ) ...
+
+Now the function we're supplying to `u` also receives an argument `b` of type `'b`, so we can supply that to `f a k`, getting a result of type `'b`, as we need:
+
+       ... u (fun (a : 'a) (b : 'b) -> f a k b) ...
+
+Now, we've used a `k` that we pulled out of nowhere, so we need to abstract over it:
+
+       fun (k : 'c -> 'b -> 'b) -> u (fun (a : 'a) (b : 'b) -> f a k b)
+
+This whole expression has type `('c -> 'b -> 'b) -> 'b -> 'b`, which is exactly the type of a `('c, 'b) list'`. So we can hypothesize that our bind is:
+
+       l'_bind (u : ('a -> 'b -> 'b) -> 'b -> 'b)
+               (f : 'a -> ('c -> 'b -> 'b) -> 'b -> 'b)
+                  : ('c -> 'b -> 'b) -> 'b -> 'b =
+           fun k -> u (fun a b -> f a k b)
+
+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.
+
+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:
+
+       fun k z -> u (fun a b -> f a k b) z
+
+Now let's think about what this does. It's a wrapper around `u`. In order to behave as the list `v` 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 `v` would.
+Will it?
+
+Suppose we have a list' whose contents are `[1; 2; 4; 8]`---that is, our list' `u` will be `fun f z -> f 1 (f 2 (f 4 (f 8 z)))`. 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:
+
+       v =
+       List.concat (List.map f u) =
+       List.concat [[]; [2]; [2; 4]; [2; 4; 8]] =
+       [2; 2; 4; 2; 4; 8]
+
+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. Does our formula
+
+       fun k z -> u (fun a b -> f a k b) z
+
+do that? Well, for each element `a` in `u`, it applies `f` to that `a`, getting one of the lists:
+
+       []        ; result of applying f to leftmost a
+       [2]
+       [2; 4]
+       [2; 4; 8] ; result of applying f to rightmost a
+
+(or rather, their list' versions). Then it takes the accumulated result `b` of previous steps in the `k`,`z`-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 of the `k`,`z`-fold as the new accumulated result `b`.
+
+So if, for example, we let `k` be `+` and `z` be `0`, then the computation would proceed:
+
+       0 ==>
+       right-fold + and 0 over [2; 4; 8] = 2+4+8+(0) ==>
+       right-fold + and 2+4+8+0 over [2; 4] = 2+4+(2+4+8+(0)) ==>
+       right-fold + and 2+4+2+4+8+0 over [2] = 2+(2+4+(2+4+8+(0))) ==>
+       right-fold + and 2+2+4+2+4+8+0 over [] = 2+(2+4+(2+4+8+(0)))
+
+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:
+
+       fun k z -> u (fun a b -> f a k b) z
+
+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
+
+       fun k z -> List.fold_right k v z =
+       fun k z -> List.fold_right k (List.concat (List.map f u)) z
+
+would.
+
+For future reference, we might make two eta-reductions to our formula, so that we have instead:
+
+       let l'_bind = fun k -> u (fun a -> f a k);;
+
+Let's make some more tests:
+
+       # l_bind [1; 2] (fun i -> [i; i+1]);;
+       - : int list = [1; 2; 2; 3]
+       
+       # l'_bind (fun f z -> f 1 (f 2 z)) (fun i -> fun f z -> f i (f (i+1) z));;
+       - : (int -> '_a -> '_a) -> '_a -> '_a = <fun>
+
+Sigh.  OCaml won't show us our own list.  So we have to choose an `f`
+and a `z` that will turn our hand-crafted lists into standard OCaml
+lists, so that they will print out.
+
+       # let cons h t = h :: t;;  (* OCaml is stupid about :: *)
+       # l'_bind (fun f z -> f 1 (f 2 z)) (fun i -> fun f z -> f i (f (i+1) z)) cons [];;
+       - : int list = [1; 2; 2; 3]
+
+Ta da!
+
+
+Montague's PTQ treatment of DPs as generalized quantifiers
+----------------------------------------------------------
+
+We've hinted that Montague's treatment of DPs as generalized
+quantifiers embodies the spirit of continuations (see de Groote 2001,
+Barker 2002 for lengthy discussion).  Let's see why.
+
+First, we'll need a type constructor.  As we've said,
+Montague replaced individual-denoting determiner phrases (with type `e`)
+with generalized quantifiers (with [extensional] type `(e -> t) -> t`.
+In particular, the denotation of a proper name like *John*, which
+might originally denote a object `j` of type `e`, came to denote a
+generalized quantifier `fun pred -> pred j` of type `(e -> t) -> t`.
+Let's write a general function that will map individuals into their
+corresponding generalized quantifier:
+
+       gqize (a : e) = fun (p : e -> t) -> p a
+
+This function is what Partee 1987 calls LIFT, which is not an unreasonable name. But we will avoid her term here, since that word has been used to refer to other functions in our discussion.
+
+This function wraps up an individual in a box.  That is to say,
+we are in the presence of a monad.  The type constructor, the unit and
+the bind follow naturally.  We've done this enough times that we won't
+belabor the construction of the bind function. The derivation is
+highly similar to the List monad just given:
+
+       type 'a continuation = ('a -> 'b) -> 'b
+       let c_unit (a : 'a) = fun (p : 'a -> 'b) -> p a
+       let c_bind (u : ('a -> 'b) -> 'b) (f : 'a -> ('c -> 'd) -> 'd) : ('c -> 'd) -> 'd =
+           fun (k : 'a -> 'b) -> u (fun (a : 'a) -> f a k)
+
+Note that `c_unit` is exactly the `gqize` function that Montague used
+to lift individuals into generalized quantifiers.
+
+That last bit in `c_bind` looks familiar---we just saw something like
+it in the List monad.  How similar is it to the List monad?  Let's
+examine the type constructor and the terms from the list monad derived
+above:
+
+       type ('a, 'b) list' = ('a -> 'b -> 'b) -> 'b -> 'b;;
+               (* that is of the form ('a -> 'r) -> 'r, where 'r = 'b -> 'b *)
+       let l'_unit a = fun k z -> k a z;;
+
+This can be eta-reduced to:
+
+       let l'_unit a = fun k -> k a
+
+and:
+
+       let l'_bind u f =
+           (* we mentioned three versions of this, the eta-expanded: *)
+           fun k z -> u (fun a b -> f a k b) z
+               (* an intermediate version, and the fully eta-reduced: *)
+           fun k -> u (fun a -> f a k)
+
+Consider the most eta-reduced versions of `l'_unit` and `l'_bind`. They're the same as the unit and bind for the Montague Continuation monad! In other words, the behavior of our v3-List monad and the behavior of the continuations monad are
+parallel in a deep sense.
+
+Have we really discovered that lists are secretly continuations?  Or
+have we merely found a way of simulating lists using list
+continuations?  Well, strictly speaking, what we have done is shown
+that one particular implementation of lists---the right fold
+implementation---gives rise to a Continuation monad fairly naturally,
+and that this monad can reproduce the behavior of the standard list
+monad.  But what about other list implementations?  Do they give rise
+to monads that can be understood in terms of continuations?
+
+
diff --git a/topics/_manipulating_trees_with_monads.mdwn b/topics/_manipulating_trees_with_monads.mdwn
new file mode 100644 (file)
index 0000000..0d9e33d
--- /dev/null
@@ -0,0 +1,546 @@
+[[!toc]]
+
+Manipulating trees with monads
+------------------------------
+
+This topic develops an idea based on a suggestion of Ken Shan's.
+We'll build a series of functions that operate on trees, doing various
+things, including updating leaves with a Reader monad, counting nodes
+with a State monad, copying the tree with a List monad, and converting
+a tree into a list of leaves with a Continuation monad.  It will turn
+out that the continuation monad can simulate the behavior of each of
+the other monads.
+
+From an engineering standpoint, we'll build a tree machine that
+deals in monads.  We can modify the behavior of the system by swapping
+one monad for another.  We've already seen how adding a monad can add
+a layer of funtionality without disturbing the underlying system, for
+instance, in the way that the Reader monad allowed us to add a layer
+of intensionality to an extensional grammar. But we have not yet seen
+the utility of replacing one monad with other.
+
+First, we'll be needing a lot of trees for the remainder of the
+course.  Here again is a type constructor for leaf-labeled, binary trees:
+
+    type 'a tree = Leaf of 'a | Node of ('a tree * 'a tree);;
+
+[How would you adjust the type constructor to allow for labels on the
+internal nodes?]
+
+We'll be using trees where the nodes are integers, e.g.,
+
+
+       let t1 = Node (Node (Leaf 2, Leaf 3),
+                      Node (Leaf 5, Node (Leaf 7,
+                                           Leaf 11)))
+           .
+        ___|___
+        |     |
+        .     .
+       _|_   _|__
+       |  |  |  |
+       2  3  5  .
+               _|__
+               |  |
+               7  11
+
+Our first task will be to replace each leaf with its double:
+
+       let rec tree_map (leaf_modifier : 'a -> 'b) (t : 'a tree) : 'b tree =
+         match t with
+           | Leaf i -> Leaf (leaf_modifier i)
+           | Node (l, r) -> Node (tree_map leaf_modifier l,
+                                  tree_map leaf_modifier r);;
+
+`tree_map` takes a tree and a function that transforms old leaves into
+new leaves, and maps that function over all the leaves in the tree,
+leaving the structure of the tree unchanged.  For instance:
+
+       let double i = i + i;;
+       tree_map double t1;;
+       - : int tree =
+       Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
+       
+           .
+        ___|____
+        |      |
+        .      .
+       _|__  __|__
+       |  |  |   |
+       4  6  10  .
+               __|___
+               |    |
+               14   22
+
+We could have built the doubling operation right into the `tree_map`
+code.  However, because we've made what to do to each leaf a
+parameter, we can decide to do something else to the leaves without
+needing to rewrite `tree_map`.  For instance, we can easily square
+each leaf instead, by supplying the appropriate `int -> int` operation
+in place of `double`:
+
+       let square i = i * i;;
+       tree_map square t1;;
+       - : int tree =
+       Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
+
+Note that what `tree_map` does is take some unchanging contextual
+information---what to do to each leaf---and supplies that information
+to each subpart of the computation.  In other words, `tree_map` has the
+behavior of a Reader monad.  Let's make that explicit.
+
+In general, we're on a journey of making our `tree_map` function more and
+more flexible.  So the next step---combining the tree transformer with
+a Reader monad---is to have the `tree_map` function return a (monadized)
+tree that is ready to accept any `int -> int` function and produce the
+updated tree.
+
+       fun e ->    .
+              _____|____
+              |        |
+              .        .
+            __|___   __|___
+            |    |   |    |
+           e 2  e 3  e 5  .
+                        __|___
+                        |    |
+                       e 7  e 11
+
+That is, we want to transform the ordinary tree `t1` (of type `int
+tree`) into a reader monadic object of type `(int -> int) -> int
+tree`: something that, when you apply it to an `int -> int` function
+`e` returns an `int tree` in which each leaf `i` has been replaced
+with `e i`.
+
+[Application note: this kind of reader object could provide a model
+for Kaplan's characters.  It turns an ordinary tree into one that
+expects contextual information (here, the `e`) that can be
+used to compute the content of indexicals embedded arbitrarily deeply
+in the tree.]
+
+With our previous applications of the Reader monad, we always knew
+which kind of environment to expect: either an assignment function, as
+in the original calculator simulation; a world, as in the
+intensionality monad; an individual, as in the Jacobson-inspired link
+monad; etc.  In the present case, we expect that our "environment"
+will be some function of type `int -> int`. "Looking up" some `int` in
+the environment will return us the `int` that comes out the other side
+of that function.
+
+       type 'a reader = (int -> int) -> 'a;;
+       let reader_unit (a : 'a) : 'a reader = fun _ -> a;;
+       let reader_bind (u: 'a reader) (f : 'a -> 'b reader) : 'b reader =
+         fun e -> f (u e) e;;
+
+It would be a simple matter to turn an *integer* into an `int reader`:
+
+       let asker : int -> int reader =
+         fun (a : int) ->
+           fun (modifier : int -> int) -> modifier a;;
+       asker 2 (fun i -> i + i);;
+       - : int = 4
+
+`asker a` is a monadic box that waits for an an environment (here, the argument `modifier`) and returns what that environment maps `a` to.
+
+How do we do the analagous transformation when our `int`s are scattered over the leaves of a tree? How do we turn an `int tree` into a reader?
+A tree is not the kind of thing that we can apply a
+function of type `int -> int` to.
+
+But we can do this:
+
+       let rec tree_monadize (f : 'a -> 'b reader) (t : 'a tree) : 'b tree reader =
+           match t with
+           | Leaf a -> reader_bind (f a) (fun b -> reader_unit (Leaf b))
+           | Node (l, r) -> reader_bind (tree_monadize f l) (fun l' ->
+                              reader_bind (tree_monadize f r) (fun r' ->
+                                reader_unit (Node (l', r'))));;
+
+This function says: give me a function `f` that knows how to turn
+something of type `'a` into an `'b reader`---this is a function of the same type that you could bind an `'a reader` to, such as `asker` or `reader_unit`---and I'll show you how to
+turn an `'a tree` into an `'b tree reader`.  That is, if you show me how to do this:
+
+                     ------------
+         1     --->  |    1     |
+                     ------------
+
+then I'll give you back the ability to do this:
+
+                     ____________
+         .           |    .     |
+       __|___  --->  |  __|___  |
+       |    |        |  |    |  |
+       1    2        |  1    2  |
+                     ------------
+
+And how will that boxed tree behave? Whatever actions you perform on it will be transmitted down to corresponding operations on its leaves. For instance, our `int reader` expects an `int -> int` environment. If supplying environment `e` to our `int reader` doubles the contained `int`:
+
+                     ------------
+         1     --->  |    1     |  applied to e  ~~>  2
+                     ------------
+
+Then we can expect that supplying it to our `int tree reader` will double all the leaves:
+
+                     ____________
+         .           |    .     |                      .
+       __|___  --->  |  __|___  | applied to e  ~~>  __|___
+       |    |        |  |    |  |                    |    |
+       1    2        |  1    2  |                    2    4
+                     ------------
+
+In more fanciful terms, the `tree_monadize` function builds plumbing that connects all of the leaves of a tree into one connected monadic network; it threads the
+`'b reader` monad through the original tree's leaves.
+
+       # tree_monadize asker t1 double;;
+       - : int tree =
+       Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
+
+Here, our environment is the doubling function (`fun i -> i + i`).  If
+we apply the very same `int tree reader` (namely, `tree_monadize
+asker t1`) to a different `int -> int` function---say, the
+squaring function, `fun i -> i * i`---we get an entirely different
+result:
+
+       # tree_monadize asker t1 square;;
+       - : int tree =
+       Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
+
+Now that we have a tree transformer that accepts a *reader* monad as a
+parameter, we can see what it would take to swap in a different monad.
+
+For instance, we can use a State monad to count the number of leaves in
+the tree.
+
+       type 'a state = int -> 'a * int;;
+       let state_unit a = fun s -> (a, s);;
+       let state_bind u f = fun s -> let (a, s') = u s in f a s';;
+
+Gratifyingly, we can use the `tree_monadize` function without any
+modification whatsoever, except for replacing the (parametric) type
+`'b reader` with `'b state`, and substituting in the appropriate unit and bind:
+
+       let rec tree_monadize (f : 'a -> 'b state) (t : 'a tree) : 'b tree state =
+           match t with
+           | Leaf a -> state_bind (f a) (fun b -> state_unit (Leaf b))
+           | Node (l, r) -> state_bind (tree_monadize f l) (fun l' ->
+                              state_bind (tree_monadize f r) (fun r' ->
+                                state_unit (Node (l', r'))));;
+
+Then we can count the number of leaves in the tree:
+
+       # let incrementer = fun a ->
+           fun s -> (a, s+1);;
+       
+       # tree_monadize incrementer t1 0;;
+       - : int tree * int =
+       (Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11))), 5)
+       
+               .
+            ___|___
+            |     |
+            .     .
+        (  _|__  _|__     ,   5 )
+           |  |  |  |
+           2  3  5  .
+                   _|__
+                   |  |
+                   7  11
+
+Note that the value returned is a pair consisting of a tree and an
+integer, 5, which represents the count of the leaves in the tree.
+
+Why does this work? Because the operation `incrementer`
+takes an argument `a` and wraps it in an State monadic box that
+increments the store and leaves behind a wrapped `a`. When we give that same operations to our
+`tree_monadize` function, it then wraps an `int tree` in a box, one
+that does the same store-incrementing for each of its leaves.
+
+We can use the state monad to annotate leaves with a number
+corresponding to that leave's ordinal position.  When we do so, we
+reveal the order in which the monadic tree forces evaluation:
+
+       # tree_monadize (fun a -> fun s -> ((a,s+1), s+1)) t1 0;;
+       - : int tree * int =
+         (Node
+           (Node (Leaf (2, 1), Leaf (3, 2)),
+            Node
+             (Leaf (5, 3),
+              Node (Leaf (7, 4), Leaf (11, 5)))),
+         5)
+
+The key thing to notice is that instead of just wrapping `a` in the
+monadic box, we wrap a pair of `a` and the current store.
+
+Reversing the annotation order requires reversing the order of the `state_bind`
+operations.  It's not obvious that this will type correctly, so think
+it through:
+
+       let rec tree_monadize_rev (f : 'a -> 'b state) (t : 'a tree) : 'b tree state =
+         match t with
+           | Leaf a -> state_bind (f a) (fun b -> state_unit (Leaf b))
+           | Node (l, r) -> state_bind (tree_monadize f r) (fun r' ->     (* R first *)
+                              state_bind (tree_monadize f l) (fun l'->    (* Then L  *)
+                                state_unit (Node (l', r'))));;
+       
+       # tree_monadize_rev (fun a -> fun s -> ((a,s+1), s+1)) t1 0;;
+       - : int tree * int =
+         (Node
+           (Node (Leaf (2, 5), Leaf (3, 4)),
+            Node
+             (Leaf (5, 3),
+              Node (Leaf (7, 2), Leaf (11, 1)))),
+         5)
+
+Later, we will talk more about controlling the order in which nodes are visited.
+
+One more revealing example before getting down to business: replacing
+`state` everywhere in `tree_monadize` with `list` lets us do:
+
+       # let decider i = if i = 2 then [20; 21] else [i];;
+       # tree_monadize decider t1;;
+       - : int tree List_monad.m =
+       [
+         Node (Node (Leaf 20, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11)));
+         Node (Node (Leaf 21, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11)))
+       ]
+
+
+Unlike the previous cases, instead of turning a tree into a function
+from some input to a result, this monadized tree gives us back a list of trees,
+one for each choice of `int`s for its leaves.
+
+Now for the main point.  What if we wanted to convert a tree to a list
+of leaves?
+
+       type ('r,'a) continuation = ('a -> 'r) -> 'r;;
+       let continuation_unit a = fun k -> k a;;
+       let continuation_bind u f = fun k -> u (fun a -> f a k);;
+       
+       let rec tree_monadize (f : 'a -> ('r,'b) continuation) (t : 'a tree) : ('r,'b tree) continuation =
+           match t with
+           | Leaf a -> continuation_bind (f a) (fun b -> continuation_unit (Leaf b))
+           | Node (l, r) -> continuation_bind (tree_monadize f l) (fun l' ->
+                              continuation_bind (tree_monadize f r) (fun r' ->
+                                continuation_unit (Node (l', r'))));;
+
+We use the Continuation monad described above, and insert the
+`continuation` type in the appropriate place in the `tree_monadize` code. Then if we give the `tree_monadize` function an operation that converts `int`s into `'b`-wrapping Continuation monads, it will give us back a way to turn `int tree`s into corresponding `'b tree`-wrapping Continuation monads.
+
+So for example, we compute:
+
+       # tree_monadize (fun a k -> a :: k ()) t1 (fun _ -> []);;
+       - : int list = [2; 3; 5; 7; 11]
+
+We have found a way of collapsing a tree into a list of its
+leaves. Can you trace how this is working? Think first about what the
+operation `fun a k -> a :: k a` does when you apply it to a
+plain `int`, and the continuation `fun _ -> []`. Then given what we've
+said about `tree_monadize`, what should we expect `tree_monadize (fun
+a -> fun k -> a :: k a)` to do?
+
+Soon we'll return to the same-fringe problem.  Since the
+simple but inefficient way to solve it is to map each tree to a list
+of its leaves, this transformation is on the path to a more efficient
+solution.  We'll just have to figure out how to postpone computing the
+tail of the list until it's needed...
+
+The Continuation monad is amazingly flexible; we can use it to
+simulate some of the computations performed above.  To see how, first
+note that an interestingly uninteresting thing happens if we use
+`continuation_unit` as our first argument to `tree_monadize`, and then
+apply the result to the identity function:
+
+       # tree_monadize continuation_unit t1 (fun t -> t);;
+       - : int tree =
+       Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11)))
+
+That is, nothing happens.  But we can begin to substitute more
+interesting functions for the first argument of `tree_monadize`:
+
+       (* Simulating the tree reader: distributing a operation over the leaves *)
+       # tree_monadize (fun a -> fun k -> k (square a)) t1 (fun t -> t);;
+       - : int tree =
+       Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
+
+       (* Counting leaves *)
+       # tree_monadize (fun a -> fun k -> 1 + k a) t1 (fun t -> 0);;
+       - : int = 5
+
+It's not immediately obvious to us how to simulate the List monadization of the tree using this technique.
+
+We could simulate the tree annotating example by setting the relevant 
+type to `(store -> 'result, 'a) continuation`.
+
+Andre Filinsky has proposed that the continuation monad is
+able to simulate any other monad (Google for "mother of all monads").
+
+If you want to see how to parameterize the definition of the `tree_monadize` function, so that you don't have to keep rewriting it for each new monad, see [this code](/code/tree_monadize.ml).
+
+The idea of using continuations to characterize natural language meaning
+------------------------------------------------------------------------
+
+We might a philosopher or a linguist be interested in continuations,
+especially if efficiency of computation is usually not an issue?
+Well, the application of continuations to the same-fringe problem
+shows that continuations can manage order of evaluation in a
+well-controlled manner.  In a series of papers, one of us (Barker) and
+Ken Shan have argued that a number of phenomena in natural langauge
+semantics are sensitive to the order of evaluation.  We can't
+reproduce all of the intricate arguments here, but we can give a sense
+of how the analyses use continuations to achieve an analysis of
+natural language meaning.
+
+**Quantification and default quantifier scope construal**.  
+
+We saw in the copy-string example ("abSd") and in the same-fringe example that
+local properties of a structure (whether a character is `'S'` or not, which
+integer occurs at some leaf position) can control global properties of
+the computation (whether the preceeding string is copied or not,
+whether the computation halts or proceeds).  Local control of
+surrounding context is a reasonable description of in-situ
+quantification.
+
+    (1) John saw everyone yesterday.
+
+This sentence means (roughly)
+
+    forall x . yesterday(saw x) john
+
+That is, the quantifier *everyone* contributes a variable in the
+direct object position, and a universal quantifier that takes scope
+over the whole sentence.  If we have a lexical meaning function like
+the following:
+
+       let lex (s:string) k = match s with 
+         | "everyone" -> Node (Leaf "forall x", k "x")
+         | "someone" -> Node (Leaf "exists y", k "y")
+         | _ -> k s;;
+
+Then we can crudely approximate quantification as follows:
+
+       # let sentence1 = Node (Leaf "John", 
+                                                 Node (Node (Leaf "saw", 
+                                                                         Leaf "everyone"), 
+                                                               Leaf "yesterday"));;
+
+       # tree_monadize lex sentence1 (fun x -> x);;
+       - : string tree =
+       Node
+        (Leaf "forall x",
+         Node (Leaf "John", Node (Node (Leaf "saw", Leaf "x"), Leaf "yesterday")))
+
+In order to see the effects of evaluation order, 
+observe what happens when we combine two quantifiers in the same
+sentence:
+
+       # let sentence2 = Node (Leaf "everyone", Node (Leaf "saw", Leaf "someone"));;
+       # tree_monadize lex sentence2 (fun x -> x);;
+       - : string tree =
+       Node
+        (Leaf "forall x",
+         Node (Leaf "exists y", Node (Leaf "x", Node (Leaf "saw", Leaf "y"))))
+
+The universal takes scope over the existential.  If, however, we
+replace the usual `tree_monadizer` with `tree_monadizer_rev`, we get
+inverse scope:
+
+       # tree_monadize_rev lex sentence2 (fun x -> x);;
+       - : string tree =
+       Node
+        (Leaf "exists y",
+         Node (Leaf "forall x", Node (Leaf "x", Node (Leaf "saw", Leaf "y"))))
+
+There are many crucially important details about quantification that
+are being simplified here, and the continuation treatment used here is not
+scalable for a number of reasons.  Nevertheless, it will serve to give
+an idea of how continuations can provide insight into the behavior of
+quantifiers.
+
+
+The Tree monad
+==============
+
+Of course, by now you may have realized that we are working with a new
+monad, the binary, leaf-labeled Tree monad.  Just as mere lists are in fact a monad,
+so are trees.  Here is the type constructor, unit, and bind:
+
+       type 'a tree = Leaf of 'a | Node of ('a tree) * ('a tree);;
+       let tree_unit (a: 'a) : 'a tree = Leaf a;;
+       let rec tree_bind (u : 'a tree) (f : 'a -> 'b tree) : 'b tree =
+           match u with
+           | Leaf a -> f a
+           | Node (l, r) -> Node (tree_bind l f, tree_bind r f);;
+
+For once, let's check the Monad laws.  The left identity law is easy:
+
+    Left identity: bind (unit a) f = bind (Leaf a) f = f a
+
+To check the other two laws, we need to make the following
+observation: it is easy to prove based on `tree_bind` by a simple
+induction on the structure of the first argument that the tree
+resulting from `bind u f` is a tree with the same strucure as `u`,
+except that each leaf `a` has been replaced with the tree returned by `f a`:
+
+                       .                         .
+                     __|__                     __|__
+                     |   |                    /\   |
+                     a1  .                   f a1  .
+                        _|__                     __|__
+                        |  |                     |   /\
+                        .  a5                    .  f a5
+          bind         _|__       f   =        __|__
+                       |  |                    |   /\
+                       .  a4                   .  f a4
+                     __|__                   __|___
+                     |   |                  /\    /\
+                     a2  a3                f a2  f a3
+
+Given this equivalence, the right identity law
+
+       Right identity: bind u unit = u
+
+falls out once we realize that
+
+       bind (Leaf a) unit = unit a = Leaf a
+
+As for the associative law,
+
+       Associativity: bind (bind u f) g = bind u (\a. bind (f a) g)
+
+we'll give an example that will show how an inductive proof would
+proceed.  Let `f a = Node (Leaf a, Leaf a)`.  Then
+
+                                                  .
+                                              ____|____
+                 .               .            |       |
+       bind    __|__   f  =    __|_    =      .       .
+               |   |           |   |        __|__   __|__
+               a1  a2        f a1 f a2      |   |   |   |
+                                            a1  a1  a1  a1
+
+Now when we bind this tree to `g`, we get
+
+                   .
+              _____|______
+              |          |
+              .          .
+            __|__      __|__
+            |   |      |   |
+          g a1 g a1  g a1 g a1
+
+At this point, it should be easy to convince yourself that
+using the recipe on the right hand side of the associative law will
+build the exact same final tree.
+
+So binary trees are a monad.
+
+Haskell combines this monad with the Option monad to provide a monad
+called a
+[SearchTree](http://hackage.haskell.org/packages/archive/tree-monad/0.2.1/doc/html/src/Control-Monad-SearchTree.html#SearchTree)
+that is intended to represent non-deterministic computations as a tree.
+
+
+What's this have to do with tree\_monadize?
+--------------------------------------------
+
+Our different implementations of `tree_monadize` above were different *layerings* of the Tree monad with other monads (Reader, State, List, and Continuation). We'll explore that further here: [[Monad Transformers]].
+
diff --git a/topics/week12_abortable_traversals b/topics/week12_abortable_traversals
new file mode 100644 (file)
index 0000000..6976a51
--- /dev/null
@@ -0,0 +1,359 @@
+#Aborting a search through a list#
+
+We said that the sorted-list implementation of a set was more efficient than
+the unsorted-list implementation, because as you were searching through the
+list, you could come to a point where you knew the element wasn't going to be
+found. So you wouldn't have to continue the search.
+
+If your implementation of lists was, say v1 lists plus the Y-combinator, then
+this is exactly right. When you get to a point where you know the answer, you
+can just deliver that answer, and not branch into any further recursion. If
+you've got the right evaluation strategy in place, everything will work out
+fine.
+
+But what if we wanted to use v3 lists instead?
+
+>      Why would we want to do that? The advantage of the v3 lists and v3 (aka
+"Church") numerals is that they have their recursive capacity built into their
+very bones. So for many natural operations on them, you won't need to use a fixed
+point combinator.
+
+>      Why is that an advantage? Well, if you use a fixed point combinator, then
+the terms you get won't be strongly normalizing: whether their reduction stops
+at a normal form will depend on what evaluation order you use. Our online
+[[lambda evaluator]] uses normal-order reduction, so it finds a normal form if
+there's one to be had. But if you want to build lambda terms in, say, Scheme,
+and you wanted to roll your own recursion as we've been doing, rather than
+relying on Scheme's native `let rec` or `define`, then you can't use the
+fixed-point combinators `Y` or <code>&Theta;</code>. Expressions using them
+will have non-terminating reductions, with Scheme's eager/call-by-value
+strategy. There are other fixed-point combinators you can use with Scheme (in
+the [week 3 notes](/week3/#index7h2) they were <code>Y&prime;</code> and
+<code>&Theta;&prime;</code>. But even with them, evaluation order still
+matters: for some (admittedly unusual) evaluation strategies, expressions using
+them will also be non-terminating.
+
+>      The fixed-point combinators may be the conceptual stars. They are cool and
+mathematically elegant. But for efficiency and implementation elegance, it's
+best to know how to do as much as you can without them. (Also, that knowledge
+could carry over to settings where the fixed point combinators are in principle
+unavailable.)
+
+
+So again, what if we're using v3 lists? What options would we have then for
+aborting a search or list traversal before it runs to completion?
+
+Suppose we're searching through the list `[5;4;3;2;1]` to see if it
+contains the number `3`. The expression which represents this search would have
+something like the following form:
+
+       ..................<eq? 1 3>  ~~>
+       .................. false     ~~>
+       .............<eq? 2 3>       ~~>
+       ............. false          ~~>
+       .........<eq? 3 3>           ~~>
+       ......... true               ~~>
+       ?
+
+Of course, whether those reductions actually followed in that order would
+depend on what reduction strategy was in place. But the result of folding the
+search function over the part of the list whose head is `3` and whose tail is `[2;
+1]` will *semantically* depend on the result of applying that function to the
+more rightmost pieces of the list, too, regardless of what order the reduction
+is computed by. Conceptually, it will be easiest if we think of the reduction
+happening in the order displayed above.
+
+Once we've found a match between our sought number `3` and some member of
+the list, we'd like to avoid any further unnecessary computations and just
+deliver the answer `true` as "quickly" or directly as possible to the larger
+computation in which the search was embedded.
+
+With a Y-combinator based search, as we said, we could do this by just not
+following a recursion branch.
+
+But with the v3 lists, the fold is "pre-programmed" to continue over the whole
+list. There is no way for us to bail out of applying the search function to the
+parts of the list that have head `4` and head `5`, too.
+
+We *can* avoid *some* unneccessary computation. The search function can detect
+that the result we've accumulated so far during the fold is now `true`, so we
+don't need to bother comparing `4` or `5` to `3` for equality. That will simplify the
+computation to some degree, since as we said, numerical comparison in the
+system we're working in is moderately expensive.
+
+However, we're still going to have to traverse the remainder of the list. That
+`true` result will have to be passed along all the way to the leftmost head of
+the list. Only then can we deliver it to the larger computation in which the
+search was embedded.
+
+It would be better if there were some way to "abort" the list traversal. If,
+having found the element we're looking for (or having determined that the
+element isn't going to be found), we could just immediately stop traversing the
+list with our answer. **Continuations** will turn out to let us do that.
+
+We won't try yet to fully exploit the terrible power of continuations. But
+there's a way that we can gain their benefits here locally, without yet having
+a fully general machinery or understanding of what's going on.
+
+The key is to recall how our implementations of booleans and pairs worked.
+Remember that with pairs, we supply the pair "handler" to the pair as *an
+argument*, rather than the other way around:
+
+       pair (\x y. add x y)
+
+or:
+
+       pair (\x y. x)
+
+to get the first element of the pair. Of course you can lift that if you want:
+
+<pre><code>extract_fst &equiv; \pair. pair (\x y. x)</code></pre>
+
+but at a lower level, the pair is still accepting its handler as an argument,
+rather than the handler taking the pair as an argument. (The handler gets *the
+pair's elements*, not the pair itself, as arguments.)
+
+>      *Terminology*: we'll try to use names of the form `get_foo` for handlers, and
+names of the form `extract_foo` for lifted versions of them, that accept the
+lists (or whatever data structure we're working with) as arguments. But we may
+sometimes forget.
+
+The v2 implementation of lists followed a similar strategy:
+
+       v2list (\h t. do_something_with_h_and_t) result_if_empty
+
+If the `v2list` here is not empty, then this will reduce to the result of
+supplying the list's head and tail to the handler `(\h t.
+do_something_with_h_and_t)`.
+
+Now, what we've been imagining ourselves doing with the search through the v3
+list is something like this:
+
+
+       larger_computation (search_through_the_list_for_3) other_arguments
+
+That is, the result of our search is supplied as an argument (perhaps together
+with other arguments) to the "larger computation". Without knowing the
+evaluation order/reduction strategy, we can't say whether the search is
+evaluated before or after it's substituted into the larger computation. But
+semantically, the search is the argument and the larger computation is the
+function to which it's supplied.
+
+What if, instead, we did the same kind of thing we did with pairs and v2
+lists? That is, what if we made the larger computation a "handler" that we
+passed as an argument to the search?
+
+       the_search (\search_result. larger_computation search_result other_arguments)
+
+What's the advantage of that, you say. Other than to show off how cleverly
+you can lift.
+
+Well, think about it. Think about the difficulty we were having aborting the
+search. Does this switch-around offer us anything useful?
+
+It could.
+
+What if the way we implemented the search procedure looked something like this?
+
+At a given stage in the search, we wouldn't just apply some function `f` to the
+head at this stage and the result accumulated so far (from folding the same
+function, and a base value, to the tail at this stage)...and then pass the result
+of that application to the embedding, more leftward computation.
+
+We'd *instead* give `f` a "handler" that expects the result of the current
+stage *as an argument*, and then evaluates to what you'd get by passing that
+result leftwards up the list, as before. 
+
+Why would we do that, you say? Just more flamboyant lifting?
+
+Well, no, there's a real point here. If we give the function a "handler" that
+encodes the normal continuation of the fold leftwards through the list, we can
+also give it other "handlers" too. For example, we can also give it the underlined handler:
+
+
+       the_search (\search_result. larger_computation search_result other_arguments)
+                          ------------------------------------------------------------------
+
+This "handler" encodes the search's having finished, and delivering a final
+answer to whatever else you wanted your program to do with the result of the
+search. If you like, at any stage in the search you might just give an argument
+to *this* handler, instead of giving an argument to the handler that continues
+the list traversal leftwards. Semantically, this would amount to *aborting* the
+list traversal! (As we've said before, whether the rest of the list traversal
+really gets evaluated will depend on what evaluation order is in place. But
+semantically we'll have avoided it. Our larger computation  won't depend on the
+rest of the list traversal having been computed.)
+
+Do you have the basic idea? Think about how you'd implement it. A good
+understanding of the v2 lists will give you a helpful model.
+
+In broad outline, a single stage of the search would look like before, except
+now `f` would receive two extra, "handler" arguments. We'll reserve the name `f` for the original fold function, and use `f2` for the function that accepts two additional handler arguments. To get the general idea, you can regard these as interchangeable. If the extra precision might help, then you can pay attention to when we're talking about the handler-taking `f2` or the original `f`. You'll only be *supplying* the `f2` function; the idea will be that the behavior of the original `f` will be implicitly encoded in `f2`'s behavior.
+
+       f2 3 <sofar value that would have resulted from folding f and z over [2; 1]> <handler to continue folding leftwards> <handler to abort the traversal>
+
+`f2`'s job would be to check whether `3` matches the element we're searching for
+(here also `3`), and if it does, just evaluate to the result of passing `true` to
+the abort handler. If it doesn't, then evaluate to the result of passing
+`false` to the continue-leftwards handler.
+
+In this case, `f2` wouldn't need to consult the result of folding `f` and `z`
+over `[2; 1]`, since if we had found the element `3` in more rightward
+positions of the list, we'd have called the abort handler and this application
+of `f2` to `3` etc would never be needed. However, in other applications the
+result of folding `f` and `z` over the more rightward parts of the list would
+be needed. Consider if you were trying to multiply all the elements of the
+list, and were going to abort (with the result `0`) if you came across any
+element in the list that was zero. If you didn't abort, you'd need to know what
+the more rightward elements of the list multiplied to, because that would
+affect the answer you passed along to the continue-leftwards handler.
+
+A **version 5** list encodes the kind of fold operation we're envisaging here,
+in the same way that v3 (and [v4](/advanced_lambda/#index1h1)) lists encoded
+the simpler fold operation. Roughly, the list `[5;4;3;2;1]` would look like
+this:
+
+
+       \f2 z continue_leftwards_handler abort_handler.
+               <fold f2 and z over [4;3;2;1]>
+               (\result_of_folding_over_4321. f2 5 result_of_folding_over_4321  continue_leftwards_handler abort_handler)
+               abort_handler
+
+       ; or, expanding the fold over [4;3;2;1]:
+
+       \f2 z continue_leftwards_handler abort_handler.
+               (\continue_leftwards_handler abort_handler.
+                       <fold f2 and z over [3;2;1]>
+                       (\result_of_folding_over_321. f2 4 result_of_folding_over_321 continue_leftwards_handler abort_handler)
+                       abort_handler
+               )
+               (\result_of_folding_over_4321. f2 5 result_of_folding_over_4321  continue_leftwards_handler abort_handler)
+               abort_handler
+
+       ; and so on
+       
+Remarks: the `larger_computation` handler should be supplied as both the
+`continue_leftwards_handler` and the `abort_handler` for the leftmost
+application, where the head `5` is supplied to `f2`; because the result of this
+application should be passed to the larger computation, whether it's a "fall
+off the left end of the list" result or it's a "I'm finished, possibly early"
+result. The `larger_computation` handler also then gets passed to the next
+rightmost stage, where the head `4` is supplied to `f2`, as the `abort_handler` to
+use if that stage decides it has an early answer.
+
+Finally, notice that we're not supplying the application of `f2` to `4` etc as an argument to the application of `f2` to `5` etc---at least, not directly. Instead, we pass
+
+       (\result_of_folding_over_4321. f2 5 result_of_folding_over_4321 <one_handler> <another_handler>)
+
+*to* the application of `f2` to `4` as its "continue" handler. The application of `f2`
+to `4` can decide whether this handler, or the other, "abort" handler, should be
+given an argument and constitute its result.
+
+
+I'll say once again: we're using temporally-loaded vocabulary throughout this,
+but really all we're in a position to mean by that are claims about the result
+of the complex expression semantically depending only on this, not on that. A
+demon evaluator who custom-picked the evaluation order to make things maximally
+bad for you could ensure that all the semantically unnecessary computations got
+evaluated anyway. We don't yet know any way to prevent that. Later, we'll see
+ways to *guarantee* one evaluation order rather than another. Of
+course, in any real computing environment you'll know in advance that you're
+dealing with a fixed evaluation order and you'll be able to program efficiently
+around that.
+
+In detail, then, here's what our v5 lists will look like:
+
+       let empty = \f2 z continue_handler abort_handler. continue_handler z  in
+       let make_list = \h t. \f2 z continue_handler abort_handler.
+               t f2 z (\sofar. f2 h sofar continue_handler abort_handler) abort_handler  in
+       let isempty = \lst larger_computation. lst
+                       ; here's our f2
+                       (\hd sofar continue_handler abort_handler. abort_handler false)
+                       ; here's our z
+                       true
+                       ; here's the continue_handler for the leftmost application of f2
+                       larger_computation
+                       ; here's the abort_handler
+                       larger_computation  in
+       let extract_head = \lst larger_computation. lst
+                       ; here's our f2
+                       (\hd sofar continue_handler abort_handler. continue_handler hd)
+                       ; here's our z
+                       junk
+                       ; here's the continue_handler for the leftmost application of f2
+                       larger_computation
+                       ; here's the abort_handler
+                       larger_computation  in
+       let extract_tail = ; left as exercise
+
+These functions are used like this:
+
+       let my_list = make_list a (make_list b (make_list c empty) in
+       extract_head my_list larger_computation
+
+If you just want to see `my_list`'s head, the use `I` as the
+`larger_computation`.
+
+What we've done here does take some work to follow. But it should be within
+your reach. And once you have followed it, you'll be well on your way to
+appreciating the full terrible power of continuations.
+
+<!-- (Silly [cultural reference](http://www.newgrounds.com/portal/view/33440).) -->
+
+Of course, like everything elegant and exciting in this seminar, [Oleg
+discusses it in much more
+detail](http://okmij.org/ftp/Streams.html#enumerator-stream).
+
+>      *Comments*:
+
+>      1.      The technique deployed here, and in the v2 lists, and in our
+>      implementations of pairs and booleans, is known as 
+>      **continuation-passing style** programming.
+
+>      2.      We're still building the list as a right fold, so in a sense the
+>      application of `f2` to the leftmost element `5` is "outermost". However,
+>      this "outermost" application is getting lifted, and passed as a *handler*
+>      to the next right application. Which is in turn getting lifted, and
+>      passed to its next right application, and so on. So if you
+>      trace the evaluation of the `extract_head` function to the list `[5;4;3;2;1]`,
+>      you'll see `1` gets passed as a "this is the head sofar" answer to its
+>      `continue_handler`; then that answer is discarded and `2` is
+>      passed as a "this is the head sofar" answer to *its* `continue_handler`,
+>      and so on. All those steps have to be evaluated to finally get the result
+>      that `5` is the outer/leftmost head of the list. That's not an efficient way
+>      to get the leftmost head.
+>      
+>      We could improve this by building lists as **left folds**. What's that?
+>      
+>      Well, the right fold of `f` over a list `[a;b;c;d;e]`, using starting value z, is:
+>      
+>                      f a (f b (f c (f d (f e z))))
+>      
+>      The left fold on the other hand starts combining `z` with elements from the left. `f z a` is then combined with `b`, and so on:
+>      
+>                      f (f (f (f (f z a) b) c) d) e
+>      
+>      or, if we preferred the arguments to each `f` flipped:
+>      
+>                      f e (f d (f c (f b (f a z))))
+>      
+>      Recall we implemented v3 lists as their own right-fold functions. We could
+>      instead implement lists as their own left-fold functions. To do that with our
+>      v5 lists, we'd replace above:
+>      
+>                      let make_list = \h t. \f2 z continue_handler abort_handler.
+>                              f2 h z (\z. t f2 z continue_handler abort_handler) abort_handler
+>      
+>      Having done that, now `extract_head` can return the leftmost head
+>      directly, using its `abort_handler`:
+>      
+>                      let extract_head = \lst larger_computation. lst
+>                                      (\hd sofar continue_handler abort_handler. abort_handler hd)
+>                                      junk
+>                                      larger_computation
+>                                      larger_computation
+>      
+>      3.      To extract tails efficiently, too, it'd be nice to fuse the apparatus
+>      developed in these v5 lists with the ideas from 
+>      [v4](/advanced_lambda/#index1h1) lists. But that is left as an exercise.
+
diff --git a/topics/week12_list_and_tree_zippers.mdwn b/topics/week12_list_and_tree_zippers.mdwn
new file mode 100644 (file)
index 0000000..1eb5d07
--- /dev/null
@@ -0,0 +1,254 @@
+[[!toc]]
+
+##List Zippers##
+
+Say you've got some moderately-complex function for searching through a list, for example:
+
+       let find_nth (test : 'a -> bool) (n : int) (lst : 'a list) : (int * 'a) ->
+           let rec helper (position : int) n lst =
+               match lst with
+               | [] -> failwith "not found"
+               | x :: xs when test x -> (if n = 1
+                   then (position, x)
+                   else helper (position + 1) (n - 1) xs
+               )
+               | x :: xs -> helper (position + 1) n xs
+           in helper 0 n lst;;
+
+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:
+
+       let find_nth' (test : 'a -> bool) (n : int) (lst : 'a list) (default : 'a) : ('a * 'a * 'a) ->
+           let rec helper (predecessor : 'a) n lst =
+               match lst with
+               | [] -> failwith "not found"
+               | x :: xs when test x -> (if n = 1
+                   then (predecessor, x, match xs with [] -> default | y::ys -> y)
+                   else helper x (n - 1) xs
+               )
+               | x :: xs -> helper x n xs
+           in helper default n lst;;
+
+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...?
+
+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.
+
+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:
+
+       [10; 20; 30; 40; 50; 60; 70; 80; 90]
+
+we might imagine the list "broken" at position 3 like this (positions are numbered starting from 0):
+
+                   40;
+               30;     50;
+           20;             60;
+       [10;                    70;
+                                   80;
+                                       90]
+
+Then if we move one step forward in the list, it would be "broken" at position 4:
+
+                       50;
+                   40;     60;
+               30;             70;
+           20;                     80;
+       [10;                            90]
+
+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".
+
+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:
+
+                   40;
+               30;     50;
+           20;             60;
+       [10;                    70;
+                                   80;
+                                       90]
+
+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.)
+
+We had some discussion 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:
+
+                t
+                 a
+                  b
+                   40;
+               30;     50;
+           20;             60;
+       [10;                    70;
+                                   80;
+                                       90]
+
+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:
+
+       ([], [10; 20; 30; 40; 50; 60; 70; 80; 90])
+
+However you understand the "zipper" metaphor, this is a very handy data structure, 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:
+
+       [10; 20; 30; *; 50; 60; 70; 80; 90], * filled by 40
+
+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.
+
+
+##Tree Zippers##
+
+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.
+
+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 leaves 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:
+
+               root
+               / \
+             /     \
+           /  \    label 1
+         /      \
+       label 1  label 2
+
+The leftmost leaf and the rightmost leaf have the same label; but they are different leaves. The leftmost leaf has a sibling leaf with the label 2; the rightmost leaf has no siblings that are leaves. 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:
+
+                1
+               / \
+             2     \
+           /  \     5
+         /      \
+        3        4
+
+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 leaves, not any of its inner nodes. The identity of its inner nodes is exhausted by their position in the tree.
+
+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 leaves. The diagrams below will tag all of the nodes, as in the second diagram above, and won't display what the leaves' labels are.
+
+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.
+
+Suppose we have the following tree:
+
+                                9200
+                           /      |  \
+                        /         |    \
+                     /            |      \
+                  /               |        \
+               /                  |          \
+              500                920          950
+           /   |    \          /  |  \      /  |  \
+        20     50     80      91  92  93   94  95  96
+       1 2 3  4 5 6  7 8 9
+
+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.
+
+Suppose we want to represent that we're *at* the node marked `50`. We might use the following metalanguage notation to specify this:
+
+       {parent = ...; siblings = [subtree 20; *; subtree 80]}, * filled by subtree 50
+
+This is modeled on the notation suggested above for list zippers. Here `subtree 20` refers to the whole subtree rooted at node `20`:
+
+         20
+        / | \
+       1  2  3
+
+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`:
+
+       {parent = ...; siblings = [*; subtree 920; subtree 950]}, * filled by subtree 500
+
+And the parent of that targetted subtree should intuitively be a tree targetted on `node 9200`:
+
+       {parent = None; siblings = [*]}, * filled by tree 9200
+
+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:
+
+       {
+          parent = {
+             parent = {
+                parent = None;
+                siblings = [*]
+             }, * filled by tree 9200;
+             siblings = [*; subtree 920; subtree 950]
+          }, * filled by subtree 500;
+          siblings = [subtree 20; *; subtree 80]
+       }, * filled by subtree 50
+
+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:
+
+       {
+          parent = {
+             parent = {
+                parent = None;
+                siblings = [*]
+             },
+             siblings = [*; subtree 920; subtree 950]
+          },
+          siblings = [subtree 20; *; subtree 80]
+       }, * filled by subtree 50
+
+
+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.
+
+For simplicity, I'll continue to use the abbreviated form:
+
+       {parent = ...; siblings = [subtree 20; *; subtree 80]}, * filled by subtree 50
+
+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.
+
+Moving left in our targetted tree that's targetted on `node 50` would be a matter of shifting the `*` leftwards:
+
+       {parent = ...; siblings = [*; subtree 50; subtree 80]}, * filled by subtree 20
+
+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.
+
+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:
+
+       {
+          parent = {parent = ...; siblings = [*; subtree 50; subtree 80]};
+          siblings = [*; leaf 2; leaf 3]
+       }, * filled by leaf 1
+
+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:
+
+              node 20'
+           /     |    \
+        /        |      \
+       leaf 1  leaf 2  leaf 3
+
+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 `*`:
+
+       {
+          parent = ...;
+          siblings = [*; subtree 50; subtree 80]
+       }, * filled by subtree 20'
+
+Or, spelling that structure out fully:
+
+       {
+          parent = {
+             parent = {
+                parent = None;
+                siblings = [*]
+             },
+             siblings = [*; subtree 920; subtree 950]
+          },
+          siblings = [*; subtree 50; subtree 80]
+       }, * filled by subtree 20'
+
+Moving upwards yet again would get us:
+
+       {
+          parent = {
+             parent = None;
+             siblings = [*]
+          },
+          siblings = [*; subtree 920; subtree 950]
+       }, * filled by subtree 500'
+
+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:
+
+       {
+          parent = None;
+          siblings = [*]
+       }, * filled by tree 9200'
+
+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.
+
+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:
+
+*      [[!wikipedia Zipper (data structure)]]
+*      [Haskell wikibook on zippers](http://en.wikibooks.org/wiki/Haskell/Zippers)
+*      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.
+*      As always, [Oleg](http://okmij.org/ftp/continuations/Continuations.html#zipper) takes this a few steps deeper.
+
+