Implement vec::foldl without recursion

This commit is contained in:
Brian Anderson 2011-10-27 20:47:06 -07:00
parent b5ed1c46c0
commit 1a89e589a4
2 changed files with 16 additions and 6 deletions

View file

@ -433,14 +433,14 @@ fn filter<T>(f: block(T) -> bool, v: [mutable? T]) -> [T] {
/*
Function: foldl
FIXME: This looks like it's actually foldr
Reduce a vector from left to right
*/
fn foldl<T, U>(p: block(U, T) -> U, z: U, v: [mutable? T]) -> U {
let sz = len(v);
if sz == 0u { ret z; }
let first = v[0];
let rest = slice(v, 1u, sz);
ret p(foldl(p, z, rest), first);
let accum = z;
iter(v) { |elt|
accum = p(accum, elt);
}
ret accum;
}
/*

View file

@ -292,6 +292,16 @@ fn test_foldl() {
assert (sum == 15u);
}
#[test]
fn test_foldl2() {
fn sub(&&a: int, &&b: int) -> int {
a - b
}
let v = [1, 2, 3, 4];
let sum = vec::foldl(sub, 0, v);
assert sum == -10;
}
#[test]
fn iter_empty() {
let i = 0;