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