Skip to content

Commit fde719f

Browse files
committed
core: Implement foldl/r without copying the accumulator
1 parent d679c0e commit fde719f

File tree

1 file changed

+18
-12
lines changed

1 file changed

+18
-12
lines changed

src/libcore/iter.rs

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -65,18 +65,18 @@ fn flat_map<A,B,IA:iterable<A>,IB:iterable<B>>(
6565
}
6666
}
6767

68-
fn foldl<A,B:copy,IA:iterable<A>>(self: IA, b0: B, blk: fn(B, A) -> B) -> B {
69-
let b = b0;
68+
fn foldl<A,B,IA:iterable<A>>(self: IA, +b0: B, blk: fn(-B, A) -> B) -> B {
69+
let b <- b0;
7070
self.iter {|a|
7171
b = blk(b, a);
7272
}
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 {
76+
fn foldr<A:copy,B,IA:iterable<A>>(
77+
self: IA, +b0: B, blk: fn(A, -B) -> B) -> B {
7878

79-
let b = b0;
79+
let b <- b0;
8080
reverse(self) {|a|
8181
b = blk(a, b);
8282
}
@@ -111,10 +111,13 @@ fn repeat(times: uint, blk: fn()) {
111111
}
112112

113113
fn min<A:copy,IA:iterable<A>>(self: IA) -> A {
114-
alt foldl(self, none) {|a, b|
114+
alt foldl::<A,option<A>,IA>(self, none) {|a, b|
115115
alt a {
116-
some(a) { some(math::min(a, b)) }
117-
none { some(b) }
116+
some(a_) if a_ < b {
117+
// FIXME: Not sure if this is successfully optimized to a move
118+
a
119+
}
120+
_ { some(b) }
118121
}
119122
} {
120123
some(val) { val }
@@ -123,10 +126,13 @@ fn min<A:copy,IA:iterable<A>>(self: IA) -> A {
123126
}
124127

125128
fn max<A:copy,IA:iterable<A>>(self: IA) -> A {
126-
alt foldl(self, none) {|a, b|
129+
alt foldl::<A,option<A>,IA>(self, none) {|a, b|
127130
alt a {
128-
some(a) { some(math::max(a, b)) }
129-
none { some(b) }
131+
some(a_) if a_ > b {
132+
// FIXME: Not sure if this is successfully optimized to a move
133+
a
134+
}
135+
_ { some(b) }
130136
}
131137
} {
132138
some(val) { val }
@@ -252,7 +258,7 @@ fn test_count() {
252258

253259
#[test]
254260
fn test_foldr() {
255-
fn sub(&&a: int, &&b: int) -> int {
261+
fn sub(&&a: int, -b: int) -> int {
256262
a - b
257263
}
258264
let sum = foldr([1, 2, 3, 4], 0, sub);

0 commit comments

Comments
 (0)