Add monad iface test

This commit is contained in:
Marijn Haverbeke 2012-01-31 13:37:06 +01:00
parent e0fa5cd2ed
commit 91da710d86

View File

@ -0,0 +1,31 @@
iface monad<A> {
fn bind<B>(fn(A) -> self<B>) -> self<B>;
}
impl <A> of monad<A> for [A] {
fn bind<B>(f: fn(A) -> [B]) -> [B] {
let r = [];
for elt in self { r += f(elt); }
r
}
}
impl <A> of monad<A> for option<A> {
fn bind<B>(f: fn(A) -> option<B>) -> option<B> {
alt self {
some(a) { f(a) }
none { none }
}
}
}
fn transform(x: option<int>) -> 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!?"];
}