3 Manipulating trees with monads
4 ------------------------------
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, copying the tree 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
14 From an engineering standpoint, we'll build a tree machine 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.
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:
25 type 'a tree = Leaf of 'a | Node of ('a tree * 'a tree);;
27 [How would you adjust the type constructor to allow for labels on the
30 We'll be using trees where the nodes are integers, e.g.,
33 let t1 = Node (Node (Leaf 2, Leaf 3),
34 Node (Leaf 5, Node (Leaf 7,
47 Our first task will be to replace each leaf with its double:
49 let rec tree_map (leaf_modifier : 'a -> 'b) (t : 'a tree) : 'b tree =
51 | Leaf i -> Leaf (leaf_modifier i)
52 | Node (l, r) -> Node (tree_map leaf_modifier l,
53 tree_map leaf_modifier r);;
55 `tree_map` takes a tree and a function that transforms old leaves into
56 new leaves, and maps that function over all the leaves in the tree,
57 leaving the structure of the tree unchanged. For instance:
59 let double i = i + i;;
62 Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
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
82 let square i = i * i;;
85 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
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.
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
109 That is, we want to transform the ordinary tree `t1` (of type `int
110 tree`) into a reader monadic object of type `(int -> int) -> int
111 tree`: something that, when you apply it to an `int -> int` function
112 `e` returns an `int tree` in which each leaf `i` has been replaced
115 [Application note: this kind of reader object could provide a model
116 for Kaplan's characters. It turns an ordinary tree into one that
117 expects contextual information (here, the `e`) that can be
118 used to compute the content of indexicals embedded arbitrarily deeply
121 With our previous applications of the Reader monad, we always knew
122 which kind of environment to expect: either an assignment function, as
123 in the original calculator simulation; a world, as in the
124 intensionality monad; an individual, as in the Jacobson-inspired link
125 monad; etc. In the present case, we expect that our "environment"
126 will be some function of type `int -> int`. "Looking up" some `int` in
127 the environment will return us the `int` that comes out the other side
130 type 'a reader = (int -> int) -> 'a;;
131 let reader_unit (a : 'a) : 'a reader = fun _ -> a;;
132 let reader_bind (u: 'a reader) (f : 'a -> 'b reader) : 'b reader =
135 It would be a simple matter to turn an *integer* into an `int reader`:
137 let asker : int -> int reader =
139 fun (modifier : int -> int) -> modifier a;;
140 asker 2 (fun i -> i + i);;
143 `asker a` is a monadic box that waits for an an environment (here, the argument `modifier`) and returns what that environment maps `a` to.
145 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?
146 A tree is not the kind of thing that we can apply a
147 function of type `int -> int` to.
151 let rec tree_monadize (f : 'a -> 'b reader) (t : 'a tree) : 'b tree reader =
153 | Leaf a -> reader_bind (f a) (fun b -> reader_unit (Leaf b))
154 | Node (l, r) -> reader_bind (tree_monadize f l) (fun l' ->
155 reader_bind (tree_monadize f r) (fun r' ->
156 reader_unit (Node (l', r'))));;
158 This function says: give me a function `f` that knows how to turn
159 something of type `'a` into an `'b reader`---this is a function of the same type that you could bind an `'a reader` to, such as `asker` or `reader_unit`---and I'll show you how to
160 turn an `'a tree` into an `'b tree reader`. That is, if you show me how to do this:
166 then I'll give you back the ability to do this:
170 __|___ ---> | __|___ |
175 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`:
178 1 ---> | 1 | applied to e ~~> 2
181 Then we can expect that supplying it to our `int tree reader` will double all the leaves:
185 __|___ ---> | __|___ | applied to e ~~> __|___
190 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
191 `'b reader` monad through the original tree's leaves.
193 # tree_monadize asker t1 double;;
195 Node (Node (Leaf 4, Leaf 6), Node (Leaf 10, Node (Leaf 14, Leaf 22)))
197 Here, our environment is the doubling function (`fun i -> i + i`). If
198 we apply the very same `int tree reader` (namely, `tree_monadize
199 asker t1`) to a different `int -> int` function---say, the
200 squaring function, `fun i -> i * i`---we get an entirely different
203 # tree_monadize asker t1 square;;
205 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
207 Now that we have a tree transformer that accepts a *reader* monad as a
208 parameter, we can see what it would take to swap in a different monad.
210 For instance, we can use a State monad to count the number of leaves in
213 type 'a state = int -> 'a * int;;
214 let state_unit a = fun s -> (a, s);;
215 let state_bind u f = fun s -> let (a, s') = u s in f a s';;
217 Gratifyingly, we can use the `tree_monadize` function without any
218 modification whatsoever, except for replacing the (parametric) type
219 `'b reader` with `'b state`, and substituting in the appropriate unit and bind:
221 let rec tree_monadize (f : 'a -> 'b state) (t : 'a tree) : 'b tree state =
223 | Leaf a -> state_bind (f a) (fun b -> state_unit (Leaf b))
224 | Node (l, r) -> state_bind (tree_monadize f l) (fun l' ->
225 state_bind (tree_monadize f r) (fun r' ->
226 state_unit (Node (l', r'))));;
228 Then we can count the number of leaves in the tree:
230 # let incrementer = fun a ->
233 # tree_monadize incrementer t1 0;;
235 (Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11))), 5)
248 Note that the value returned is a pair consisting of a tree and an
249 integer, 5, which represents the count of the leaves in the tree.
251 Why does this work? Because the operation `incrementer`
252 takes an argument `a` and wraps it in an State monadic box that
253 increments the store and leaves behind a wrapped `a`. When we give that same operations to our
254 `tree_monadize` function, it then wraps an `int tree` in a box, one
255 that does the same store-incrementing for each of its leaves.
257 We can use the state monad to annotate leaves with a number
258 corresponding to that leave's ordinal position. When we do so, we
259 reveal the order in which the monadic tree forces evaluation:
261 # tree_monadize (fun a -> fun s -> ((a,s+1), s+1)) t1 0;;
264 (Node (Leaf (2, 1), Leaf (3, 2)),
267 Node (Leaf (7, 4), Leaf (11, 5)))),
270 The key thing to notice is that instead of just wrapping `a` in the
271 monadic box, we wrap a pair of `a` and the current store.
273 Reversing the annotation order requires reversing the order of the `state_bind`
274 operations. It's not obvious that this will type correctly, so think
277 let rec tree_monadize_rev (f : 'a -> 'b state) (t : 'a tree) : 'b tree state =
279 | Leaf a -> state_bind (f a) (fun b -> state_unit (Leaf b))
280 | Node (l, r) -> state_bind (tree_monadize f r) (fun r' -> (* R first *)
281 state_bind (tree_monadize f l) (fun l'-> (* Then L *)
282 state_unit (Node (l', r'))));;
284 # tree_monadize_rev (fun a -> fun s -> ((a,s+1), s+1)) t1 0;;
287 (Node (Leaf (2, 5), Leaf (3, 4)),
290 Node (Leaf (7, 2), Leaf (11, 1)))),
293 Later, we will talk more about controlling the order in which nodes are visited.
295 One more revealing example before getting down to business: replacing
296 `state` everywhere in `tree_monadize` with `list` lets us do:
298 # let decider i = if i = 2 then [20; 21] else [i];;
299 # tree_monadize decider t1;;
300 - : int tree List_monad.m =
302 Node (Node (Leaf 20, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11)));
303 Node (Node (Leaf 21, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11)))
307 Unlike the previous cases, instead of turning a tree into a function
308 from some input to a result, this monadized tree gives us back a list of trees,
309 one for each choice of `int`s for its leaves.
311 Now for the main point. What if we wanted to convert a tree to a list
314 type ('r,'a) continuation = ('a -> 'r) -> 'r;;
315 let continuation_unit a = fun k -> k a;;
316 let continuation_bind u f = fun k -> u (fun a -> f a k);;
318 let rec tree_monadize (f : 'a -> ('r,'b) continuation) (t : 'a tree) : ('r,'b tree) continuation =
320 | Leaf a -> continuation_bind (f a) (fun b -> continuation_unit (Leaf b))
321 | Node (l, r) -> continuation_bind (tree_monadize f l) (fun l' ->
322 continuation_bind (tree_monadize f r) (fun r' ->
323 continuation_unit (Node (l', r'))));;
325 We use the Continuation monad described above, and insert the
326 `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.
328 So for example, we compute:
330 # tree_monadize (fun a k -> a :: k ()) t1 (fun _ -> []);;
331 - : int list = [2; 3; 5; 7; 11]
333 We have found a way of collapsing a tree into a list of its
334 leaves. Can you trace how this is working? Think first about what the
335 operation `fun a k -> a :: k a` does when you apply it to a
336 plain `int`, and the continuation `fun _ -> []`. Then given what we've
337 said about `tree_monadize`, what should we expect `tree_monadize (fun
338 a -> fun k -> a :: k a)` to do?
340 Soon we'll return to the same-fringe problem. Since the
341 simple but inefficient way to solve it is to map each tree to a list
342 of its leaves, this transformation is on the path to a more efficient
343 solution. We'll just have to figure out how to postpone computing the
344 tail of the list until it's needed...
346 The Continuation monad is amazingly flexible; we can use it to
347 simulate some of the computations performed above. To see how, first
348 note that an interestingly uninteresting thing happens if we use
349 `continuation_unit` as our first argument to `tree_monadize`, and then
350 apply the result to the identity function:
352 # tree_monadize continuation_unit t1 (fun t -> t);;
354 Node (Node (Leaf 2, Leaf 3), Node (Leaf 5, Node (Leaf 7, Leaf 11)))
356 That is, nothing happens. But we can begin to substitute more
357 interesting functions for the first argument of `tree_monadize`:
359 (* Simulating the tree reader: distributing a operation over the leaves *)
360 # tree_monadize (fun a -> fun k -> k (square a)) t1 (fun t -> t);;
362 Node (Node (Leaf 4, Leaf 9), Node (Leaf 25, Node (Leaf 49, Leaf 121)))
364 (* Counting leaves *)
365 # tree_monadize (fun a -> fun k -> 1 + k a) t1 (fun t -> 0);;
368 It's not immediately obvious to us how to simulate the List monadization of the tree using this technique.
370 We could simulate the tree annotating example by setting the relevant
371 type to `(store -> 'result, 'a) continuation`.
373 Andre Filinsky has proposed that the continuation monad is
374 able to simulate any other monad (Google for "mother of all monads").
376 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).
378 The idea of using continuations to characterize natural language meaning
379 ------------------------------------------------------------------------
381 We might a philosopher or a linguist be interested in continuations,
382 especially if efficiency of computation is usually not an issue?
383 Well, the application of continuations to the same-fringe problem
384 shows that continuations can manage order of evaluation in a
385 well-controlled manner. In a series of papers, one of us (Barker) and
386 Ken Shan have argued that a number of phenomena in natural langauge
387 semantics are sensitive to the order of evaluation. We can't
388 reproduce all of the intricate arguments here, but we can give a sense
389 of how the analyses use continuations to achieve an analysis of
390 natural language meaning.
392 **Quantification and default quantifier scope construal**.
394 We saw in the copy-string example ("abSd") and in the same-fringe example that
395 local properties of a structure (whether a character is `'S'` or not, which
396 integer occurs at some leaf position) can control global properties of
397 the computation (whether the preceeding string is copied or not,
398 whether the computation halts or proceeds). Local control of
399 surrounding context is a reasonable description of in-situ
402 (1) John saw everyone yesterday.
404 This sentence means (roughly)
406 forall x . yesterday(saw x) john
408 That is, the quantifier *everyone* contributes a variable in the
409 direct object position, and a universal quantifier that takes scope
410 over the whole sentence. If we have a lexical meaning function like
413 let lex (s:string) k = match s with
414 | "everyone" -> Node (Leaf "forall x", k "x")
415 | "someone" -> Node (Leaf "exists y", k "y")
418 Then we can crudely approximate quantification as follows:
420 # let sentence1 = Node (Leaf "John",
421 Node (Node (Leaf "saw",
425 # tree_monadize lex sentence1 (fun x -> x);;
429 Node (Leaf "John", Node (Node (Leaf "saw", Leaf "x"), Leaf "yesterday")))
431 In order to see the effects of evaluation order,
432 observe what happens when we combine two quantifiers in the same
435 # let sentence2 = Node (Leaf "everyone", Node (Leaf "saw", Leaf "someone"));;
436 # tree_monadize lex sentence2 (fun x -> x);;
440 Node (Leaf "exists y", Node (Leaf "x", Node (Leaf "saw", Leaf "y"))))
442 The universal takes scope over the existential. If, however, we
443 replace the usual `tree_monadizer` with `tree_monadizer_rev`, we get
446 # tree_monadize_rev lex sentence2 (fun x -> x);;
450 Node (Leaf "forall x", Node (Leaf "x", Node (Leaf "saw", Leaf "y"))))
452 There are many crucially important details about quantification that
453 are being simplified here, and the continuation treatment used here is not
454 scalable for a number of reasons. Nevertheless, it will serve to give
455 an idea of how continuations can provide insight into the behavior of
462 Of course, by now you may have realized that we are working with a new
463 monad, the binary, leaf-labeled Tree monad. Just as mere lists are in fact a monad,
464 so are trees. Here is the type constructor, unit, and bind:
466 type 'a tree = Leaf of 'a | Node of ('a tree) * ('a tree);;
467 let tree_unit (a: 'a) : 'a tree = Leaf a;;
468 let rec tree_bind (u : 'a tree) (f : 'a -> 'b tree) : 'b tree =
471 | Node (l, r) -> Node (tree_bind l f, tree_bind r f);;
473 For once, let's check the Monad laws. The left identity law is easy:
475 Left identity: bind (unit a) f = bind (Leaf a) f = f a
477 To check the other two laws, we need to make the following
478 observation: it is easy to prove based on `tree_bind` by a simple
479 induction on the structure of the first argument that the tree
480 resulting from `bind u f` is a tree with the same strucure as `u`,
481 except that each leaf `a` has been replaced with the tree returned by `f a`:
497 Given this equivalence, the right identity law
499 Right identity: bind u unit = u
501 falls out once we realize that
503 bind (Leaf a) unit = unit a = Leaf a
505 As for the associative law,
507 Associativity: bind (bind u f) g = bind u (\a. bind (f a) g)
509 we'll give an example that will show how an inductive proof would
510 proceed. Let `f a = Node (Leaf a, Leaf a)`. Then
515 bind __|__ f = __|_ = . .
517 a1 a2 f a1 f a2 | | | |
520 Now when we bind this tree to `g`, we get
530 At this point, it should be easy to convince yourself that
531 using the recipe on the right hand side of the associative law will
532 build the exact same final tree.
534 So binary trees are a monad.
536 Haskell combines this monad with the Option monad to provide a monad
538 [SearchTree](http://hackage.haskell.org/packages/archive/tree-monad/0.2.1/doc/html/src/Control-Monad-SearchTree.html#SearchTree)
539 that is intended to represent non-deterministic computations as a tree.
542 What's this have to do with tree\_monadize?
543 --------------------------------------------
545 Our different implementations of `tree_monadize` above were different *layerings* of the Tree monad with other monads (Reader, State, List, and Continuation). We'll explore that further here: [[Monad Transformers]].