some rewrites, not finished
[lambda.git] / topics / week12_abortable_traversals.mdwn
1 ## Aborting a search through a list ##
2
3 We've talked about different implementations of lists in the Lambda Calculus; and we've also talked about using lists to implement other data structures, like sets. One thing we observed is that if you're going to implement a set using a list (this isn't an especially efficient implementation of a set, but let's do the best we can with it), it's helpful to make sure that the list is always sorted. That way, as you're searching through the list, you might come to a point before the end where you knew the element you're looking for wasn't going to be found anymore. So you wouldn't have to continue the search.
4
5 If you were implementing lists with `letrec` or a fixed point combinator, then at that point you could just have your traversal function return some appropriate result, instead of requesting that the recursion continue.
6
7 But what if you were instead using our right-fold or left-fold implementation of lists, instead of resorting to `letrec` or a fixed point combinator? In those cases, if your traversal function returns a result, that result automatically gets passed to the next stage of the traversal, as the updated seed value from the previous steps. If we make the seed value type complex, we could signal to the rest of the traversal that the job is done, they don't need to do any more work. For example, the seed value might be a pair of `false` and some default value until we reach a certain stage, and all the traversal steps until that stage have to do their normal work, but once we've gotten to the stage where we're ready to return a result, we make the seed value be a pair of `true` and the result we've computed. Then all the later traversal steps see that `true` and just pass the existing seed pair on to the rest of the traversal. At the end, we throw away the `true` and take the second member of the final seed value as our desired result. This will work fine, but we still have to go through every step of the traversal. Let's think about whether we can modify the right-fold and/or left-fold implementation of lists to allow for a genuine early abort. When we find a result mid-way through the traversal, we want to be able to just return that result and have the traversal then be _finished_.
8
9 We worked out such an implementation in the homework session on Wed April 22. The scheme we used was that, whereas before our traversal functions would have an interface like this:
10
11     \current_list_element seed_value_so_far. do_something
12
13 Our traversal functions will instead now have an interface like this:
14
15     \current_list_element seed_value_so_far done_handler keep_going_handler.
16       if ... then done_handler (some_result) else keep_going_handler (another_result)
17
18 and we worked out that a left-fold implementation of the list `[10,20,30,40]` could look like this:
19
20     \f z done_handler. f 10 z done_handler (\z. [20,30,40] f z done_handler)
21
22 The only surprising bit here is that the `keep_going_handler` we supply the traversal function `f` with encodes how the traversal should continue, using the updated seed value `z` from this step, without actually computing the rest of the traversal. It's up to `f` to decide whether to invoke the rest of the traversal, by supplying a value to that `keep_going_handler`, or to finish the traversal right now by supply a value to the `done_handler` instead.
23
24 A question came up in the session of why we need the `done_handler` in these schemes. We could just eliminate it and have the traversal function `f` choose between simply returning a value --- that'd abort the traversal, the way we did above by passing the value to `done_handler` --- or instead supplying a value to the `keep_going_handler`. And the answer is that in this case, this is correct. (In a few weeks when we look at delimited continuations in terms of `reset`/`shift`, you'll see that this is essentially how the `abort` operation gets implemented using `shift`.) However, sometimes it helps to express a basic case a bit more verbosely than seems immediately necessary, because then later generalizations will look more natural. That's true here. So let's just use the implementation as we've written it. If you prefer, you can just make the `done_handler` be the identity function.
25
26 With this general scheme, here is the empty list:
27
28     \f z done_handler. done_handler z
29
30 and here is the `cons` operation:
31
32     \x xs. \f z done_handler. f x z done_handler (\z. xs f z done_handler)
33
34 (The latter can just be read off of our construction of `[10,20,30,40]`; I just substituted `x` for `10` and `xs` for `[20, 30, 40]`.)
35
36 Here's an example of how to get the head of such a list:
37
38     xs (\x z done keep_going. done x) err done_handler
39
40 `err` is what's returned if you ask for the `head` of the empty list.
41
42 Here's how to get the length of such a list:
43
44     xs (\x z done keep_going. keep_going (succ z)) 0 done_handler
45
46 Here there is no opportunity to abort early with a correct value, so our traversal function always delivers its output to the `keep_going` handler.
47
48 Here's how to get the last element of such a list:
49
50     xs (\x z done keep_going. keep_going x) err done_handler
51
52 This is similar to getting the first element, except that each step delivers its output to the `keep_going` handler rather than to the `done` handler. That ensures that we will only get the output of the last step, when the traversal function is applied to the last member of the list. If the list is empty, then we'll get the `err` value, just as with the function that tries to extract the list's head.
53
54 All of this gave us a left-fold implementation of lists. (Perhaps if you were _aiming_ for a left-fold implementation of lists, you would make the traversal function `f` take its `current_list_element` and `seed_value` arguments in the flipped order, but let's not worry about that.)
55
56 Now, let's think about how to get a right-fold implementation. It's not profoundly different, but it does require us to change our interface a little. Our left-fold implementation of `[10,20,30,40]`, above, looked like this (now we abbreviate some of the variables):
57
58     \f z d. f 10 z d (\z. [20,30,40] f z d)
59
60 Expanding the definition of `[20,30,40]`, and all the successive tails, this comes to:
61
62     \f z d. f 10 z d (\z. f 20 z d (\z. f 30 z d (\z. f 40 z d d)))
63
64 For a right-fold implementation, that should instead look like roughly like this:
65
66     \f z d. f 40 z d (\z. f 30 z d (\z. f 20 z d (\z. f 10 z d d)))
67
68 Now suppose we had just the implementation of the tail of the list, `[20,30,40]`, that is:
69
70     \f z d. f 40 z d (\z. f 30 z d (\z. f 20 z d d))
71
72 How should we take that value and transform it into the preceding value, which represents `10` consed onto that tail? I can't see how to do it in a general way, and I expect it's just not possible. Essentially what we want is to take that second `d` in the innermost function `\z. f 20 z d d`, we want to replace that second `d` with something like `(\z. f 10 z d d)`. But how can we replace just the second `d` without also replacing the first `d`, and indeed all the other bound occurrences of `d` in the expansion of `[20,30,40]`.
73
74 The difficulty here is that our traversal function `f` expects two handlers, but we are only giving the fold function we implement the list as a single handler. That single handler gets fed twice to the traversal function. One time it may be transformed, but at the end of the traversal, as with `\z. f 20 z d d`, there's nothing left to do to "keep going", so here it's just the single handler `d` fed to `f` twice. But we can see that in order to implement `cons` for a right-folding traversal, we don't want it to be the single handler `d` fed to `f` twice. It'd work better if we implemented `[20,30,40]` like this:
75
76     \f z d g. f 40 z d (\z. f 30 z d (\z. f 20 z d g))
77
78 Notice that now the fold function we implement the list as takes *two* handlers, `d` (for "done") and `g` (for "keep going"). Generally we'll *invoke* the fold function *by supplying the same handler function to both of these*. However, it's still useful to have the list be defined so that they're separate arguments. For now we can `cons` `10` onto the list by just substituting `(\z. f 10 z d g)` in for the bound `g`. That is:
79
80     [10,20,30,40] ≡ \f z d g. [20,30,40] f z d (\z. f 10 z d g)
81
82 Spelling this out, here are the implementations of the functions we defined before, only now for the right-fold lists:
83
84     null = \f z d g. g z
85     cons x xs = \f z d g. xs f z d (\z. f x z d g)
86     head xs = xs (\x z d g. g x) err done_handler done_handler
87     length xs = xs (\x z d g. g (succ z)) 0 done_handler done_handler
88     last xs = xs (\x z d g. d x) err done_handler done_handler
89
90 *Exercise*: when considering just the implementation of `null`, both `\f z d g. g z` and `\f z d g. d z` may seem like reasonable candidates. What would go wrong with the rest of our scheme is we had instead used the latter?
91
92
93 ---
94
95
96 We said that the sorted-list implementation of a set was more efficient than
97 the unsorted-list implementation, because as you were searching through the
98 list, you could come to a point where you knew the element wasn't going to be
99 found. So you wouldn't have to continue the search.
100
101 If your implementation of lists was, say v1 lists plus the Y-combinator, then
102 this is exactly right. When you get to a point where you know the answer, you
103 can just deliver that answer, and not branch into any further recursion. If
104 you've got the right evaluation strategy in place, everything will work out
105 fine.
106
107 But what if we wanted to use v3 lists instead?
108
109 >       Why would we want to do that? The advantage of the v3 lists and v3 (aka
110 "Church") numerals is that they have their recursive capacity built into their
111 very bones. So for many natural operations on them, you won't need to use a fixed
112 point combinator.
113
114 >       Why is that an advantage? Well, if you use a fixed point combinator, then
115 the terms you get won't be strongly normalizing: whether their reduction stops
116 at a normal form will depend on what evaluation order you use. Our online
117 [[lambda evaluator]] uses normal-order reduction, so it finds a normal form if
118 there's one to be had. But if you want to build lambda terms in, say, Scheme,
119 and you wanted to roll your own recursion as we've been doing, rather than
120 relying on Scheme's native `let rec` or `define`, then you can't use the
121 fixed-point combinators `Y` or <code>&Theta;</code>. Expressions using them
122 will have non-terminating reductions, with Scheme's eager/call-by-value
123 strategy. There are other fixed-point combinators you can use with Scheme (in
124 the [week 3 notes](/week3/#index7h2) they were <code>Y&prime;</code> and
125 <code>&Theta;&prime;</code>. But even with them, evaluation order still
126 matters: for some (admittedly unusual) evaluation strategies, expressions using
127 them will also be non-terminating.
128
129 >       The fixed-point combinators may be the conceptual stars. They are cool and
130 mathematically elegant. But for efficiency and implementation elegance, it's
131 best to know how to do as much as you can without them. (Also, that knowledge
132 could carry over to settings where the fixed point combinators are in principle
133 unavailable.)
134
135
136 So again, what if we're using v3 lists? What options would we have then for
137 aborting a search or list traversal before it runs to completion?
138
139 Suppose we're searching through the list `[5;4;3;2;1]` to see if it
140 contains the number `3`. The expression which represents this search would have
141 something like the following form:
142
143         ..................<eq? 1 3>  ~~>
144         .................. false     ~~>
145         .............<eq? 2 3>       ~~>
146         ............. false          ~~>
147         .........<eq? 3 3>           ~~>
148         ......... true               ~~>
149         ?
150
151 Of course, whether those reductions actually followed in that order would
152 depend on what reduction strategy was in place. But the result of folding the
153 search function over the part of the list whose head is `3` and whose tail is `[2;
154 1]` will *semantically* depend on the result of applying that function to the
155 more rightmost pieces of the list, too, regardless of what order the reduction
156 is computed by. Conceptually, it will be easiest if we think of the reduction
157 happening in the order displayed above.
158
159 Once we've found a match between our sought number `3` and some member of
160 the list, we'd like to avoid any further unnecessary computations and just
161 deliver the answer `true` as "quickly" or directly as possible to the larger
162 computation in which the search was embedded.
163
164 With a Y-combinator based search, as we said, we could do this by just not
165 following a recursion branch.
166
167 But with the v3 lists, the fold is "pre-programmed" to continue over the whole
168 list. There is no way for us to bail out of applying the search function to the
169 parts of the list that have head `4` and head `5`, too.
170
171 We *can* avoid *some* unneccessary computation. The search function can detect
172 that the result we've accumulated so far during the fold is now `true`, so we
173 don't need to bother comparing `4` or `5` to `3` for equality. That will simplify the
174 computation to some degree, since as we said, numerical comparison in the
175 system we're working in is moderately expensive.
176
177 However, we're still going to have to traverse the remainder of the list. That
178 `true` result will have to be passed along all the way to the leftmost head of
179 the list. Only then can we deliver it to the larger computation in which the
180 search was embedded.
181
182 It would be better if there were some way to "abort" the list traversal. If,
183 having found the element we're looking for (or having determined that the
184 element isn't going to be found), we could just immediately stop traversing the
185 list with our answer. **Continuations** will turn out to let us do that.
186
187 We won't try yet to fully exploit the terrible power of continuations. But
188 there's a way that we can gain their benefits here locally, without yet having
189 a fully general machinery or understanding of what's going on.
190
191 The key is to recall how our implementations of booleans and pairs worked.
192 Remember that with pairs, we supply the pair "handler" to the pair as *an
193 argument*, rather than the other way around:
194
195         pair (\x y. add x y)
196
197 or:
198
199         pair (\x y. x)
200
201 to get the first element of the pair. Of course you can lift that if you want:
202
203 <pre><code>extract_fst &equiv; \pair. pair (\x y. x)</code></pre>
204
205 but at a lower level, the pair is still accepting its handler as an argument,
206 rather than the handler taking the pair as an argument. (The handler gets *the
207 pair's elements*, not the pair itself, as arguments.)
208
209 >       *Terminology*: we'll try to use names of the form `get_foo` for handlers, and
210 names of the form `extract_foo` for lifted versions of them, that accept the
211 lists (or whatever data structure we're working with) as arguments. But we may
212 sometimes forget.
213
214 The v2 implementation of lists followed a similar strategy:
215
216         v2list (\h t. do_something_with_h_and_t) result_if_empty
217
218 If the `v2list` here is not empty, then this will reduce to the result of
219 supplying the list's head and tail to the handler `(\h t.
220 do_something_with_h_and_t)`.
221
222 Now, what we've been imagining ourselves doing with the search through the v3
223 list is something like this:
224
225
226         larger_computation (search_through_the_list_for_3) other_arguments
227
228 That is, the result of our search is supplied as an argument (perhaps together
229 with other arguments) to the "larger computation". Without knowing the
230 evaluation order/reduction strategy, we can't say whether the search is
231 evaluated before or after it's substituted into the larger computation. But
232 semantically, the search is the argument and the larger computation is the
233 function to which it's supplied.
234
235 What if, instead, we did the same kind of thing we did with pairs and v2
236 lists? That is, what if we made the larger computation a "handler" that we
237 passed as an argument to the search?
238
239         the_search (\search_result. larger_computation search_result other_arguments)
240
241 What's the advantage of that, you say. Other than to show off how cleverly
242 you can lift.
243
244 Well, think about it. Think about the difficulty we were having aborting the
245 search. Does this switch-around offer us anything useful?
246
247 It could.
248
249 What if the way we implemented the search procedure looked something like this?
250
251 At a given stage in the search, we wouldn't just apply some function `f` to the
252 head at this stage and the result accumulated so far (from folding the same
253 function, and a base value, to the tail at this stage)...and then pass the result
254 of that application to the embedding, more leftward computation.
255
256 We'd *instead* give `f` a "handler" that expects the result of the current
257 stage *as an argument*, and then evaluates to what you'd get by passing that
258 result leftwards up the list, as before. 
259
260 Why would we do that, you say? Just more flamboyant lifting?
261
262 Well, no, there's a real point here. If we give the function a "handler" that
263 encodes the normal continuation of the fold leftwards through the list, we can
264 also give it other "handlers" too. For example, we can also give it the underlined handler:
265
266
267         the_search (\search_result. larger_computation search_result other_arguments)
268                            ------------------------------------------------------------------
269
270 This "handler" encodes the search's having finished, and delivering a final
271 answer to whatever else you wanted your program to do with the result of the
272 search. If you like, at any stage in the search you might just give an argument
273 to *this* handler, instead of giving an argument to the handler that continues
274 the list traversal leftwards. Semantically, this would amount to *aborting* the
275 list traversal! (As we've said before, whether the rest of the list traversal
276 really gets evaluated will depend on what evaluation order is in place. But
277 semantically we'll have avoided it. Our larger computation  won't depend on the
278 rest of the list traversal having been computed.)
279
280 Do you have the basic idea? Think about how you'd implement it. A good
281 understanding of the v2 lists will give you a helpful model.
282
283 In broad outline, a single stage of the search would look like before, except
284 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.
285
286         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>
287
288 `f2`'s job would be to check whether `3` matches the element we're searching for
289 (here also `3`), and if it does, just evaluate to the result of passing `true` to
290 the abort handler. If it doesn't, then evaluate to the result of passing
291 `false` to the continue-leftwards handler.
292
293 In this case, `f2` wouldn't need to consult the result of folding `f` and `z`
294 over `[2; 1]`, since if we had found the element `3` in more rightward
295 positions of the list, we'd have called the abort handler and this application
296 of `f2` to `3` etc would never be needed. However, in other applications the
297 result of folding `f` and `z` over the more rightward parts of the list would
298 be needed. Consider if you were trying to multiply all the elements of the
299 list, and were going to abort (with the result `0`) if you came across any
300 element in the list that was zero. If you didn't abort, you'd need to know what
301 the more rightward elements of the list multiplied to, because that would
302 affect the answer you passed along to the continue-leftwards handler.
303
304 A **version 5** list encodes the kind of fold operation we're envisaging here,
305 in the same way that v3 (and [v4](/advanced_lambda/#index1h1)) lists encoded
306 the simpler fold operation. Roughly, the list `[5;4;3;2;1]` would look like
307 this:
308
309
310         \f2 z continue_leftwards_handler abort_handler.
311                 <fold f2 and z over [4;3;2;1]>
312                 (\result_of_folding_over_4321. f2 5 result_of_folding_over_4321  continue_leftwards_handler abort_handler)
313                 abort_handler
314
315         ; or, expanding the fold over [4;3;2;1]:
316
317         \f2 z continue_leftwards_handler abort_handler.
318                 (\continue_leftwards_handler abort_handler.
319                         <fold f2 and z over [3;2;1]>
320                         (\result_of_folding_over_321. f2 4 result_of_folding_over_321 continue_leftwards_handler abort_handler)
321                         abort_handler
322                 )
323                 (\result_of_folding_over_4321. f2 5 result_of_folding_over_4321  continue_leftwards_handler abort_handler)
324                 abort_handler
325
326         ; and so on
327         
328 Remarks: the `larger_computation` handler should be supplied as both the
329 `continue_leftwards_handler` and the `abort_handler` for the leftmost
330 application, where the head `5` is supplied to `f2`; because the result of this
331 application should be passed to the larger computation, whether it's a "fall
332 off the left end of the list" result or it's a "I'm finished, possibly early"
333 result. The `larger_computation` handler also then gets passed to the next
334 rightmost stage, where the head `4` is supplied to `f2`, as the `abort_handler` to
335 use if that stage decides it has an early answer.
336
337 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
338
339         (\result_of_folding_over_4321. f2 5 result_of_folding_over_4321 <one_handler> <another_handler>)
340
341 *to* the application of `f2` to `4` as its "continue" handler. The application of `f2`
342 to `4` can decide whether this handler, or the other, "abort" handler, should be
343 given an argument and constitute its result.
344
345
346 I'll say once again: we're using temporally-loaded vocabulary throughout this,
347 but really all we're in a position to mean by that are claims about the result
348 of the complex expression semantically depending only on this, not on that. A
349 demon evaluator who custom-picked the evaluation order to make things maximally
350 bad for you could ensure that all the semantically unnecessary computations got
351 evaluated anyway. We don't yet know any way to prevent that. Later, we'll see
352 ways to *guarantee* one evaluation order rather than another. Of
353 course, in any real computing environment you'll know in advance that you're
354 dealing with a fixed evaluation order and you'll be able to program efficiently
355 around that.
356
357 In detail, then, here's what our v5 lists will look like:
358
359         let empty = \f2 z continue_handler abort_handler. continue_handler z  in
360         let make_list = \h t. \f2 z continue_handler abort_handler.
361                 t f2 z (\sofar. f2 h sofar continue_handler abort_handler) abort_handler  in
362         let isempty = \lst larger_computation. lst
363                         ; here's our f2
364                         (\hd sofar continue_handler abort_handler. abort_handler false)
365                         ; here's our z
366                         true
367                         ; here's the continue_handler for the leftmost application of f2
368                         larger_computation
369                         ; here's the abort_handler
370                         larger_computation  in
371         let extract_head = \lst larger_computation. lst
372                         ; here's our f2
373                         (\hd sofar continue_handler abort_handler. continue_handler hd)
374                         ; here's our z
375                         junk
376                         ; here's the continue_handler for the leftmost application of f2
377                         larger_computation
378                         ; here's the abort_handler
379                         larger_computation  in
380         let extract_tail = ; left as exercise
381
382 These functions are used like this:
383
384         let my_list = make_list a (make_list b (make_list c empty) in
385         extract_head my_list larger_computation
386
387 If you just want to see `my_list`'s head, the use `I` as the
388 `larger_computation`.
389
390 What we've done here does take some work to follow. But it should be within
391 your reach. And once you have followed it, you'll be well on your way to
392 appreciating the full terrible power of continuations.
393
394 <!-- (Silly [cultural reference](http://www.newgrounds.com/portal/view/33440).) -->
395
396 Of course, like everything elegant and exciting in this seminar, [Oleg
397 discusses it in much more
398 detail](http://okmij.org/ftp/Streams.html#enumerator-stream).
399
400 >       *Comments*:
401
402 >       1.      The technique deployed here, and in the v2 lists, and in our
403 >       implementations of pairs and booleans, is known as 
404 >       **continuation-passing style** programming.
405
406 >       2.      We're still building the list as a right fold, so in a sense the
407 >       application of `f2` to the leftmost element `5` is "outermost". However,
408 >       this "outermost" application is getting lifted, and passed as a *handler*
409 >       to the next right application. Which is in turn getting lifted, and
410 >       passed to its next right application, and so on. So if you
411 >       trace the evaluation of the `extract_head` function to the list `[5;4;3;2;1]`,
412 >       you'll see `1` gets passed as a "this is the head sofar" answer to its
413 >       `continue_handler`; then that answer is discarded and `2` is
414 >       passed as a "this is the head sofar" answer to *its* `continue_handler`,
415 >       and so on. All those steps have to be evaluated to finally get the result
416 >       that `5` is the outer/leftmost head of the list. That's not an efficient way
417 >       to get the leftmost head.
418 >       
419 >       We could improve this by building lists as **left folds**. What's that?
420 >       
421 >       Well, the right fold of `f` over a list `[a;b;c;d;e]`, using starting value z, is:
422 >       
423 >                       f a (f b (f c (f d (f e z))))
424 >       
425 >       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:
426 >       
427 >                       f (f (f (f (f z a) b) c) d) e
428 >       
429 >       or, if we preferred the arguments to each `f` flipped:
430 >       
431 >                       f e (f d (f c (f b (f a z))))
432 >       
433 >       Recall we implemented v3 lists as their own right-fold functions. We could
434 >       instead implement lists as their own left-fold functions. To do that with our
435 >       v5 lists, we'd replace above:
436 >       
437 >                       let make_list = \h t. \f2 z continue_handler abort_handler.
438 >                               f2 h z (\z. t f2 z continue_handler abort_handler) abort_handler
439 >       
440 >       Having done that, now `extract_head` can return the leftmost head
441 >       directly, using its `abort_handler`:
442 >       
443 >                       let extract_head = \lst larger_computation. lst
444 >                                       (\hd sofar continue_handler abort_handler. abort_handler hd)
445 >                                       junk
446 >                                       larger_computation
447 >                                       larger_computation
448 >       
449 >       3.      To extract tails efficiently, too, it'd be nice to fuse the apparatus
450 >       developed in these v5 lists with the ideas from 
451 >       [v4](/advanced_lambda/#index1h1) lists. But that is left as an exercise.
452