rust/src/lib/either.rs

63 lines
1.4 KiB
Rust
Raw Normal View History

2011-06-16 18:55:46 -05:00
import option;
import option::some;
import option::none;
2011-06-16 18:55:46 -05:00
tag t[T, U] { left(T); right(U); }
2011-06-16 18:55:46 -05:00
type operator[T, U] = fn(&T) -> U ;
2011-06-16 18:55:46 -05:00
fn either[T, U,
V](&operator[T, V] f_left, &operator[U, V] f_right, &t[T, U] value)
-> V {
alt (value) {
case (left(?l)) { f_left(l) }
case (right(?r)) { f_right(r) }
}
}
fn lefts[T, U](&(t[T, U])[] eithers) -> T[] {
let T[] result = ~[];
for (t[T, U] elt in eithers) {
alt (elt) {
case (left(?l)) { result += ~[l] }
2011-06-16 18:55:46 -05:00
case (_) {/* fallthrough */ }
}
}
ret result;
}
fn rights[T, U](&(t[T, U])[] eithers) -> U[] {
let U[] result = ~[];
for (t[T, U] elt in eithers) {
alt (elt) {
case (right(?r)) { result += ~[r] }
2011-06-16 18:55:46 -05:00
case (_) {/* fallthrough */ }
}
}
ret result;
}
fn partition[T, U](&(t[T, U])[] eithers)
-> rec(T[] lefts, U[] rights) {
let T[] lefts = ~[];
let U[] rights = ~[];
for (t[T, U] elt in eithers) {
alt (elt) {
case (left(?l)) { lefts += ~[l] }
case (right(?r)) { rights += ~[r] }
}
}
ret rec(lefts=lefts, rights=rights);
}
//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//