From fde719f635955b1c3d76639062410262fd0df351 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 12 Feb 2012 03:04:33 -0800 Subject: [PATCH] core: Implement foldl/r without copying the accumulator --- src/libcore/iter.rs | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index eec41833351..c2fc2838d70 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -65,18 +65,18 @@ fn flat_map,IB:iterable>( } } -fn foldl>(self: IA, b0: B, blk: fn(B, A) -> B) -> B { - let b = b0; +fn foldl>(self: IA, +b0: B, blk: fn(-B, A) -> B) -> B { + let b <- b0; self.iter {|a| b = blk(b, a); } ret b; } -fn foldr>( - self: IA, b0: B, blk: fn(A, B) -> B) -> B { +fn foldr>( + self: IA, +b0: B, blk: fn(A, -B) -> B) -> B { - let b = b0; + let b <- b0; reverse(self) {|a| b = blk(a, b); } @@ -111,10 +111,13 @@ fn repeat(times: uint, blk: fn()) { } fn min>(self: IA) -> A { - alt foldl(self, none) {|a, b| + alt foldl::,IA>(self, none) {|a, b| alt a { - some(a) { some(math::min(a, b)) } - none { some(b) } + some(a_) if a_ < b { + // FIXME: Not sure if this is successfully optimized to a move + a + } + _ { some(b) } } } { some(val) { val } @@ -123,10 +126,13 @@ fn min>(self: IA) -> A { } fn max>(self: IA) -> A { - alt foldl(self, none) {|a, b| + alt foldl::,IA>(self, none) {|a, b| alt a { - some(a) { some(math::max(a, b)) } - none { some(b) } + some(a_) if a_ > b { + // FIXME: Not sure if this is successfully optimized to a move + a + } + _ { some(b) } } } { some(val) { val } @@ -252,7 +258,7 @@ fn test_count() { #[test] fn test_foldr() { - fn sub(&&a: int, &&b: int) -> int { + fn sub(&&a: int, -b: int) -> int { a - b } let sum = foldr([1, 2, 3, 4], 0, sub);