Skip to content

Commit 2b62a80

Browse files
committed
stdlib: Add result::chain for composing results
1 parent c1092fb commit 2b62a80

File tree

3 files changed

+49
-8
lines changed

3 files changed

+49
-8
lines changed

src/lib/result.rs

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,11 @@ tag t<T, U> {
1919
*/
2020
ok(T);
2121
/*
22-
Variant: error
22+
Variant: err
2323
2424
Contains the error value
2525
*/
26-
error(U);
26+
err(U);
2727
}
2828

2929
/* Section: Operations */
@@ -40,24 +40,24 @@ If the result is an error
4040
fn get<T, U>(res: t<T, U>) -> T {
4141
alt res {
4242
ok(t) { t }
43-
error(_) {
43+
err(_) {
4444
fail "get called on error result";
4545
}
4646
}
4747
}
4848

4949
/*
50-
Function: get
50+
Function: get_err
5151
5252
Get the value out of an error result
5353
5454
Failure:
5555
5656
If the result is not an error
5757
*/
58-
fn get_error<T, U>(res: t<T, U>) -> U {
58+
fn get_err<T, U>(res: t<T, U>) -> U {
5959
alt res {
60-
error(u) { u }
60+
err(u) { u }
6161
ok(_) {
6262
fail "get_error called on ok result";
6363
}
@@ -72,7 +72,7 @@ Returns true if the result is <ok>
7272
fn success<T, U>(res: t<T, U>) -> bool {
7373
alt res {
7474
ok(_) { true }
75-
error(_) { false }
75+
err(_) { false }
7676
}
7777
}
7878

@@ -83,4 +83,27 @@ Returns true if the result is <error>
8383
*/
8484
fn failure<T, U>(res: t<T, U>) -> bool {
8585
!success(res)
86-
}
86+
}
87+
88+
/*
89+
Function: chain
90+
91+
Call a function based on a previous result
92+
93+
If `res` is <ok> then the value is extracted and passed to `op` whereupon
94+
`op`s result is returned. if `res` is <err> then it is immediately returned.
95+
This function can be used to compose the results of two functions.
96+
97+
Example:
98+
99+
> let res = chain(read_file(file), { |buf]
100+
> ok(parse_buf(buf))
101+
> })
102+
103+
*/
104+
fn chain<T, U, V>(res: t<T, V>, op: block(T) -> t<U, V>) -> t<U, V> {
105+
alt res {
106+
ok(t) { op(t) }
107+
err(e) { err(e) }
108+
}
109+
}

src/test/stdtest/result.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import std::result;
2+
3+
fn op1() -> result::t<int, str> { result::ok(666) }
4+
5+
fn op2(&&i: int) -> result::t<uint, str> { result::ok(i as uint + 1u) }
6+
7+
fn op3() -> result::t<int, str> { result::err("sadface") }
8+
9+
#[test]
10+
fn chain_success() {
11+
assert result::get(result::chain(op1(), op2)) == 667u;
12+
}
13+
14+
#[test]
15+
fn chain_failure() {
16+
assert result::get_err(result::chain(op3(), op2)) == "sadface";
17+
}

src/test/stdtest/stdtest.rc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ mod test;
3131
mod uint;
3232
mod float;
3333
mod math;
34+
mod result;
3435

3536
// Local Variables:
3637
// mode: rust

0 commit comments

Comments
 (0)