trait vec_monad { fn bind(f: fn(A) -> ~[B]) -> ~[B]; } impl monad of vec_monad for ~[A] { fn bind(f: fn(A) -> ~[B]) -> ~[B] { let mut r = ~[]; for self.each |elt| { r += f(elt); } r } } trait option_monad { fn bind(f: fn(A) -> option) -> option; } impl monad of option_monad for option { fn bind(f: fn(A) -> option) -> option { alt self { some(a) => { f(a) } none => { none } } } } fn transform(x: option) -> option<~str> { x.bind(|n| some(n + 1) ).bind(|n| some(int::str(n)) ) } fn main() { assert transform(some(10)) == some(~"11"); assert transform(none) == none; assert (~[~"hi"]).bind(|x| ~[x, x + ~"!"] ).bind(|x| ~[x, x + ~"?"] ) == ~[~"hi", ~"hi?", ~"hi!", ~"hi!?"]; }