edits
[lambda.git] / from_lists_to_continuations.mdwn
1
2 Refunctionalizing zippers: from lists to continuations
3 ------------------------------------------------------
4
5 If zippers are continuations reified (defuntionalized), then one route
6 to continuations is to re-functionalize a zipper.  Then the
7 concreteness and understandability of the zipper provides a way of
8 understanding and equivalent treatment using continuations.
9
10 Let's work with lists of chars for a change.  To maximize readability, we'll
11 indulge in an abbreviatory convention that "abSd" abbreviates the
12 list `['a'; 'b'; 'S'; 'd']`.
13
14 We will set out to compute a deceptively simple-seeming **task: given a
15 string, replace each occurrence of 'S' in that string with a copy of
16 the string up to that point.**
17
18 We'll define a function `t` (for "task") that maps strings to their
19 updated version.
20
21 Expected behavior:
22
23 <pre>
24 t "abSd" ~~> "ababd"
25 </pre>   
26
27
28 In linguistic terms, this is a kind of anaphora
29 resolution, where `'S'` is functioning like an anaphoric element, and
30 the preceding string portion is the antecedent.
31
32 This deceptively simple task gives rise to some mind-bending complexity.
33 Note that it matters which 'S' you target first (the position of the *
34 indicates the targeted 'S'):
35
36 <pre>
37     t "aSbS" 
38         *
39 ~~> t "aabS" 
40           *
41 ~~> "aabaab"
42 </pre>
43
44 versus
45
46 <pre>
47     t "aSbS"
48           *
49 ~~> t "aSbaSb" 
50         *
51 ~~> t "aabaSb"
52            *
53 ~~> "aabaaabab"
54 </pre>   
55
56 versus
57
58 <pre>
59     t "aSbS"
60           *
61 ~~> t "aSbaSb"
62            *
63 ~~> t "aSbaaSbab"
64             *
65 ~~> t "aSbaaaSbaabab"
66              *
67 ~~> ...
68 </pre>
69
70 Aparently, this task, as simple as it is, is a form of computation,
71 and the order in which the `'S'`s get evaluated can lead to divergent
72 behavior.
73
74 For now, we'll agree to always evaluate the leftmost `'S'`, which
75 guarantees termination, and a final string without any `'S'` in it.
76
77 This is a task well-suited to using a zipper.  We'll define a function
78 `tz` (for task with zippers), which accomplishes the task by mapping a
79 char list zipper to a char list.  We'll call the two parts of the
80 zipper `unzipped` and `zipped`; we start with a fully zipped list, and
81 move elements to the zipped part by pulling the zipped down until the
82 entire list has been unzipped (and so the zipped half of the zipper is 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 (recurcively) 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 zipper using procedures.  
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 a **continuation** of the recipe.  So in this context, a continuation
152 is a function of type `char list -> char list`.  For instance, the
153 continuation corresponding to the portion of the recipe below the
154 horizontal line is the function `fun (tail:char list) -> a::(b::tail)`.
155
156 This means that we can now represent the unzipped part of our
157 zipper--the part we've already unzipped--as a continuation: a function
158 describing how to finish building the list.  We'll write a new
159 function, `tc` (for task with continuations), that will take an input
160 list (not a zipper!) and a continuation and return a processed list.
161 The structure and the behavior will follow that of `tz` above, with
162 some small but interesting differences.  We've included the orginal
163 `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']
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, I'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` is a
194 list, but `c` is a function.  That's the most crucial difference, the
195 point of the excercise, and it should be emphasized.  For instance,
196 you can see this difference in the fact that in `tz`, we have to glue
197 together the two instances of `unzipped` with an explicit `List.append`.
198 In the `tc` version of the task, we simply compose `c` with itself: 
199 `c o c = fun x -> c (c x)`.
200
201 Why use the identity function as the initial continuation?  Well, if
202 you have already constructed the list "abSd", what's the next step in
203 the recipe to produce the desired result (which is the same list,
204 "abSd")?  Clearly, the identity continuation.
205
206 A good way to test your understanding is to figure out what the
207 continuation function `c` must be at the point in the computation when
208 `tc` is called with the first argument `"Sd"`.  Two choices: is it
209 `fun x -> a::b::x`, or it is `fun x -> b::a::x`?  
210 The way to see if you're right is to execute the following 
211 command and see what happens:
212
213     tc ['S'; 'd'] (fun x -> 'a'::'b'::x);;
214
215 There are a number of interesting directions we can go with this task.
216 The task was chosen because the computation can be viewed as a
217 simplified picture of a computation using continuations, where `'S'`
218 plays the role of a control operator with some similarities to what is
219 often called `shift`.  In the analogy, the list portrays a string of
220 functional applications, where `[f1; f2; f3; x]` represents `f1(f2(f3
221 x))`.  The limitation of the analogy is that it is only possible to
222 represent computations in which the applications are always
223 right-branching, i.e., the computation `((f1 f2) f3) x` cannot be
224 directly represented.
225
226 One possibile development is that we could add a special symbol `'#'`,
227 and then the task would be to copy from the target `'S'` only back to
228 the closest `'#'`.  This would allow the task to simulate delimited
229 continuations (for right-branching computations).
230
231 The task is well-suited to the list zipper because the list monad has
232 an intimate connection with continuations.  The following section
233 makes this connection.  We'll return to the list task after talking
234 about generalized quantifiers below.
235