X-Git-Url: http://lambda.jimpryor.net/git/gitweb.cgi?p=lambda.git;a=blobdiff_plain;f=code%2Ftree_monadize.ml;h=43ef659f0ad5162eabe0d915a8e90dccdab7ebb6;hp=08b8d690302825d6c2f60b6b3a656c18d9db0677;hb=4528f489f93c2f44f573678dff7359d54d9f9672;hpb=874a793d588bc067f680d5fa5dd9d57d2aa191db diff --git a/code/tree_monadize.ml b/code/tree_monadize.ml index 08b8d690..43ef659f 100644 --- a/code/tree_monadize.ml +++ b/code/tree_monadize.ml @@ -196,6 +196,36 @@ let int_readerize : int -> int Reader_monad.monad = let env = fun i -> i + i in TreeReader.monadize int_readerize t1 env;; +(* You can also avoid declaring a separate toplevel TreeReader module + * (or even a separate Reader_monad module) by ysing one of these forms: + * ... + * let module T = Tree_monadizer(Reader_monad) in + * T.monadize int_readerize t1 env;; + * or: + * ... + * let env = fun i -> i + i in + * let module Monad = struct + * type env = int -> int;; + * type 'a monad = env -> 'a;; + * let unit a : 'a monad = fun e -> a;; + * let bind (u : 'a monad) (f : 'a -> 'b monad) : 'b monad = + * fun e -> f (u e) e;; + * end in + * let module T = Tree_monadizer(Monad) in + * T.monadize int_readerize t1 env;; + * or: + * ... + * let module T = Tree_monadizer(struct + * type env = int -> int;; + * type 'a monad = env -> 'a;; + * let unit a : 'a monad = fun e -> a;; + * let bind (u : 'a monad) (f : 'a -> 'b monad) : 'b monad = + * fun e -> f (u e) e;; + * end) in + * T.monadize int_readerize t1 env;; + *) + + (* square each leaf *) let env = fun i -> i * i in TreeReader.monadize int_readerize t1 env;; @@ -239,4 +269,27 @@ TreeCont.monadize (fun a k -> k [a; a*a]) t1 initial_continuation;; let initial_continuation = fun t -> 0 in TreeCont.monadize (fun a k -> 1 + k a) t1 initial_continuation;; +(* +(* Tree monad *) + +(* type 'a tree defined above *) +let tree_unit (a: 'a) : 'a tree = Leaf a;; +let rec tree_bind (u : 'a tree) (f : 'a -> 'b tree) : 'b tree = + match u with + | Leaf a -> f a + | Node (l, r) -> Node (tree_bind l f, tree_bind r f);; +type ('a) treeT_reader = + 'a tree reader;; + +let unit (a: 'a) : 'a tree reader = + reader_unit (Leaf a);; + +let rec bind (u : 'a tree_reader) (f : 'a -> ('b, M) tree) : ('b, M) tree = + match u with + | Leaf a -> M.bind (f a) (fun b -> M.unit (Leaf b)) + | Node (l, r) -> M.bind (bind l f) (fun l' -> + M.bind (bind r f) (fun r' -> + M.unit (Node (l', r'));; + + *)