add note
[lambda.git] / topics / week13_coroutines_exceptions_and_aborts.mdwn
1 [[!toc]]
2
3 ## Coroutines ##
4
5 Recall [[the recent homework assignment|/exercises/assignment12]] where you solved the same-fringe problem with a `make_fringe_enumerator` function, or in the Scheme version using streams instead of zippers, with a `lazy-flatten` function.
6
7 The technique illustrated in those solutions 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*.
8
9 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:
10
11         main program        next1 thread        next2 thread
12         ------------        ------------        ------------
13         start next1
14         (paused)            starting
15         (paused)            calculate first leaf
16         (paused)            <--- return it
17         start next2         (paused)            starting
18         (paused)            (paused)            calculate first leaf
19         (paused)            (paused)            <-- return it
20         compare leaves      (paused)            (paused)
21         call loop again     (paused)            (paused)
22         call next1 again    (paused)            (paused)
23         (paused)            calculate next leaf (paused)
24         (paused)            <-- return it       (paused)
25         ... and so on ...
26
27 If you want to read more about these kinds of threads, here are some links:
28
29 <!-- *  [[!wikipedia Computer_multitasking]]
30 *       [[!wikipedia Thread_(computer_science)]] -->
31
32 *       [[!wikipedia Coroutine]]
33 *       [[!wikipedia Iterator]]
34 *       [[!wikipedia Generator_(computer_science)]]
35 *       [[!wikipedia Fiber_(computer_science)]]
36 <!-- *  [[!wikipedia Green_threads]]
37 *       [[!wikipedia Protothreads]] -->
38
39 The way we built cooperative threads using `make_fringe_enumerator` 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 either required us to manually save and restore the thread's snapshotted state (a tree zipper); or else we had to use a mutable reference cell to save and restore that state for us. Using the saved state, the next invocation of the `next_leaf` function could start up again where the previous invocation left off.
40
41 It's possible to build cooperative threads without using those tools, however. Already our [[solution using streams|/exercises/assignment12#streams2]] uses neither zippers nor any mutation. Instead it saves the thread's state in explicitly-created thunks, and resumes the thread by forcing the thunk.
42
43 Some languages have a native syntax for coroutines. Here's how we'd write the same-fringe solution above using native coroutines in the language Lua:
44
45         > function fringe_enumerator (tree)
46             if tree.leaf then
47                 coroutine.yield (tree.leaf)
48             else
49                 fringe_enumerator (tree.left)
50                 fringe_enumerator (tree.right)
51             end
52         end
53         
54         > function same_fringe (tree1, tree2)
55             local next1 = coroutine.wrap (fringe_enumerator)
56             local next2 = coroutine.wrap (fringe_enumerator)
57             local function loop (leaf1, leaf2)
58                 if leaf1 or leaf2 then
59                     return leaf1 == leaf2 and loop( next1(), next2() )
60                 elseif not leaf1 and not leaf2 then
61                     return true
62                 else
63                     return false
64                 end
65             end
66             return loop (next1(tree1), next2(tree2))
67         end
68         
69         > return same_fringe ( {leaf=1}, {leaf=2} )
70         false
71         
72         > return same_fringe ( {leaf=1}, {leaf=1} )
73         true
74         
75         > return same_fringe ( {left = {leaf=1}, right = {left = {leaf=2}, right = {leaf=3}}},
76             {left = {left = {leaf=1}, right = {leaf=2}}, right = {leaf=3}} )
77         true
78
79 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.
80
81
82 ##Exceptions and Aborts##
83
84 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.
85
86 While writing OCaml code, you've probably come across errors. In fact, you've probably come across errors of several sorts. One sort of error comes about when you've got syntax errors and the OCaml interpreter isn't even able to parse your code. A second sort of error is type errors, as in:
87
88         # let lst = [1; 2] in
89           "a" :: lst;;
90         Error: This expression has type int list
91                but an expression was expected of type string list
92
93 Type errors are also detected and reported before OCaml attempts to execute or evaluate your code. But you may also have encountered a third kind of error, that arises while your program is running. For example:
94
95         # 1/0;;
96         Exception: Division_by_zero.
97         # List.nth [1;2] 10;;
98         Exception: Failure "nth".
99
100 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 standard implementation of `List.nth`:
101
102         let nth l n =
103           if n < 0 then invalid_arg "List.nth" else
104           let rec nth_aux l n =
105             match l with
106             | [] -> failwith "nth"
107             | a::l -> if n = 0 then a else nth_aux l (n-1)
108           in nth_aux l n
109
110 (The Juli8 version of `List.nth` only differs in sometimes raising a different error.) Notice the two clauses `invalid_arg "List.nth"` and `failwith "nth"`. These are two helper functions which are shorthand for:
111
112         raise (Invalid_argument "List.nth");;
113         raise (Failure "nth");;
114
115 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:
116
117         raise bad
118
119 the effect is for the program to immediately stop without evaluating any further code:
120
121         # let xcell = ref 0;;
122         val xcell : int ref = {contents = 0}
123         # let bad = Failure "test"
124           in let _ = raise bad
125           in xcell := 1;;
126         Exception: Failure "test".
127         # !xcell;;
128         - : int = 0
129
130 Notice that the line `xcell := 1` was never evaluated, so the contents of `xcell` are still `0`.
131
132 I said when you evaluate the expression:
133
134         raise bad
135
136 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. (In OCaml 4.02 and higher, there is also a more inclusive construct that combines these, `match ... with PATTERN -> ... | exception PATTERN -> ...`.)
137
138         # let foo x =
139             try
140                 (if x = 1 then 10
141                 else if x = 2 then raise (Failure "two")
142                 else raise (Failure "three")
143                 ) + 100
144             with Failure "two" -> 20
145             ;;
146         val foo : int -> int = <fun>
147         # foo 1;;
148         - : int = 110
149         # foo 2;;
150         - : int = 20
151         # foo 3;;
152         Exception: Failure "three".
153
154 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.
155
156 So what I should have said is that when you evaluate the expression:
157
158         raise bad
159
160 *and that exception is never caught*, then the effect is for the program to immediately stop.
161
162 **Trivia**: what's the type of the `raise (Failure "two")` in:
163
164         if x = 1 then 10
165         else raise (Failure "two")
166
167 What's its type in:
168
169         if x = 1 then "ten"
170         else raise (Failure "two")
171
172 So now what do you expect the type of this to be:
173
174         fun x -> raise (Failure "two")
175
176 How about this:
177
178         (fun x -> raise (Failure "two") : 'a -> 'a)
179
180 Remind you of anything we discussed earlier? (At one point earlier in term we were asking whether you could come up with any functions of type `'a -> 'a` other than the identity function.)
181
182 **/Trivia.**
183
184 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.
185
186 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:
187
188         # try
189             try
190                 (raise (Failure "blah")
191                 ) + 100
192             with Failure "fooey" -> 10
193           with Failure "blah" -> 20;;
194         - : int = 20
195
196 The matching `try ... with ...` block need not *lexically surround* the site where the error was raised:
197
198         # let foo b x =
199             try
200                 (b x
201                 ) + 100
202             with Failure "blah" -> 20
203         in let bar x =
204             raise (Failure "blah")
205         in foo bar 0;;
206         - : int = 20
207
208 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`.
209
210 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:
211
212         # let foo x =
213             try begin
214                 (if x = 1 then 10
215                 else abort 20
216                 ) + 100
217             end
218             ;;
219
220 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.
221
222 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:
223
224         > function foo(x)
225             local value
226             if (x == 1) then
227                 value = 10
228             else
229                 return 20         -- abort early
230             end
231             return value + 100    -- in a language like Scheme, you could omit the `return` here
232                                   -- but in Lua, a function's normal result must always be explicitly `return`ed
233         end
234         
235         > return foo(1)
236         110
237         
238         > return foo(2)
239         20
240
241 Okay, so that's our second execution pattern.
242
243 ##What do these have in common?##
244
245 In both of these patterns --- coroutines and exceptions/aborts --- 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.
246
247 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:
248
249         let foo x =
250             try begin
251                 (if x = 1 then 10
252                 else abort 20
253                 ) + 100
254             end
255         in (foo 2) + 1;;
256
257 we can imagine a box:
258
259         let foo x =
260         +---try begin----------------+
261         |       (if x = 1 then 10    |
262         |       else abort 20        |
263         |       ) + 100              |
264         +---end----------------------+
265         in (foo 2) + 1000;;
266
267 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.
268
269
270 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:
271
272         let x = 2
273         in let foo_result =
274         +---try begin----------------+
275         |       (if x = 1 then 10    |
276         |       else abort 20        |
277         |       ) + 100              |
278         +---end----------------------+
279         in (foo_result) + 1000;;
280
281 and we can think of the code starting with `let foo_result = ...` as a function, with the box being its parameter, like this:
282
283     let foo_result = < >
284     in foo_result + 100
285
286 or, spelling out the gap `< >` as a bound variable:
287
288         fun box ->
289             let foo_result = box
290             in (foo_result) + 1000
291
292 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:
293
294         let x = 2
295         in let snapshot = fun box ->
296             let foo_result = box
297             in (foo_result) + 1000
298         in let value =
299             (if x = 1 then 10
300             else ... (* we'll come back to this part *)
301             ) + 100
302         in shapshot value;;
303
304 But now how should the `abort 20` part, that we ellided here, work? What should happen when we try to evaluate that?
305
306 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:
307
308         let x = 2
309         in let snapshot = fun box ->
310             let foo_result = box
311             in (foo_result) + 1000
312         in let value =
313             (if x = 1 then 10
314             else snapshot 20
315             ) + 100
316         in shapshot value;;
317
318 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:
319
320         let x = 2
321         in let snapshot = fun box ->
322             let foo_result = box
323             in (foo_result) + 1000
324         in let value =
325             (if x = 1 then 10
326             else snapshot 20 THEN STOP
327             ) + 100
328         in shapshot value;;
329
330 We can get that by some further rearranging of the code:
331
332         let x = 2
333         in let snapshot = fun box ->
334             let foo_result = box
335             in (foo_result) + 1000
336         in let continue_normally = fun from_value ->
337             let value = from_value + 100
338             in snapshot value
339         in
340             if x = 1 then continue_normally 10
341             else snapshot 20;;
342
343 And this is indeed what is happening, at a fundamental level, when you use an expression like `abort 20`.
344
345 <!--
346 # #require "delimcc";;
347 # open Delimcc;;
348 # let reset body = let p = new_prompt () in push_prompt p (body p);;
349 # let test_cps x =
350       let snapshot = fun box ->
351           let foo_result = box
352           in (foo_result) + 1000
353       in let continue_normally = fun from_value ->
354           let value = from_value + 100
355           in snapshot value
356       in if x = 1 then continue_normally 10
357       else snapshot 20;;
358
359         let foo x =
360         +===try begin================+
361         |       (if x = 1 then 10    |
362         |       else abort 20        |
363         |       ) + 100              |
364         +===end======================+
365         in (foo 2) + 1000;;
366
367 # let test_shift x =
368     let foo x = reset(fun p () ->
369         (shift p (fun k ->
370             if x = 1 then k 10 else 20)
371         ) + 100)
372     in foo z + 1000;;
373
374 # test_cps 1;;
375 - : int = 1110
376 # test_shift 1;;
377 - : int = 1110
378 # test_cps 2;;
379 - : int = 1020
380 # test_shift 2;;
381 - : int = 1020
382 -->
383
384 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.
385
386 ##Continuations, finally##
387
388 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.
389
390 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.
391
392 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.
393
394 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 our [[abortable list traversals|/topics/week12_abortable_traversals]].
395
396 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).
397
398 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.
399
400 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.
401
402 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.
403
404 This inversion of who is the argument and who is the function receiving the argument is paradigmatic of working with continuations.
405
406 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.
407
408 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:
409
410         let foo x =
411             try begin
412                 (if x = 1 then 10
413                 else abort 20
414                 ) + 100
415             end
416         in (foo 2) + 1000;;
417
418 into this:
419
420         let x = 2
421         in let snapshot = fun box ->
422             let foo_result = box
423             in (foo_result) + 1000
424         in let continue_normally = fun from_value ->
425             let value = from_value + 100
426             in snapshot value
427         in
428             if x = 1 then continue_normally 10
429             else snapshot 20;;
430
431 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.
432
433 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 ...)`.
434
435 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).
436
437 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.
438
439 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.
440