Skip to content

Commit

Permalink
stdlib: Add result module
Browse files Browse the repository at this point in the history
This contains a result tag with ok(T) and error(U) variants. I expect
to use it for error handling on functions that can recover from errors,
like in the io module.
  • Loading branch information
brson committed Oct 29, 2011
1 parent 802deac commit c1092fb
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
86 changes: 86 additions & 0 deletions src/lib/result.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
Module: result
A type representing either success or failure
*/

/* Section: Types */

/*
Tag: t
The result type
*/
tag t<T, U> {
/*
Variant: ok
Contains the result value
*/
ok(T);
/*
Variant: error
Contains the error value
*/
error(U);
}

/* Section: Operations */

/*
Function: get
Get the value out of a successful result
Failure:
If the result is an error
*/
fn get<T, U>(res: t<T, U>) -> T {
alt res {
ok(t) { t }
error(_) {
fail "get called on error result";
}
}
}

/*
Function: get
Get the value out of an error result
Failure:
If the result is not an error
*/
fn get_error<T, U>(res: t<T, U>) -> U {
alt res {
error(u) { u }
ok(_) {
fail "get_error called on ok result";
}
}
}

/*
Function: success
Returns true if the result is <ok>
*/
fn success<T, U>(res: t<T, U>) -> bool {
alt res {
ok(_) { true }
error(_) { false }
}
}

/*
Function: failure
Returns true if the result is <error>
*/
fn failure<T, U>(res: t<T, U>) -> bool {
!success(res)
}
1 change: 1 addition & 0 deletions src/lib/std.rc
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ mod test;
mod unsafe;
mod term;
mod math;
mod result;

#[cfg(unicode)]
mod unicode;
Expand Down

0 comments on commit c1092fb

Please sign in to comment.