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