edits
[lambda.git] / zipper-lists-continuations.mdwn
1 Today we're going to encounter continuations.  We're going to come at
2 them from three different directions, and each time we're going to end
3 up at the same place: a particular monad, which we'll call the
4 continuation monad.
5
6 The three approches are:
7
8 *    Rethinking the list monad;
9 *    Montague's PTQ treatment of DPs as generalized quantifiers; and
10 *    Refunctionalizing zippers (Shan: zippers are defunctionalized continuations);
11
12 Rethinking the list monad
13 -------------------------
14
15 To construct a monad, the key element is to settle on a type
16 constructor, and the monad naturally follows from that.  I'll remind
17 you of some examples of how monads follow from the type constructor in
18 a moment.  This will involve some review of familair material, but
19 it's worth doing for two reasons: it will set up a pattern for the new
20 discussion further below, and it will tie together some previously
21 unconnected elements of the course (more specifically, version 3 lists
22 and monads).
23
24 For instance, take the **Reader Monad**.  Once we decide that the type
25 constructor is
26
27     type 'a reader = fun e:env -> 'a
28
29 then we can deduce the unit and the bind:
30
31     runit x:'a -> 'a reader = fun (e:env) -> x
32
33 Since the type of an `'a reader` is `fun e:env -> 'a` (by definition),
34 the type of the `runit` function is `'a -> e:env -> 'a`, which is a
35 specific case of the type of the *K* combinator.  So it makes sense
36 that *K* is the unit for the reader monad.
37
38 Since the type of the `bind` operator is required to be
39
40     r_bind:('a reader) -> ('a -> 'b reader) -> ('b reader)
41
42 We can deduce the correct `bind` function as follows:
43
44     r_bind (u:'a reader) (f:'a -> 'b reader):('b reader) =
45
46 We have to open up the `u` box and get out the `'a` object in order to
47 feed it to `f`.  Since `u` is a function from environments to
48 objects of type `'a`, we'll have
49
50          .... f (u e) ...
51
52 This subexpression types to `'b reader`, which is good.  The only
53 problem is that we don't have an `e`, so we have to abstract over that
54 variable:
55
56          fun e -> f (u e) ...
57
58 This types to `env -> 'b reader`, but we want to end up with `env ->
59 'b`.  The easiest way to turn a 'b reader into a 'b is to apply it to
60 an environment.  So we end up as follows:
61
62     r_bind (u:'a reader) (f:'a -> 'b reader):('b reader) = f (u e) e         
63
64 And we're done.
65
66 The **State Monad** is similar.  We somehow intuit that we want to use
67 the following type constructor:
68
69     type 'a state = 'store -> ('a, 'store)
70
71 So our unit is naturally
72
73     let s_unit (x:'a):('a state) = fun (s:'store) -> (x, s)
74
75 And we deduce the bind in a way similar to the reasoning given above.
76 First, we need to apply `f` to the contents of the `u` box:
77
78     let s_bind (u:'a state) (f:'a -> ('b state)):('b state) = 
79
80 But unlocking the `u` box is a little more complicated.  As before, we
81 need to posit a state `s` that we can apply `u` to.  Once we do so,
82 however, we won't have an `'a`, we'll have a pair whose first element
83 is an `'a`.  So we have to unpack the pair:
84
85         ... let (a, s') = u s in ... (f a) ...
86
87 Abstracting over the `s` and adjusting the types gives the result:
88
89     let s_bind (u:'a state) (f:'a -> ('b state)):('b state) = 
90       fun (s:state) -> let (a, s') = u s in f a s'
91
92 The **Option Monad** doesn't follow the same pattern so closely, so we
93 won't pause to explore it here, though conceptually its unit and bind
94 follow just as naturally from its type constructor.
95
96 Our other familiar monad is the **List Monad**, which we were told
97 looks like this:
98
99     type 'a list = ['a];;
100     l_unit (x:'a) = [x];;
101     l_bind u f = List.concat (List.map f u);;
102
103 Recall that `List.map` take a function and a list and returns the
104 result to applying the function to the elements of the list:
105
106     List.map (fun i -> [i;i+1]) [1;2] ~~> [[1; 2]; [2; 3]]
107
108 and List.concat takes a list of lists and erases the embdded list
109 boundaries:
110
111     List.concat [[1; 2]; [2; 3]] ~~> [1; 2; 2; 3]
112
113 And sure enough, 
114
115     l_bind [1;2] (fun i -> [i, i+1]) ~~> [1; 2; 2; 3]
116
117 But where is the reasoning that led us to this unit and bind?
118 And what is the type `['a]`?  Magic.
119
120 So let's take a *completely useless digressing* and see if we can
121 gain some insight into the details of the List monad.  Let's choose
122 type constructor that we can peer into, using some of the technology
123 we built up so laboriously during the first half of the course.  I'm
124 going to use type 3 lists, partly because I know they'll give the
125 result I want, but also because they're my favorite.  These were the
126 lists that made lists look like Church numerals with extra bits
127 embdded in them:
128
129     empty list:                fun f z -> z
130     list with one element:     fun f z -> f 1 z
131     list with two elements:    fun f z -> f 2 (f 1 z)
132     list with three elements:  fun f z -> f 3 (f 2 (f 1 z))
133
134 and so on.  To save time, we'll let the Ocaml interpreter infer the
135 principle types of these functions (rather than deducing what the
136 types should be):
137
138 <pre>
139 # fun f z -> z;;
140 - : 'a -> 'b -> 'b = <fun>
141 # fun f z -> f 1 z;;
142 - : (int -> 'a -> 'b) -> 'a -> 'b = <fun>
143 # fun f z -> f 2 (f 1 z);;
144 - : (int -> 'a -> 'a) -> 'a -> 'a = <fun>
145 # fun f z -> f 3 (f 2 (f 1 z))
146 - : (int -> 'a -> 'a) -> 'a -> 'a = <fun>
147 </pre>
148
149 Finally, we're getting consistent principle types, so we can stop.
150 These types should remind you of the simply-typed lambda calculus
151 types for Church numerals (`(o -> o) -> o -> o`) with one extra bit
152 thrown in (in this case, and int).
153
154 So here's our type constructor for our hand-rolled lists:
155
156     type 'a list' = (int -> 'a -> 'a) -> 'a -> 'a
157
158 Generalizing to lists that contain any kind of element (not just
159 ints), we have
160
161     type ('a, 'b) list' = ('a -> 'b -> 'b) -> 'b -> 'b
162
163 So an `('a, 'b) list'` is a list containing elements of type `'a`,
164 where `'b` is the type of some part of the plumbing.  This is more
165 general than an ordinary Ocaml list, but we'll see how to map them
166 into Ocaml lists soon.  We don't need to grasp the role of the `'b`'s
167 in order to proceed to build a monad:
168
169     l'_unit (x:'a):(('a, 'b) list) = fun x -> fun f z -> f x z
170
171 No problem.  Arriving at bind is a little more complicated, but
172 exactly the same principles apply, you just have to be careful and
173 systematic about it.
174
175     l'_bind (u:('a,'b) list') (f:'a -> ('c, 'd) list'): ('c, 'd) list'  = ...
176
177 Unfortunately, we'll need to spell out the types:
178
179     l'_bind (u: ('a -> 'b -> 'b) -> 'b -> 'b)
180             (f: 'a -> ('c -> 'd -> 'd) -> 'd -> 'd)
181             : ('c -> 'd -> 'd) -> 'd -> 'd = ...
182
183 It's a rookie mistake to quail before complicated types.  You should
184 be no more intimiated by complex types than by a linguistic tree with
185 deeply embedded branches: complex structure created by repeated
186 application of simple rules.
187
188 As usual, we need to unpack the `u` box.  Examine the type of `u`.
189 This time, `u` will only deliver up its contents if we give `u` as an
190 argument a function expecting an `'a`.  Once that argument is applied
191 to an object of type `'a`, we'll have what we need.  Thus:
192
193       .... u (fun (x:'a) -> ... (f a) ... ) ...
194
195 In order for `u` to have the kind of argument it needs, we have to
196 adjust `(f a)` (which has type `('c -> 'd -> 'd) -> 'd -> 'd`) in
197 order to deliver something of type `'b -> 'b`.  The easiest way is to
198 alias `'d` to `'b`, and provide `(f a)` with an argument of type `'c
199 -> 'b -> 'b`.  Thus:
200
201     l'_bind (u: ('a -> 'b -> 'b) -> 'b -> 'b)
202             (f: 'a -> ('c -> 'b -> 'b) -> 'b -> 'b)
203             : ('c -> 'b -> 'b) -> 'b -> 'b = 
204       .... u (fun (x:'a) -> f a k) ...
205
206 [Excercise: can you arrive at a fully general bind for this type
207 constructor, one that does not collapse `'d`'s with `'b`'s?]
208
209 As usual, we have to abstract over `k`, but this time, no further
210 adjustments are needed:
211
212     l'_bind (u: ('a -> 'b -> 'b) -> 'b -> 'b)
213             (f: 'a -> ('c -> 'b -> 'b) -> 'b -> 'b)
214             : ('c -> 'b -> 'b) -> 'b -> 'b = 
215       fun (k:'c -> 'b -> 'b) -> u (fun (x:'a) -> f a k)
216
217 You should carefully check to make sure that this term is consistent
218 with the typing.
219
220 Our theory is that this monad should be capable of exactly
221 replicating the behavior of the standard List monad.  Let's test:
222
223
224     l_bind [1;2] (fun i -> [i, i+1]) ~~> [1; 2; 2; 3]
225
226     l'_bind (fun f z -> f 1 (f 2 z)) 
227             (fun i -> fun f z -> f i (f (i+1) z)) ~~> <fun>
228
229 Sigh.  Ocaml won't show us our own list.  So we have to choose an `f`
230 and a `z` that will turn our hand-crafted lists into standard Ocaml
231 lists, so that they will print out.
232
233 # let cons h t = h :: t;;  (* Ocaml is stupid about :: *)
234 # l'_bind (fun f z -> f 1 (f 2 z)) 
235           (fun i -> fun f z -> f i (f (i+1) z)) cons [];;
236 - : int list = [1; 2; 2; 3]
237
238 Ta da!
239
240 Just for mnemonic purposes (sneaking in an instance of eta reduction
241 to the definition of unit), we can summarize the result as follows:
242
243     type ('a, 'b) list' = ('a -> 'b -> 'b) -> 'b -> 'b
244     l'_unit x = fun f -> f x
245     l'_bind u f = fun k -> u (fun x -> f x k)
246
247 To bad this digression, though it ties together various
248 elements of the course, has *no relevance whatsoever* to the topic of
249 continuations.
250
251 Montague's PTQ treatment of DPs as generalized quantifiers
252 ----------------------------------------------------------
253
254 We've hinted that Montague's treatment of DPs as generalized
255 quantifiers embodies the spirit of continuations (see de Groote 2001,
256 Barker 2002 for lengthy discussion).  Let's see why.  
257
258 First, we'll need a type constructor.  As you probably know, 
259 Montague replaced individual-denoting determiner phrases (with type `e`)
260 with generalized quantifiers (with [extensional] type `(e -> t) -> t`.
261 In particular, the denotation of a proper name like *John*, which
262 might originally denote a object `j` of type `e`, came to denote a
263 generalized quantifier `fun pred -> pred j` of type `(e -> t) -> t`.
264 Let's write a general function that will map individuals into their
265 corresponding generalized quantifier:
266
267    gqize (x:e) = fun (p:e->t) -> p x
268
269 This function wraps up an individual in a fancy box.  That is to say,
270 we are in the presence of a monad.  The type constructor, the unit and
271 the bind follow naturally.  We've done this enough times that I won't
272 belabor the construction of the bind function, the derivation is
273 similar to the List monad just given:
274
275    type 'a continuation = ('a -> 'b) -> 'b
276    c_unit (x:'a) = fun (p:'a -> 'b) -> p x
277    c_bind (u:('a -> 'b) -> 'b) (f: 'a -> ('c -> 'd) -> 'd): ('c -> 'd) -> 'd =
278      fun (k:'a -> 'b) -> u (fun (x:'a) -> f x k)
279
280 How similar is it to the List monad?  Let's examine the type
281 constructor and the terms from the list monad derived above:
282
283     type ('a, 'b) list' = ('a -> 'b -> 'b) -> 'b -> 'b
284     l'_unit x = fun f -> f x                 
285     l'_bind u f = fun k -> u (fun x -> f x k)
286
287 (I performed a sneaky but valid eta reduction in the unit term.)
288
289 The unit and the bind for the Montague continuation monad and the
290 homemade List monad are the same terms!  In other words, the behavior
291 of the List monad and the behavior of the continuations monad are
292 parallel in a deep sense.  To emphasize the parallel, we can
293 instantiate the type of the list' monad using the Ocaml list type:
294
295     type 'a c_list = ('a -> 'a list) -> 'a list
296     let c_list_unit x = fun f -> f x;;
297     let c_list_bind u f = fun k -> u (fun x -> f x k);;
298
299 Have we really discovered that lists are secretly continuations?
300 Or have we merely found a way of simulating lists using list
301 continuations?  Both perspectives are valid, and we can use our
302 intuitions about the list monad to understand continuations, and vice
303 versa.  The connections will be expecially relevant when we consider 
304 indefinites and Hamblin semantics on the linguistic side, and
305 non-determinism on the list monad side.
306