diff options
| author | Brian Anderson <banderson@mozilla.com> | 2012-02-12 02:57:50 -0800 |
|---|---|---|
| committer | Brian Anderson <banderson@mozilla.com> | 2012-02-12 19:24:24 -0800 |
| commit | d679c0eb3486408ca7575eb70a0fc55a0d3de235 (patch) | |
| tree | bc7183d2917edd73808491180415a99baf20174d | |
| parent | 3edad3555e1f5c01572f32e84480383c1ae2b472 (diff) | |
| download | rust-d679c0eb3486408ca7575eb70a0fc55a0d3de235.tar.gz rust-d679c0eb3486408ca7575eb70a0fc55a0d3de235.zip | |
core: Add iter::foldr
| -rw-r--r-- | src/libcore/iter.rs | 19 |
1 files changed, 19 insertions, 0 deletions
diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 6af10bd8a35..eec41833351 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -73,6 +73,16 @@ fn foldl<A,B:copy,IA:iterable<A>>(self: IA, b0: B, blk: fn(B, A) -> B) -> B { ret b; } +fn foldr<A:copy,B:copy,IA:iterable<A>>( + self: IA, b0: B, blk: fn(A, B) -> B) -> B { + + let b = b0; + reverse(self) {|a| + b = blk(a, b); + } + ret b; +} + fn to_list<A:copy,IA:iterable<A>>(self: IA) -> [A] { foldl::<A,[A],IA>(self, [], {|r, a| r + [a]}) } @@ -238,4 +248,13 @@ fn test_reverse() { #[test] fn test_count() { assert count([1, 2, 1, 2, 1], 1) == 3u; +} + +#[test] +fn test_foldr() { + fn sub(&&a: int, &&b: int) -> int { + a - b + } + let sum = foldr([1, 2, 3, 4], 0, sub); + assert sum == -2; } \ No newline at end of file |
