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