coroutines tweak
[lambda.git] / coroutines_and_aborts.mdwn
index a7eccfc..a0b35c8 100644 (file)
@@ -109,7 +109,7 @@ Anyway, using record types, we might define the tree zipper interface like so:
            ;;
 -->
 
-The following function takes an 'a tree and returns an 'a zipper focused on its root:
+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}
@@ -255,7 +255,7 @@ It's possible to build cooperative threads without using those tools, however. S
            {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 to rely on.
+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##
@@ -316,9 +316,10 @@ the effect is for the program to immediately stop. That's not exactly true. You
 
        # let foo x =
            try
-               if x = 1 then 10
+               (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>
@@ -329,7 +330,7 @@ the effect is for the program to immediately stop. That's not exactly true. You
        # foo 3;;
        Exception: Failure "three".
 
-Notice what happens here. If we call `foo 1`, then the code between `try` and `with` evaluates to `10`, with no exceptions being raised. That then is what the entire `try ... with ...` block evaluates to; and so too what `foo 1` evaluates to. If we call `foo 2`, then the code between `try` and `with` raises an exception `Failure "two"`. The pattern in the `with` clause matches that exception, so we get instead `20`. If we call `foo 3`, we again raise an exception. This exception isn't matched by the `with` block, so it percolates up to the top of the program, and then the program immediately stops.
+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:
 
@@ -343,7 +344,8 @@ When an exception is raised, it percolates up through the code that called it, u
 
        # try
            try
-               raise (Failure "blah")
+               (raise (Failure "blah")
+                       ) + 100
            with Failure "fooey" -> 10
          with Failure "blah" -> 20;;
        - : int = 20
@@ -352,7 +354,8 @@ The matching `try ... with ...` block need not *lexically surround* the site whe
 
        # let foo b x =
            try
-               b x
+               (b x
+                       ) + 100
            with Failure "blah" -> 20
        in let bar x =
            raise (Failure "blah")
@@ -366,7 +369,8 @@ OK, now this exception-handling apparatus does exemplify the second execution pa
        # let foo x =
            try begin
                (if x = 1 then 10
-               else abort 20) + 100
+               else abort 20
+                       ) + 100
            end
            ;;
 
@@ -379,9 +383,10 @@ Many programming languages have this simplified exceution pattern, either instea
            if (x == 1) then
                value = 10
            else
-               return 20
+               return 20         -- return early
            end
-           return value + 100
+           return value + 100    -- in Lua, a function's normal value
+                                 -- must always also be explicitly returned
        end
        
        > return foo(1)
@@ -401,7 +406,8 @@ A more general way to think about these snapshots is to think of the code we're
        let foo x =
            try begin
                (if x = 1 then 10
-               else abort 20) + 100
+               else abort 20
+                       ) + 100
            end
        in (foo 2) + 1;;
 
@@ -410,20 +416,22 @@ we can imagine a box:
        let foo x =
        +---try begin----------------+
        |       (if x = 1 then 10    |
-       |       else abort 20) + 100 |
+       |       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.
+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 =
+       let x = 2
+       in let foo_result =
        +---try begin----------------+
        |       (if x = 1 then 10    |
-       |       else abort 20) + 100 |
+       |       else abort 20        |
+       |       ) + 100              |
        +---end----------------------+
        in (foo_result) + 1000;;
 
@@ -459,7 +467,7 @@ Well, that's when we use the snapshot code in an unusual way. If we encounter an
                ) + 100
        in shapshot value;;
 
-Except that isn't quite right, yet---in this fragment, after the snapshot code is finished, we'd pick up again inside `let value = (...) + 100 in snapshot value`. We don't want to pick up again there. We want instead to do this:
+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 ->
@@ -477,11 +485,11 @@ We can get that by some further rearranging of the code:
        in let snapshot = fun box ->
                let foo_result = box
                in (foo_result) + 1000
-       in let finish_value = fun start ->
-               let value = start + 100
+       in let continue_normally = fun from_value ->
+               let value = from_value + 100
                in snapshot value
        in 
-               if x = 1 then finish_value 10
+               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`.
@@ -494,16 +502,17 @@ And this is indeed what is happening, at a fundamental level, when you use an ex
          let snapshot = fun box ->
                  let foo_result = box
                  in (foo_result) + 1000
-         in let finish_value = fun start ->
-                 let value = start + 100
+         in let continue_normally = fun from_value ->
+                 let value = from_value + 100
                  in snapshot value
-         in if x = 1 then finish_value 10
+         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 |
+       |       else abort 20        |
+       |       ) + 100              |
        +===end======================+
        in (foo 2) + 1000;;
 
@@ -524,10 +533,58 @@ And this is indeed what is happening, at a fundamental level, when you use an ex
 - : int = 1020
 -->
 
-A similar kind of "snapshotting" lets coroutines keep track of where the left off, so that they can start up again at that same place.
+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 abort from deep inside a sub-computation. Or suspend and resume a thread. 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 (that has already returned its value---what should happen then?) Maybe we'd call the same continuation function *multiple times* (what should happen then?). All of these weird and wonderful possibilities await us.
+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 so as 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 inner code as an *argument* or bound variable. That is: the cde 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 subject terms 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 subject terms to be of type `(e -> t) -> t`, and that now it'd be the predicate (still of type `e -> t`) that provides an argument to the function expressed by the subject.
+
+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 ...)`. 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 these that we won't be exploring in the seminar. Ken Shan has done amazing 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) + 1;;
+
+into this:
+
+       let x = 2
+       in let snapshot = fun box ->
+               let foo_result = box
+               in (foo_result) + 1000
+       in let finish_value = fun start ->
+               let value = start + 100
+               in snapshot value
+       in 
+               if x = 1 then finish_value 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.