X-Git-Url: http://lambda.jimpryor.net/git/gitweb.cgi?p=lambda.git;a=blobdiff_plain;f=manipulating_trees_with_monads.mdwn;h=e739c997bada0d8b2c9f23fc07e4821e22574f63;hp=2ec15d6a6c9a8ee37ec39304a5f4d1ee75befffc;hb=c6912ab54f5f042930b15e63b984480c1b98e6ca;hpb=ff95f5a38d61a6fa0b9c5e4da4253a6a3266a7dc diff --git a/manipulating_trees_with_monads.mdwn b/manipulating_trees_with_monads.mdwn index 2ec15d6a..e739c997 100644 --- a/manipulating_trees_with_monads.mdwn +++ b/manipulating_trees_with_monads.mdwn @@ -95,8 +95,6 @@ a Reader monad---is to have the `tree_map` function return a (monadized) tree that is ready to accept any `int -> int` function and produce the updated tree. -\tree (. (. (f 2) (f 3)) (. (f 5) (. (f 7) (f 11)))) - \f . _____|____ | | @@ -267,8 +265,8 @@ it through: let rec tree_monadize_rev (f : 'a -> 'b state) (t : 'a tree) : 'b tree state = match t with | Leaf a -> state_bind (f a) (fun b -> state_unit (Leaf b)) - | Node (l, r) -> state_bind (tree_monadize f r) (fun r' -> - state_bind (tree_monadize f l) (fun l' -> + | Node (l, r) -> state_bind (tree_monadize f r) (fun r' -> (* R first *) + state_bind (tree_monadize f l) (fun l'-> (* Then L *) state_unit (Node (l', r'))));; # tree_monadize_rev (fun a -> fun s -> (s+1, s+1)) t1 0;; @@ -290,7 +288,7 @@ One more revealing example before getting down to business: replacing Unlike the previous cases, instead of turning a tree into a function from some input to a result, this transformer replaces each `int` with -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. +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. [Why is the argument to `tree_monadize` `int -> int list list` instead of `int -> int list`? Well, as usual, the List monad bind operation @@ -407,8 +405,6 @@ induction on the structure of the first argument that the tree resulting from `bind u f` is a tree with the same strucure as `u`, except that each leaf `a` has been replaced with `f a`: -\tree (. (f a1) (. (. (. (f a2) (f a3)) (f a4)) (f a5))) - . . __|__ __|__ | | | | @@ -438,9 +434,6 @@ As for the associative law, we'll give an example that will show how an inductive proof would proceed. Let `f a = Node (Leaf a, Leaf a)`. Then -\tree (. (. (. (. (a1) (a2))))) -\tree (. (. (. (. (a1) (a1)) (. (a1) (a1))))) - . ____|____ . . | |