Skip to content

Commit

Permalink
std: added either::flip, to_result and result::to_either
Browse files Browse the repository at this point in the history
  • Loading branch information
boggle committed Dec 16, 2011
1 parent fd1dd76 commit 1fe4bd0
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
25 changes: 25 additions & 0 deletions src/libcore/either.rs
Expand Up @@ -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
Expand Down
13 changes: 10 additions & 3 deletions src/libcore/result.rs
Expand Up @@ -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";
}
}
Expand Down Expand Up @@ -71,7 +71,7 @@ Function: success
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 }
Expand All @@ -83,10 +83,17 @@ Function: failure
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
Expand Down

0 comments on commit 1fe4bd0

Please sign in to comment.