zipper-lists-contin s/x/a/
[lambda.git] / continuations.mdwn
index ec97f1a..83ae5f1 100644 (file)
@@ -30,4 +30,41 @@ This function will be applied to whatever is the result of `g (3 + 4)`. So this
 
 Go back and read the material on "Aborting a Search Through a List" in [[Week4]] for an example of doing this.
 
+In very general terms, the strategy is to work with functions like this:
+
+       let g' k (i : int) =
+               ... do stuff ...
+               ... if you want to abort early, supply an argument to k ...
+               ... do more stuff ...
+               ... normal result
+       in let gcon = fun result -> 1 + 2 * (1 - result)
+       in gcon (g' gcon (3 + 4))
+
+It's a convention to use variables like `k` for continuation arguments. If the function `g'` never supplies an argument to its contination argument `k`, but instead just finishes evaluating to a normal result, that normal result will be delivered to `g'`'s continuation `gcon`, just as happens when we don't pass around any explicit continuation variables.
+
+The above snippet of OCaml code doesn't really capture what happens when we pass explicit continuation variables. For suppose that inside `g'`, we do supply an argument to `k`. That would go into the `result` parameter in `gcon`. But then what happens once we've finished evaluating the application of `gcon` to that `result`? In the OCaml snippet above, the final value would then bubble up through the context in the body of `g'` where `k` was applied, and eventually out to the final line of the snippet, where it once again supplied an argument to `gcon`. That's not what happens with a real continuation. A real continuation works more like this:
+
+       let g' k (i : int) =
+               ... do stuff ...
+               ... if you want to abort early, supply an argument to k ...
+               ... do more stuff ...
+               ... normal result
+       in let gcon = fun result ->
+               let final_value = 1 + 2 * (1 - result)
+               in end_program_with final_value
+       in gcon (g' gcon (3 + 4))
+
+So once we've finished evaluating the application of `gcon` to a `result`, the program is finished. (This is how undelimited continuations behave. We'll discuss delimited continuations later.)
+
+So now, guess what would be the result of doing the following:
+
+       let g' k (i : int) =
+               1 + k i
+       in let gcon = fun result ->
+               let final_value = (1, result)
+               in end_program_with final_value
+       in gcon (g' gcon (3 + 4))
+
+<!-- (1, 7) ... explain why not (1, 8) -->
+