tree_monadize 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 suggestion of Ken Shan's.
7 We'll build a series of functions that operate on trees, doing various
8 things, including updating leaves with a Reader monad, counting nodes
9 with a State monad, replacing leaves with a List monad, and converting
10 a tree into a list of leaves with a Continuation monad.  It will turn
11 out that the continuation monad can simulate the behavior of each of
12 the other monads.
13
14 From an engineering standpoint, we'll build a tree transformer that
15 deals in monads.  We can modify the behavior of the system by swapping
16 one monad for another.  We've already seen how adding a monad can add
17 a layer of funtionality without disturbing the underlying system, for
18 instance, in the way that the Reader monad allowed us to add a layer
19 of intensionality to an extensional grammar, but we have not yet seen
20 the utility of replacing one monad with other.
21
22 First, we'll be needing a lot of trees for the remainder of the
23 course.  Here again is a type constructor for leaf-labeled, binary trees:
24
25     type 'a tree = Leaf of 'a | Node of ('a tree * 'a tree)
26
27 [How 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         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         2  3  5  .
43                 _|__
44                 |  |
45                 7  11
46
47 Our first task will be to replace each leaf with its double:
48
49         let rec tree_map (leaf_modifier : 'a -> 'b) (t : 'a tree) : 'b tree =
50           match t with
51             | Leaf i -> Leaf (leaf_modifier i)
52             | Node (l, r) -> Node (tree_map leaf_modifier l,
53                                    tree_map leaf_modifier r);;
54
55 `tree_map` takes a function that transforms old leaves into new leaves,
56 and maps that function over all the leaves in the tree, leaving the
57 structure of the tree unchanged.  For instance:
58
59         let double i = i + i;;
60         tree_map double t1;;
61         - : int tree =
62         Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
63         
64             .
65          ___|____
66          |      |
67          .      .
68         _|__  __|__
69         |  |  |   |
70         4  6  10  .
71                 __|___
72                 |    |
73                 14   22
74
75 We could have built the doubling operation right into the `tree_map`
76 code.  However, because we've made what to do to each leaf a
77 parameter, we can decide to do something else to the leaves without
78 needing to rewrite `tree_map`.  For instance, we can easily square
79 each leaf instead by supplying the appropriate `int -> int` operation
80 in place of `double`:
81
82         let square i = i * i;;
83         tree_map square t1;;
84         - : int tree =ppp
85         Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
86
87 Note that what `tree_map` does is take some unchanging contextual
88 information---what to do to each leaf---and supplies that information
89 to each subpart of the computation.  In other words, `tree_map` has the
90 behavior of a Reader monad.  Let's make that explicit.
91
92 In general, we're on a journey of making our `tree_map` function more and
93 more flexible.  So the next step---combining the tree transformer with
94 a Reader monad---is to have the `tree_map` function return a (monadized)
95 tree that is ready to accept any `int -> int` function and produce the
96 updated tree.
97
98 \tree (. (. (f 2) (f 3)) (. (f 5) (. (f 7) (f 11))))
99
100         \f      .
101            _____|____
102            |        |
103            .        .
104          __|___   __|___
105          |    |   |    |
106         f 2  f 3  f 5  .
107                      __|___
108                      |    |
109                     f 7  f 11
110
111 That is, we want to transform the ordinary tree `t1` (of type `int
112 tree`) into a reader monadic object of type `(int -> int) -> int
113 tree`: something that, when you apply it to an `int -> int` function
114 `f` returns an `int tree` in which each leaf `i` has been replaced
115 with `f i`.
116
117 [Application note: this kind of reader object could provide a model
118 for Kaplan's characters.  It turns an ordinary tree into one that
119 expects contextual information (here, the `λ f`) that can be
120 used to compute the content of indexicals embedded arbitrarily deeply
121 in the tree.]
122
123 With our previous applications of the Reader monad, we always knew
124 which kind of environment to expect: either an assignment function, as
125 in the original calculator simulation; a world, as in the
126 intensionality monad; an individual, as in the Jacobson-inspired link
127 monad; etc.  In the present case, we expect that our "environment"
128 will be some function of type `int -> int`. "Looking up" some `int` in
129 the environment will return us the `int` that comes out the other side
130 of that function.
131
132         type 'a reader = (int -> int) -> 'a;;  (* mnemonic: e for environment *)
133         let reader_unit (a : 'a) : 'a reader = fun _ -> a;;
134         let reader_bind (u: 'a reader) (f : 'a -> 'b reader) : 'b reader = fun e -> f (u e) e;;
135
136 It would be a simple matter to turn an *integer* into an `int reader`:
137
138         let int_readerize : int -> int reader = fun (a : int) -> fun (modifier : int -> int) -> modifier a;;
139         int_readerize 2 (fun i -> i + i);;
140         - : int = 4
141
142 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?
143 A tree is not the kind of thing that we can apply a
144 function of type `int -> int` to.
145
146 But we can do this:
147
148         let rec tree_monadize (f : 'a -> 'b reader) (t : 'a tree) : 'b tree reader =
149             match t with
150             | Leaf a -> reader_bind (f a) (fun b -> reader_unit (Leaf b))
151             | Node (l, r) -> reader_bind (tree_monadize f l) (fun l' ->
152                                reader_bind (tree_monadize f r) (fun r' ->
153                                  reader_unit (Node (l', r'))));;
154
155 This function says: give me a function `f` that knows how to turn
156 something of type `'a` into an `'b reader`---this is a function of the same type that you could bind an `'a reader` to---and I'll show you how to
157 turn an `'a tree` into an `'b tree reader`.  That is, if you show me how to do this:
158
159                       ------------
160           1     --->  |    1     |
161                       ------------
162
163 then I'll give you back the ability to do this:
164
165                       ____________
166           .           |    .     |
167         __|___  --->  |  __|___  |
168         |    |        |  |    |  |
169         1    2        |  1    2  |
170                       ------------
171
172 And how will that boxed tree behave? Whatever actions you perform on it will be transmitted down to corresponding operations on its leaves. For instance, our `int reader` expects an `int -> int` environment. If supplying environment `e` to our `int reader` doubles the contained `int`:
173
174                       ------------
175           1     --->  |    1     |  applied to e  ~~>  2
176                       ------------
177
178 Then we can expect that supplying it to our `int tree reader` will double all the leaves:
179
180                       ____________
181           .           |    .     |                      .
182         __|___  --->  |  __|___  | applied to e  ~~>  __|___
183         |    |        |  |    |  |                    |    |
184         1    2        |  1    2  |                    2    4
185                       ------------
186
187 In more fanciful terms, the `tree_monadize` function builds plumbing that connects all of the leaves of a tree into one connected monadic network; it threads the
188 `'b reader` monad through the original tree's leaves.
189
190         # tree_monadize int_readerize t1 double;;
191         - : int tree =
192         Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
193
194 Here, our environment is the doubling function (`fun i -> i + i`).  If
195 we apply the very same `int tree reader` (namely, `tree_monadize
196 int_readerize t1`) to a different `int -> int` function---say, the
197 squaring function, `fun i -> i * i`---we get an entirely different
198 result:
199
200         # tree_monadize int_readerize t1 square;;
201         - : int tree =
202         Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
203
204 Now that we have a tree transformer that accepts a *reader* monad as a
205 parameter, we can see what it would take to swap in a different monad.
206
207 For instance, we can use a State monad to count the number of leaves in
208 the tree.
209
210         type 'a state = int -> 'a * int;;
211         let state_unit a = fun s -> (a, s);;
212         let state_bind u f = fun s -> let (a, s') = u s in f a s';;
213
214 Gratifyingly, we can use the `tree_monadize` function without any
215 modification whatsoever, except for replacing the (parametric) type
216 `'b reader` with `'b state`, and substituting in the appropriate unit and bind:
217
218         let rec tree_monadize (f : 'a -> 'b state) (t : 'a tree) : 'b tree state =
219             match t with
220             | Leaf a -> state_bind (f a) (fun b -> state_unit (Leaf b))
221             | Node (l, r) -> state_bind (tree_monadize f l) (fun l' ->
222                                state_bind (tree_monadize f r) (fun r' ->
223                                  state_unit (Node (l', r'))));;
224
225 Then we can count the number of leaves in the tree:
226
227         # tree_monadize (fun a -> fun s -> (a, s+1)) t1 0;;
228         - : int tree * int =
229         (Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11))), 5)
230         
231             .
232          ___|___
233          |     |
234          .     .
235         _|__  _|__         , 5
236         |  |  |  |
237         2  3  5  .
238                 _|__
239                 |  |
240                 7  11
241
242 Note that the value returned is a pair consisting of a tree and an
243 integer, 5, which represents the count of the leaves in the tree.
244
245 Why does this work? Because the operation `fun a -> fun s -> (a, s+1)`
246 takes an `int` and wraps it in an `int state` monadic box that
247 increments the state. When we give that same operations to our
248 `tree_monadize` function, it then wraps an `int tree` in a box, one
249 that does the same state-incrementing for each of its leaves.
250
251 One more revealing example before getting down to business: replacing
252 `state` everywhere in `tree_monadize` with `list` gives us
253
254         # tree_monadize (fun i -> [ [i; square i] ]) t1;;
255         - : int list tree list =
256         [Node
257           (Node (Leaf [2; 4], Leaf [3; 9]),
258            Node (Leaf [5; 25], Node (Leaf [7; 49], Leaf [11; 121])))]
259
260 Unlike the previous cases, instead of turning a tree into a function
261 from some input to a result, this transformer replaces each `int` with
262 a list of `int`'s. We might also have done this with a Reader monad, though then our environments would need to be of type `int -> int list`. Experiment with what happens if you supply the `tree_monadize` based on the List monad an operation like `fun -> [ i; [2*i; 3*i] ]`. Use small trees for your experiment.
263
264 [Why is the argument to `tree_monadize` `int -> int list list` instead
265 of `int -> int list`?  Well, as usual, the List monad bind operation
266 will erase the outer list box, so if we want to replace the leaves
267 with lists, we have to nest the replacement lists inside a disposable
268 box.]
269
270 Now for the main point.  What if we wanted to convert a tree to a list
271 of leaves?
272
273         type ('a, 'r) continuation = ('a -> 'r) -> 'r;;
274         let continuation_unit a = fun k -> k a;;
275         let continuation_bind u f = fun k -> u (fun a -> f a k);;
276         
277         let rec tree_monadize (f : 'a -> ('b, 'r) continuation) (t : 'a tree) : ('b tree, 'r) continuation =
278             match t with
279             | Leaf a -> continuation_bind (f a) (fun b -> continuation_unit (Leaf b))
280             | Node (l, r) -> continuation_bind (tree_monadize f l) (fun l' ->
281                                continuation_bind (tree_monadize f r) (fun r' ->
282                                  continuation_unit (Node (l', r'))));;
283
284 We use the Continuation monad described above, and insert the
285 `continuation` type in the appropriate place in the `tree_monadize` code. Then if we give the `tree_monadize` function an operation that converts `int`s into `'b`-wrapping Continuation monads, it will give us back a way to turn `int tree`s into corresponding `'b tree`-wrapping Continuation monads.
286
287 So for example, we compute:
288
289         # tree_monadize (fun a -> fun k -> a :: k a) t1 (fun t -> []);;
290         - : int list = [2; 3; 5; 7; 11]
291
292 We have found a way of collapsing a tree into a list of its leaves. Can you trace how this is working? Think first about what the operation `fun a -> fun k -> a :: k a` does when you apply it to a plain `int`, and the continuation `fun _ -> []`. Then given what we've said about `tree_monadize`, what should we expect `tree_monadize (fun a -> fun k -> a :: k a` to do?
293
294 The Continuation monad is amazingly flexible; we can use it to
295 simulate some of the computations performed above.  To see how, first
296 note that an interestingly uninteresting thing happens if we use
297 `continuation_unit` as our first argument to `tree_monadize`, and then
298 apply the result to the identity function:
299
300         # tree_monadize continuation_unit t1 (fun t -> t);;
301         - : int tree =
302         Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11)))
303
304 That is, nothing happens.  But we can begin to substitute more
305 interesting functions for the first argument of `tree_monadize`:
306
307         (* Simulating the tree reader: distributing a operation over the leaves *)
308         # tree_monadize (fun a -> fun k -> k (square a)) t1 (fun t -> t);;
309         - : int tree =
310         Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
311
312         (* Simulating the int list tree list *)
313         # tree_monadize (fun a -> fun k -> k [a; square a]) t1 (fun t -> t);;
314         - : int list tree =
315         Node
316          (Node (Leaf [2; 4], Leaf [3; 9]),
317           Node (Leaf [5; 25], Node (Leaf [7; 49], Leaf [11; 121])))
318
319         (* Counting leaves *)
320         # tree_monadize (fun a -> fun k -> 1 + k a) t1 (fun t -> 0);;
321         - : int = 5
322
323 We could simulate the tree state example too, but it would require
324 generalizing the type of the Continuation monad to
325
326         type ('a, 'b, 'c) continuation = ('a -> 'b) -> 'c;;
327
328 If you want to see how to parameterize the definition of the `tree_monadize` function, so that you don't have to keep rewriting it for each new monad, see [this code](/code/tree_monadize.ml).
329
330
331 The Binary Tree monad
332 ---------------------
333
334 Of course, by now you may have realized that we have discovered a new
335 monad, the Binary Tree monad.  Just as mere lists are in fact a monad,
336 so are trees.  Here is the type constructor, unit, and bind:
337
338         type 'a tree = Leaf of 'a | Node of ('a tree) * ('a tree);;
339         let tree_unit (a: 'a) : 'a tree = Leaf a;;
340         let rec tree_bind (u : 'a tree) (f : 'a -> 'b tree) : 'b tree =
341             match u with
342             | Leaf a -> f a
343             | Node (l, r) -> Node (tree_bind l f, tree_bind r f);;
344
345 For once, let's check the Monad laws.  The left identity law is easy:
346
347     Left identity: bind (unit a) f = bind (Leaf a) f = f a
348
349 To check the other two laws, we need to make the following
350 observation: it is easy to prove based on `tree_bind` by a simple
351 induction on the structure of the first argument that the tree
352 resulting from `bind u f` is a tree with the same strucure as `u`,
353 except that each leaf `a` has been replaced with `f a`:
354
355 \tree (. (f a1) (. (. (. (f a2) (f a3)) (f a4)) (f a5)))
356
357                         .                         .
358                       __|__                     __|__
359                       |   |                     |   |
360                       a1  .                   f a1  .
361                          _|__                     __|__
362                          |  |                     |   |
363                          .  a5                    .  f a5
364            bind         _|__       f   =        __|__
365                         |  |                    |   |
366                         .  a4                   .  f a4
367                       __|__                   __|___
368                       |   |                   |    |
369                       a2  a3                f a2  f a3
370
371 Given this equivalence, the right identity law
372
373         Right identity: bind u unit = u
374
375 falls out once we realize that
376
377         bind (Leaf a) unit = unit a = Leaf a
378
379 As for the associative law,
380
381         Associativity: bind (bind u f) g = bind u (\a. bind (f a) g)
382
383 we'll give an example that will show how an inductive proof would
384 proceed.  Let `f a = Node (Leaf a, Leaf a)`.  Then
385
386 \tree (. (. (. (. (a1) (a2)))))
387 \tree (. (. (. (. (a1) (a1)) (. (a1) (a1)))))
388
389                                                    .
390                                                ____|____
391                   .               .            |       |
392         bind    __|__   f  =    __|_    =      .       .
393                 |   |           |   |        __|__   __|__
394                 a1  a2        f a1 f a2      |   |   |   |
395                                              a1  a1  a1  a1
396
397 Now when we bind this tree to `g`, we get
398
399                     .
400                _____|______
401                |          |
402                .          .
403              __|__      __|__
404              |   |      |   |
405            g a1 g a1  g a1 g a1
406
407 At this point, it should be easy to convince yourself that
408 using the recipe on the right hand side of the associative law will
409 built the exact same final tree.
410
411 So binary trees are a monad.
412
413 Haskell combines this monad with the Option monad to provide a monad
414 called a
415 [SearchTree](http://hackage.haskell.org/packages/archive/tree-monad/0.2.1/doc/html/src/Control-Monad-SearchTree.html#SearchTree)
416 that is intended to represent non-deterministic computations as a tree.
417
418
419 What's this have to do with tree\_mondadize?
420 --------------------------------------------
421
422 So we've defined a Tree monad:
423
424         type 'a tree = Leaf of 'a | Node of ('a tree) * ('a tree);;
425         let tree_unit (a: 'a) : 'a tree = Leaf a;;
426         let rec tree_bind (u : 'a tree) (f : 'a -> 'b tree) : 'b tree =
427             match u with
428             | Leaf a -> f a
429             | Node (l, r) -> Node (tree_bind l f, tree_bind r f);;
430
431 What's this have to do with the `tree_monadize` functions we defined earlier?
432
433         let rec tree_monadize (f : 'a -> 'b reader) (t : 'a tree) : 'b tree reader =
434             match t with
435             | Leaf a -> reader_bind (f a) (fun b -> reader_unit (Leaf b))
436             | Node (l, r) -> reader_bind (tree_monadize f l) (fun l' ->
437                                reader_bind (tree_monadize f r) (fun r' ->
438                                  reader_unit (Node (l', r'))));;
439
440 ... and so on for different monads?
441
442 The answer is that each of those `tree_monadize` functions is adding a Tree monad *layer* to a pre-existing Reader (and so on) monad. We discuss that further here: [[Monad Transformers]].
443