from zippers to lists to continuations
[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