Skip to content

Commit d679c0e

Browse files
committed
core: Add iter::foldr
1 parent 3edad35 commit d679c0e

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/libcore/iter.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,16 @@ fn foldl<A,B:copy,IA:iterable<A>>(self: IA, b0: B, blk: fn(B, A) -> B) -> B {
7373
ret b;
7474
}
7575

76+
fn foldr<A:copy,B:copy,IA:iterable<A>>(
77+
self: IA, b0: B, blk: fn(A, B) -> B) -> B {
78+
79+
let b = b0;
80+
reverse(self) {|a|
81+
b = blk(a, b);
82+
}
83+
ret b;
84+
}
85+
7686
fn to_list<A:copy,IA:iterable<A>>(self: IA) -> [A] {
7787
foldl::<A,[A],IA>(self, [], {|r, a| r + [a]})
7888
}
@@ -238,4 +248,13 @@ fn test_reverse() {
238248
#[test]
239249
fn test_count() {
240250
assert count([1, 2, 1, 2, 1], 1) == 3u;
251+
}
252+
253+
#[test]
254+
fn test_foldr() {
255+
fn sub(&&a: int, &&b: int) -> int {
256+
a - b
257+
}
258+
let sum = foldr([1, 2, 3, 4], 0, sub);
259+
assert sum == -2;
241260
}

0 commit comments

Comments
 (0)