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