1be499b023d19ea5b1da89c5ccb18002a3b5e1b9
[lambda.git] / manipulating_trees_with_monads.mdwn
1 [[!toc]]
2
3
4 Manipulating trees with monads
5 ------------------------------
6
7 This thread develops an idea based on a detailed suggestion of Ken
8 Shan's.  We'll build a series of functions that operate on trees,
9 doing various things, including replacing leaves, counting nodes, and
10 converting a tree to a list of leaves.  The end result will be an
11 application for continuations.
12
13 From an engineering standpoint, we'll build a tree transformer that
14 deals in monads.  We can modify the behavior of the system by swapping
15 one monad for another.  (We've already seen how adding a monad can add
16 a layer of funtionality without disturbing the underlying system, for
17 instance, in the way that the reader monad allowed us to add a layer
18 of intensionality to an extensional grammar, but we have not yet seen
19 the utility of replacing one monad with other.)
20
21 First, we'll be needing a lot of trees during the remainder of the
22 course.  Here's a type constructor for binary trees:
23
24     type 'a tree = Leaf of 'a | Node of ('a tree * 'a tree)
25
26 These are trees in which the internal nodes do not have labels.  [How
27 would you adjust the type constructor to allow for labels on the
28 internal nodes?]
29
30 We'll be using trees where the nodes are integers, e.g.,
31
32
33 <pre>
34 let t1 = Node ((Node ((Leaf 2), (Leaf 3))),
35                (Node ((Leaf 5),(Node ((Leaf 7),
36                                       (Leaf 11))))))
37
38     .
39  ___|___
40  |     |
41  .     .
42 _|__  _|__
43 |  |  |  |
44 2  3  5  .
45         _|__
46         |  |
47         7  11
48 </pre>
49
50 Our first task will be to replace each leaf with its double:
51
52 <pre>
53 let rec treemap (newleaf:'a -> 'b) (t:'a tree):('b tree) =
54   match t with Leaf x -> Leaf (newleaf x)
55              | Node (l, r) -> Node ((treemap newleaf l),
56                                     (treemap newleaf r));;
57 </pre>
58 `treemap` takes a function that transforms old leaves into new leaves, 
59 and maps that function over all the leaves in the tree, leaving the
60 structure of the tree unchanged.  For instance:
61
62 <pre>
63 let double i = i + i;;
64 treemap double t1;;
65 - : int tree =
66 Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
67
68     .
69  ___|____
70  |      |
71  .      .
72 _|__  __|__
73 |  |  |   |
74 4  6  10  .
75         __|___
76         |    |
77         14   22
78 </pre>
79
80 We could have built the doubling operation right into the `treemap`
81 code.  However, because what to do to each leaf is a parameter, we can
82 decide to do something else to the leaves without needing to rewrite
83 `treemap`.  For instance, we can easily square each leaf instead by
84 supplying the appropriate `int -> int` operation in place of `double`:
85
86 <pre>
87 let square x = x * x;;
88 treemap square t1;;
89 - : int tree =ppp
90 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
91 </pre>
92
93 Note that what `treemap` does is take some global, contextual
94 information---what to do to each leaf---and supplies that information
95 to each subpart of the computation.  In other words, `treemap` has the
96 behavior of a reader monad.  Let's make that explicit.  
97
98 In general, we're on a journey of making our treemap function more and
99 more flexible.  So the next step---combining the tree transducer with
100 a reader monad---is to have the treemap function return a (monadized)
101 tree that is ready to accept any `int->int` function and produce the
102 updated tree.
103
104 \tree (. (. (f2) (f3))(. (f5) (.(f7)(f11))))
105 <pre>
106 \f    .
107   ____|____
108   |       |
109   .       .
110 __|__   __|__
111 |   |   |   |
112 f2  f3  f5  .
113           __|___
114           |    |
115           f7  f11
116 </pre>
117
118 That is, we want to transform the ordinary tree `t1` (of type `int
119 tree`) into a reader object of type `(int->int)-> int tree`: something 
120 that, when you apply it to an `int->int` function returns an `int
121 tree` in which each leaf `x` has been replaced with `(f x)`.
122
123 With previous readers, we always knew which kind of environment to
124 expect: either an assignment function (the original calculator
125 simulation), a world (the intensionality monad), an integer (the
126 Jacobson-inspired link monad), etc.  In this situation, it will be
127 enough for now to expect that our reader will expect a function of
128 type `int->int`.
129
130 <pre>
131 type 'a reader = (int->int) -> 'a;;  (* mnemonic: e for environment *)
132 let reader_unit (x:'a): 'a reader = fun _ -> x;;
133 let reader_bind (u: 'a reader) (f:'a -> 'c reader):'c reader = fun e -> f (u e) e;;
134 </pre>
135
136 It's easy to figure out how to turn an `int` into an `int reader`:
137
138 <pre>
139 let int2int_reader (x:'a): 'b reader = fun (op:'a -> 'b) -> op x;;
140 int2int_reader 2 (fun i -> i + i);;
141 - : int = 4
142 </pre>
143
144 But what do we do when the integers are scattered over the leaves of a
145 tree?  A binary tree is not the kind of thing that we can apply a
146 function of type `int->int` to.
147
148 <pre>
149 let rec treemonadizer (f:'a -> 'b reader) (t:'a tree):('b tree) reader =
150   match t with Leaf x -> reader_bind (f x) (fun x' -> reader_unit (Leaf x'))
151              | Node (l, r) -> reader_bind (treemonadizer f l) (fun x ->
152                                 reader_bind (treemonadizer f r) (fun y ->
153                                   reader_unit (Node (x, y))));;
154 </pre>
155
156 This function says: give me a function `f` that knows how to turn
157 something of type `'a` into an `'b reader`, and I'll show you how to 
158 turn an `'a tree` into an `'a tree reader`.  In more fanciful terms, 
159 the `treemonadizer` function builds plumbing that connects all of the
160 leaves of a tree into one connected monadic network; it threads the
161 monad through the leaves.
162
163 <pre>
164 # treemonadizer int2int_reader t1 (fun i -> i + i);;
165 - : int tree =
166 Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
167 </pre>
168
169 Here, our environment is the doubling function (`fun i -> i + i`).  If
170 we apply the very same `int tree reader` (namely, `treemonadizer
171 int2int_reader t1`) to a different `int->int` function---say, the
172 squaring function, `fun i -> i * i`---we get an entirely different
173 result:
174
175 <pre>
176 # treemonadizer int2int_reader t1 (fun i -> i * i);;
177 - : int tree =
178 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
179 </pre>
180
181 Now that we have a tree transducer that accepts a monad as a
182 parameter, we can see what it would take to swap in a different monad.
183 For instance, we can use a state monad to count the number of nodes in
184 the tree.
185
186 <pre>
187 type 'a state = int -> 'a * int;;
188 let state_unit x i = (x, i+.5);;
189 let state_bind u f i = let (a, i') = u i in f a (i'+.5);;
190 </pre>
191
192 Gratifyingly, we can use the `treemonadizer` function without any
193 modification whatsoever, except for replacing the (parametric) type
194 `reader` with `state`:
195
196 <pre>
197 let rec treemonadizer (f:'a -> 'b state) (t:'a tree):('b tree) state =
198   match t with Leaf x -> state_bind (f x) (fun x' -> state_unit (Leaf x'))
199              | Node (l, r) -> state_bind (treemonadizer f l) (fun x ->
200                                 state_bind (treemonadizer f r) (fun y ->
201                                   state_unit (Node (x, y))));;
202 </pre>
203
204 Then we can count the number of nodes in the tree:
205
206 <pre>
207 # treemonadizer state_unit t1 0;;
208 - : int tree * int =
209 (Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11))), 13)
210
211     .
212  ___|___
213  |     |
214  .     .
215 _|__  _|__
216 |  |  |  |
217 2  3  5  .
218         _|__
219         |  |
220         7  11
221 </pre>
222
223 Notice that we've counted each internal node twice---it's a good
224 exercise to adjust the code to count each node once.
225
226 One more revealing example before getting down to business: replacing
227 `state` everywhere in `treemonadizer` with `list` gives us
228
229 <pre>
230 # treemonadizer (fun x -> [ [x; square x] ]) t1;;
231 - : int list tree list =
232 [Node
233   (Node (Leaf [2; 4], Leaf [3; 9]),
234    Node (Leaf [5; 25], Node (Leaf [7; 49], Leaf [11; 121])))]
235 </pre>
236
237 Unlike the previous cases, instead of turning a tree into a function
238 from some input to a result, this transformer replaces each `int` with
239 a list of `int`'s.
240
241 Now for the main point.  What if we wanted to convert a tree to a list
242 of leaves?  
243
244 <pre>
245 type ('a, 'r) continuation = ('a -> 'r) -> 'r;;
246 let continuation_unit x c = c x;;
247 let continuation_bind u f c = u (fun a -> f a c);;
248
249 let rec treemonadizer (f:'a -> ('b, 'r) continuation) (t:'a tree):(('b tree), 'r) continuation =
250   match t with Leaf x -> continuation_bind (f x) (fun x' -> continuation_unit (Leaf x'))
251              | Node (l, r) -> continuation_bind (treemonadizer f l) (fun x ->
252                                 continuation_bind (treemonadizer f r) (fun y ->
253                                   continuation_unit (Node (x, y))));;
254 </pre>
255
256 We use the continuation monad described above, and insert the
257 `continuation` type in the appropriate place in the `treemonadizer` code.
258 We then compute:
259
260 <pre>
261 # treemonadizer (fun a c -> a :: (c a)) t1 (fun t -> []);;
262 - : int list = [2; 3; 5; 7; 11]
263 </pre>
264
265 We have found a way of collapsing a tree into a list of its leaves.
266
267 The continuation monad is amazingly flexible; we can use it to
268 simulate some of the computations performed above.  To see how, first
269 note that an interestingly uninteresting thing happens if we use the
270 continuation unit as our first argument to `treemonadizer`, and then
271 apply the result to the identity function:
272
273 <pre>
274 # treemonadizer continuation_unit t1 (fun x -> x);;
275 - : int tree =
276 Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11)))
277 </pre>
278
279 That is, nothing happens.  But we can begin to substitute more
280 interesting functions for the first argument of `treemonadizer`:
281
282 <pre>
283 (* Simulating the tree reader: distributing a operation over the leaves *)
284 # treemonadizer (fun a c -> c (square a)) t1 (fun x -> x);;
285 - : int tree =
286 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
287
288 (* Simulating the int list tree list *)
289 # treemonadizer (fun a c -> c [a; square a]) t1 (fun x -> x);;
290 - : int list tree =
291 Node
292  (Node (Leaf [2; 4], Leaf [3; 9]),
293   Node (Leaf [5; 25], Node (Leaf [7; 49], Leaf [11; 121])))
294
295 (* Counting leaves *)
296 # treemonadizer (fun a c -> 1 + c a) t1 (fun x -> 0);;
297 - : int = 5
298 </pre>
299
300 We could simulate the tree state example too, but it would require
301 generalizing the type of the continuation monad to 
302
303     type ('a -> 'b -> 'c) continuation = ('a -> 'b) -> 'c;;
304
305 The binary tree monad
306 ---------------------
307
308 Of course, by now you may have realized that we have discovered a new
309 monad, the binary tree monad:
310
311 <pre>
312 type 'a tree = Leaf of 'a | Node of ('a tree) * ('a tree);;
313 let tree_unit (x:'a) = Leaf x;;
314 let rec tree_bind (u:'a tree) (f:'a -> 'b tree):'b tree = 
315   match u with Leaf x -> f x 
316              | Node (l, r) -> Node ((tree_bind l f), (tree_bind r f));;
317 </pre>
318
319 For once, let's check the Monad laws.  The left identity law is easy:
320
321     Left identity: bind (unit a) f = bind (Leaf a) f = fa
322
323 To check the other two laws, we need to make the following
324 observation: it is easy to prove based on `tree_bind` by a simple
325 induction on the structure of the first argument that the tree
326 resulting from `bind u f` is a tree with the same strucure as `u`,
327 except that each leaf `a` has been replaced with `fa`:
328
329 \tree (. (fa1) (. (. (. (fa2)(fa3)) (fa4)) (fa5)))
330 <pre>
331                 .                         .       
332               __|__                     __|__   
333               |   |                     |   |   
334               a1  .                    fa1  .   
335                  _|__                     __|__ 
336                  |  |                     |   | 
337                  .  a5                    .  fa5
338    bind         _|__       f   =        __|__   
339                 |  |                    |   |   
340                 .  a4                   .  fa4  
341               __|__                   __|___   
342               |   |                   |    |   
343               a2  a3                 fa2  fa3         
344 </pre>   
345
346 Given this equivalence, the right identity law
347
348     Right identity: bind u unit = u
349
350 falls out once we realize that
351
352     bind (Leaf a) unit = unit a = Leaf a
353
354 As for the associative law,
355
356     Associativity: bind (bind u f) g = bind u (\a. bind (fa) g)
357
358 we'll give an example that will show how an inductive proof would
359 proceed.  Let `f a = Node (Leaf a, Leaf a)`.  Then
360
361 \tree (. (. (. (. (a1)(a2)))))
362 \tree (. (. (. (. (a1) (a1)) (. (a1) (a1)))  ))
363 <pre>
364                                            .
365                                        ____|____
366           .               .            |       |
367 bind    __|__   f  =    __|_    =      .       .
368         |   |           |   |        __|__   __|__
369         a1  a2         fa1 fa2       |   |   |   |
370                                      a1  a1  a1  a1  
371 </pre>
372
373 Now when we bind this tree to `g`, we get
374
375 <pre>
376            .
377        ____|____
378        |       |
379        .       .
380      __|__   __|__
381      |   |   |   |
382     ga1 ga1 ga1 ga1  
383 </pre>
384
385 At this point, it should be easy to convince yourself that
386 using the recipe on the right hand side of the associative law will
387 built the exact same final tree.
388
389 So binary trees are a monad.
390
391 Haskell combines this monad with the Option monad to provide a monad
392 called a
393 [SearchTree](http://hackage.haskell.org/packages/archive/tree-monad/0.2.1/doc/html/src/Control-Monad-SearchTree.html#SearchTree)
394 that is intended to 
395 represent non-deterministic computations as a tree.
396