2012-01-31 06:37:06 -06:00
|
|
|
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] {
|
2012-03-22 10:39:41 -05:00
|
|
|
let mut r = [];
|
2012-04-06 13:01:43 -05:00
|
|
|
for self.each {|elt| r += f(elt); }
|
2012-01-31 06:37:06 -06:00
|
|
|
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!?"];
|
|
|
|
}
|