diff --git a/src/test/run-pass/monad.rs b/src/test/run-pass/monad.rs new file mode 100644 index 000000000000..bdfb6ff8b707 --- /dev/null +++ b/src/test/run-pass/monad.rs @@ -0,0 +1,31 @@ +iface monad { + fn bind(fn(A) -> self) -> self; +} + +impl of monad for [A] { + fn bind(f: fn(A) -> [B]) -> [B] { + let r = []; + for elt in self { r += f(elt); } + r + } +} + +impl of monad for option { + fn bind(f: fn(A) -> option) -> option { + alt self { + some(a) { f(a) } + none { none } + } + } +} + +fn transform(x: option) -> option { + 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!?"]; +}