edits
[lambda.git] / from_lists_to_continuations.mdwn
1 Refunctionalizing zippers: from lists to continuations
2 ------------------------------------------------------
3
4 If zippers are continuations reified (defuntionalized), then one route
5 to continuations is to re-functionalize a zipper.  Then the
6 concreteness and understandability of the zipper provides a way of
7 understanding and equivalent treatment using continuations.
8
9 Let's work with lists of chars for a change.  To maximize readability, we'll
10 indulge in an abbreviatory convention that "abSd" abbreviates the
11 list `['a'; 'b'; 'S'; 'd']`.
12
13 We will set out to compute a deceptively simple-seeming **task: given a
14 string, replace each occurrence of 'S' in that string with a copy of
15 the string up to that point.**
16
17 We'll define a function `t` (for "task") that maps strings to their
18 updated version.
19
20 Expected behavior:
21
22 <pre>
23 t "abSd" ~~> "ababd"
24 </pre>   
25
26
27 In linguistic terms, this is a kind of anaphora
28 resolution, where `'S'` is functioning like an anaphoric element, and
29 the preceding string portion is the antecedent.
30
31 This simple task gives rise to considerable complexity.
32 Note that it matters which 'S' you target first (the position of the *
33 indicates the targeted 'S'):
34
35 <pre>
36     t "aSbS" 
37         *
38 ~~> t "aabS" 
39           *
40 ~~> "aabaab"
41 </pre>
42
43 versus
44
45 <pre>
46     t "aSbS"
47           *
48 ~~> t "aSbaSb" 
49         *
50 ~~> t "aabaSb"
51            *
52 ~~> "aabaaabab"
53 </pre>   
54
55 versus
56
57 <pre>
58     t "aSbS"
59           *
60 ~~> t "aSbaSb"
61            *
62 ~~> t "aSbaaSbab"
63             *
64 ~~> t "aSbaaaSbaabab"
65              *
66 ~~> ...
67 </pre>
68
69 Apparently, this task, as simple as it is, is a form of computation,
70 and the order in which the `'S'`s get evaluated can lead to divergent
71 behavior.
72
73 For now, we'll agree to always evaluate the leftmost `'S'`, which
74 guarantees termination, and a final string without any `'S'` in it.
75
76 This is a task well-suited to using a zipper.  We'll define a function
77 `tz` (for task with zippers), which accomplishes the task by mapping a
78 char list zipper to a char list.  We'll call the two parts of the
79 zipper `unzipped` and `zipped`; we start with a fully zipped list, and
80 move elements from the zipped part to the unzipped part by pulling the
81 zipper down until the entire list has been unzipped (at which point
82 the zipped half of the zipper will be empty).
83
84 <pre>
85 type 'a list_zipper = ('a list) * ('a list);;
86
87 let rec tz (z:char list_zipper) = 
88   match z with (unzipped, []) -> List.rev(unzipped) (* Done! *)
89              | (unzipped, 'S'::zipped) -> tz ((List.append unzipped unzipped), zipped) 
90              | (unzipped, target::zipped) -> tz (target::unzipped, zipped);; (* Pull zipper *)
91
92 # tz ([], ['a'; 'b'; 'S'; 'd']);;
93 - : char list = ['a'; 'b'; 'a'; 'b'; 'd']
94
95 # tz ([], ['a'; 'S'; 'b'; 'S']);;
96 - : char list = ['a'; 'a'; 'b'; 'a'; 'a'; 'b']
97 </pre>
98
99 Note that this implementation enforces the evaluate-leftmost rule.
100 Task completed.
101
102 One way to see exactly what is going on is to watch the zipper in
103 action by tracing the execution of `tz`.  By using the `#trace`
104 directive in the Ocaml interpreter, the system will print out the
105 arguments to `tz` each time it is (recursively) called.  Note that the
106 lines with left-facing arrows (`<--`) show (recursive) calls to `tz`,
107 giving the value of its argument (a zipper), and the lines with
108 right-facing arrows (`-->`) show the output of each recursive call, a
109 simple list.  
110
111 <pre>
112 # #trace tz;;
113 t1 is now traced.
114 # tz ([], ['a'; 'b'; 'S'; 'd']);;
115 tz <-- ([], ['a'; 'b'; 'S'; 'd'])
116 tz <-- (['a'], ['b'; 'S'; 'd'])         (* Pull zipper *)
117 tz <-- (['b'; 'a'], ['S'; 'd'])         (* Pull zipper *)
118 tz <-- (['b'; 'a'; 'b'; 'a'], ['d'])    (* Special step *)
119 tz <-- (['d'; 'b'; 'a'; 'b'; 'a'], [])  (* Pull zipper *)
120 tz --> ['a'; 'b'; 'a'; 'b'; 'd']        (* Output reversed *)
121 tz --> ['a'; 'b'; 'a'; 'b'; 'd']
122 tz --> ['a'; 'b'; 'a'; 'b'; 'd']
123 tz --> ['a'; 'b'; 'a'; 'b'; 'd']
124 tz --> ['a'; 'b'; 'a'; 'b'; 'd']
125 - : char list = ['a'; 'b'; 'a'; 'b'; 'd'] 
126 </pre>
127
128 The nice thing about computations involving lists is that it's so easy
129 to visualize them as a data structure.  Eventually, we want to get to
130 a place where we can talk about more abstract computations.  In order
131 to get there, we'll first do the exact same thing we just did with
132 concrete zippers using procedures instead.
133
134 Think of a list as a procedural recipe: `['a'; 'b'; 'S'; 'd']` 
135 is the result of the computation `a::(b::(S::(d::[])))` (or, in our old
136 style, `makelist 'a' (makelist 'b' (makelist 'S' (makelist 'c' empty)))`).
137 The recipe for constructing the list goes like this:
138
139 <pre>
140 (0)  Start with the empty list []
141 (1)  make a new list whose first element is 'd' and whose tail is the list constructed in step (0)
142 (2)  make a new list whose first element is 'S' and whose tail is the list constructed in step (1)
143 -----------------------------------------
144 (3)  make a new list whose first element is 'b' and whose tail is the list constructed in step (2)
145 (4)  make a new list whose first element is 'a' and whose tail is the list constructed in step (3)
146 </pre>
147
148 What is the type of each of these steps?  Well, it will be a function
149 from the result of the previous step (a list) to a new list: it will
150 be a function of type `char list -> char list`.  We'll call each step
151 (or group of steps) a **continuation** of the recipe.  So in this
152 context, a continuation is a function of type `char list -> char
153 list`.  For instance, the continuation corresponding to the portion of
154 the recipe below the horizontal line is the function `fun (tail:char
155 list) -> a::(b::tail)`.
156
157 This means that we can now represent the unzipped part of our zipper
158 as a continuation: a function describing how to finish building the
159 list.  We'll write a new function, `tc` (for task with continuations),
160 that will take an input list (not a zipper!) and a continuation and
161 return a processed list.  The structure and the behavior will follow
162 that of `tz` above, with some small but interesting differences.
163 We've included the orginal `tz` to facilitate detailed comparison:
164
165 <pre>
166 let rec tz (z:char list_zipper) = 
167   match z with (unzipped, []) -> List.rev(unzipped) (* Done! *)
168              | (unzipped, 'S'::zipped) -> tz ((List.append unzipped unzipped), zipped) 
169              | (unzipped, target::zipped) -> tz (target::unzipped, zipped);; (* Pull zipper *)
170
171 let rec tc (l: char list) (c: (char list) -> (char list)) =
172   match l with [] -> List.rev (c [])
173              | 'S'::zipped -> tc zipped (fun x -> c (c x))
174              | target::zipped -> tc zipped (fun x -> target::(c x));;
175
176 # tc ['a'; 'b'; 'S'; 'd'] (fun x -> x);;
177 - : char list = ['a'; 'b'; 'a'; 'b'; 'd']
178
179 # tc ['a'; 'S'; 'b'; 'S'] (fun x -> x);;
180 - : char list = ['a'; 'a'; 'b'; 'a'; 'a'; 'b']
181 </pre>
182
183 To emphasize the parallel, we've re-used the names `zipped` and
184 `target`.  The trace of the procedure will show that these variables
185 take on the same values in the same series of steps as they did during
186 the execution of `tz` above.  There will once again be one initial and
187 four recursive calls to `tc`, and `zipped` will take on the values
188 `"bSd"`, `"Sd"`, `"d"`, and `""` (and, once again, on the final call,
189 the first `match` clause will fire, so the the variable `zipper` will
190 not be instantiated).
191
192 I have not called the functional argument `unzipped`, although that is
193 what the parallel would suggest.  The reason is that `unzipped` (in
194 `tz`) is a list, but `c` (in `tc`) is a function.  ('c' stands for
195 'continuation', of course.)  That's the most crucial difference, the
196 point of the excercise, and it should be emphasized.  For instance,
197 you can see this difference in the fact that in `tz`, we have to glue
198 together the two instances of `unzipped` with an explicit (and
199 relatively computationally inefficient) `List.append`.  In the `tc`
200 version of the task, we simply compose `c` with itself: `c o c = fun x
201 -> c (c x)`.
202
203 Why use the identity function as the initial continuation?  Well, if
204 you have already constructed the initial list `"abSd"`, what's the next
205 step in the recipe to produce the desired result, i.e, the very same
206 list, `"abSd"`?  Clearly, the identity continuation.
207
208 A good way to test your understanding is to figure out what the
209 continuation function `c` must be at the point in the computation when
210 `tc` is called with the first argument `"Sd"`.  Two choices: is it
211 `fun x -> a::b::x`, or it is `fun x -> b::a::x`?  The way to see if
212 you're right is to execute the following command and see what happens:
213
214     tc ['S'; 'd'] (fun x -> 'a'::'b'::x);;
215
216 There are a number of interesting directions we can go with this task.
217 The reason this task was chosen is because it can be viewed as a
218 simplified picture of a computation using continuations, where `'S'`
219 plays the role of a control operator with some similarities to what is
220 often called `shift`.  In the analogy, the input list portrays a
221 sequence of functional applications, where `[f1; f2; f3; x]` represents
222 `f1(f2(f3 x))`.  The limitation of the analogy is that it is only
223 possible to represent computations in which the applications are
224 always right-branching, i.e., the computation `((f1 f2) f3) x` cannot
225 be directly represented.
226
227 One possibile development is that we could add a special symbol `'#'`,
228 and then the task would be to copy from the target `'S'` only back to
229 the closest `'#'`.  This would allow the task to simulate delimited
230 continuations with embedded prompts.
231
232 The reason the task is well-suited to the list zipper is in part
233 because the list monad has an intimate connection with continuations.
234 The following section explores this connection.  We'll return to the
235 list task after talking about generalized quantifiers below.
236
237
238