X-Git-Url: http://lambda.jimpryor.net/git/gitweb.cgi?p=lambda.git;a=blobdiff_plain;f=week11.mdwn;h=0128a5da9bbc933e7b961aa64a2685dec8ace7cc;hp=b48dd5f410d314554c6fad96293592be0f855d96;hb=339b62e48b39fadd325d9e0dc903430c4a896870;hpb=44bcb5340c6c85c2fbd05b28c8837f57529faf31 diff --git a/week11.mdwn b/week11.mdwn index b48dd5f4..0128a5da 100644 --- a/week11.mdwn +++ b/week11.mdwn @@ -1,22 +1,11 @@ These notes may change in the next few days (today is 30 Nov 2010). The material here benefited from many discussions with Ken Shan. -[[!toc]] +##[[Tree and List Zippers]]## -##List Zippers## +##[[Coroutines and Aborts]]## -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;; +##[[From Lists to Continuations]]## 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: @@ -908,10 +897,11 @@ The recipe for constructing the list goes like this: 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 -a **continuation** of the recipe. 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)`. +(or group of steps) a **continuation** of the recipe. 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)`. This means that we can now represent the unzipped part of our zipper--the part we've already unzipped--as a continuation: a function @@ -954,57 +944,57 @@ what the parallel would suggest. The reason is that `unzipped` is a list, but `c` is a function. That's the most crucial difference, 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 `List.append`. +together the two instances of `unzipped` with an explicit (and +relatively inefficient) `List.append`. In the `tc` version of the task, we simply compose `c` with itself: `c o c = fun x -> c (c x)`. Why use the identity function as the initial continuation? Well, if -you have already constructed the list "abSd", what's the next step in -the recipe to produce the desired result (which is the same list, -"abSd")? Clearly, the identity continuation. +you have already constructed the initial list `"abSd"`, what's the next +step in the recipe to produce the desired result, i.e, the very same +list, `"abSd"`? Clearly, the identity continuation. A good way to test your understanding is to figure out what the continuation function `c` must be at the point in the computation when `tc` is called with the first argument `"Sd"`. Two choices: is it -`fun x -> a::b::x`, or it is `fun x -> b::a::x`? -The way to see if you're right is to execute the following -command and see what happens: +`fun x -> a::b::x`, or it is `fun x -> b::a::x`? The way to see if +you're right is to execute the following command and see what happens: tc ['S'; 'd'] (fun x -> 'a'::'b'::x);; There are a number of interesting directions we can go with this task. -The task was chosen because the computation can be viewed as a +The reason this task was chosen is because it can be viewed as a simplified picture of a computation using continuations, where `'S'` plays the role of a control operator with some similarities to what is -often called `shift`. In the analogy, the list portrays a string 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. +often called `shift`. 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 possibile development is that we could add a special symbol `'#'`, and then the task would be to copy from the target `'S'` only back to the closest `'#'`. This would allow the task to simulate delimited -continuations (for right-branching computations). +continuations with embedded prompts. -The task is well-suited to the list zipper because the list monad has -an intimate connection with continuations. The following section -makes this connection. We'll return to the list task after talking -about generalized quantifiers below. +The reason the task is well-suited to the list zipper is in part +because the list monad has an intimate connection with continuations. +The following section explores this connection. We'll return to the +list task after talking about generalized quantifiers below. Rethinking the list monad ------------------------- To construct a monad, the key element is to settle on a type -constructor, and the monad naturally follows from that. We'll remind -you of some examples of how monads follow from the type constructor in -a moment. This will involve some review of familair 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). +constructor, and the monad more or less naturally follows from that. +We'll remind you of some examples of how monads follow from the type +constructor in a moment. This will involve some review of familair +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 that the type constructor is @@ -1015,17 +1005,19 @@ then the choice of unit and bind is natural: let r_unit (a : 'a) : 'a reader = fun (e : env) -> a -Since the type of an `'a reader` is `env -> 'a` (by definition), -the type of the `r_unit` function is `'a -> env -> 'a`, which is a -specific case of the type of the *K* combinator. So it makes sense -that *K* is the unit for the reader monad. +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 correct `bind` function as follows. We -start by declaring the types determined by the definition of a bind operation: +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) = ... @@ -1034,19 +1026,26 @@ 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 invented an environment `e` that we didn't already have , -so we have to abstract over that variable to balance the books: +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) = - f (u e) e +
+r_bind (u : 'a reader) (f : 'a -> 'b reader) : ('b reader) = 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. @@ -1115,7 +1114,7 @@ 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 some use of each of them (rather than +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 -> 'a list` to them. Once we've done so, we @@ -1130,13 +1129,13 @@ 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 +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 type -3 lists (the right fold implementation), though it's important to -wonder how things would change if we used some other strategy for -implementating lists. These were the lists that made lists look like -Church numerals with extra bits embdded in them: +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 implementating lists). These were the lists that made +lists look like Church numerals with extra bits embdded in them: empty list: fun f z -> z list with one element: fun f z -> f 1 z @@ -1220,7 +1219,7 @@ Now, we've used a `k` that we pulled out of nowhere, so we need to abstract over 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 we our bind is: +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) @@ -1329,7 +1328,7 @@ highly similar to the List monad just given: 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_bind` is exactly the `gqize` function that Montague used +Note that `c_unit` is exactly the `gqize` function that Montague used to lift individuals into the continuation monad. That last bit in `c_bind` looks familiar---we just saw something like @@ -1360,7 +1359,7 @@ to monads that can be understood in terms of continuations? Manipulating trees with monads ------------------------------ -This thread develops an idea based on a detailed suggestion of Ken +This topic develops an idea based on a detailed suggestion of Ken Shan's. We'll build a series of functions that operate on trees, doing various things, including replacing leaves, counting nodes, and converting a tree to a list of leaves. The end result will be an @@ -1368,11 +1367,11 @@ application for continuations. From an engineering standpoint, we'll build a tree transformer 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 +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.) +the utility of replacing one monad with other. First, we'll be needing a lot of trees during the remainder of the course. Here's a type constructor for binary trees: @@ -1750,4 +1749,7 @@ called a that is intended to represent non-deterministic computations as a tree. +##[[List Monad as Continuation Monad]]## + +##[[Manipulating Trees with Monads]]##