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