std: added either::flip, to_result and result::to_either

This commit is contained in:
Stefan Plantikow 2011-12-16 16:31:35 +01:00
parent fd1dd76977
commit 1fe4bd0f43
2 changed files with 35 additions and 3 deletions

View File

@ -78,6 +78,31 @@ fn partition<copy T, copy U>(eithers: [t<T, U>])
ret {lefts: lefts, rights: rights};
}
/*
Function: flip
Flips between left and right of a given either
*/
pure fn flip<copy T, copy U>(eith: t<T, U>) -> t<U, T> {
alt eith {
right(r) { left(r) }
left(l) { right(l) }
}
}
/*
Function: to_result
Converts either::t to a result::t, making the "right" choice
an ok result, and the "left" choice a fail
*/
pure fn to_result<copy T, copy U>(eith: t<T, U>) -> result::t<U, T> {
alt eith {
right(r) { result::ok(r) }
left(l) { result::err(l) }
}
}
//
// Local Variables:
// mode: rust

View File

@ -42,7 +42,7 @@ fn get<T, U>(res: t<T, U>) -> T {
ok(t) { t }
err(_) {
// FIXME: Serialize the error value
// and include it in the fail message
// and include it in the fail message (maybe just note it)
fail "get called on error result";
}
}
@ -71,7 +71,7 @@ fn get_err<T, U>(res: t<T, U>) -> U {
Returns true if the result is <ok>
*/
fn success<T, U>(res: t<T, U>) -> bool {
pure fn success<T, U>(res: t<T, U>) -> bool {
alt res {
ok(_) { true }
err(_) { false }
@ -83,10 +83,17 @@ fn success<T, U>(res: t<T, U>) -> bool {
Returns true if the result is <error>
*/
fn failure<T, U>(res: t<T, U>) -> bool {
pure fn failure<T, U>(res: t<T, U>) -> bool {
!success(res)
}
pure fn to_either<copy T, copy U>(res: t<U, T>) -> either::t<T, U> {
alt res {
ok(res) { either::right(res) }
err(fail_) { either::left(fail_) }
}
}
/*
Function: chain