stdlib: Fix the list::foldl implementation

This commit is contained in:
Brian Anderson 2011-10-28 13:45:32 -07:00
parent 49e8ffa34f
commit 39b729e36f
2 changed files with 18 additions and 8 deletions

View file

@ -34,22 +34,22 @@ Function: foldl
Left fold Left fold
Applies `f` to the first argument in the list and `u`, then applies Applies `f` to `u` and the first element in the list, then applies
`f` to the second argument and the result of the previous call, `f` to the result of the previous call and the second element,
and so on, returning the accumulated result. and so on, returning the accumulated result.
Parameters: Parameters:
ls - The list to fold ls - The list to fold
u - The initial value z - The initial value
f - The function to apply f - The function to apply
*/ */
fn foldl<T, U>(ls: list<T>, u: U, f: block(T, U) -> U) -> U { fn foldl<T, U>(ls: list<U>, z: T, f: block(T, U) -> T) -> T {
let accum: U = u; let accum: T = z;
let ls = ls; let ls = ls;
while true { while true {
alt ls { alt ls {
cons(hd, tl) { accum = f(hd, accum); ls = *tl; } cons(hd, tl) { accum = f(accum, hd); ls = *tl; }
nil. { break; } nil. { break; }
} }
} }
@ -100,7 +100,7 @@ Function: len
Returns the length of a list Returns the length of a list
*/ */
fn len<T>(ls: list<T>) -> uint { fn len<T>(ls: list<T>) -> uint {
fn count<T>(_t: T, &&u: uint) -> uint { ret u + 1u; } fn count<T>(&&u: uint, _t: T) -> uint { ret u + 1u; }
ret foldl(ls, 0u, bind count(_, _)); ret foldl(ls, 0u, bind count(_, _));
} }

View file

@ -25,11 +25,21 @@ fn test_from_vec_mut() {
#[test] #[test]
fn test_foldl() { fn test_foldl() {
let l = from_vec([0, 1, 2, 3, 4]); let l = from_vec([0, 1, 2, 3, 4]);
fn add(&&a: int, &&b: uint) -> uint { ret (a as uint) + b; } fn add(&&a: uint, &&b: int) -> uint { ret a + (b as uint); }
let rs = list::foldl(l, 0u, add); let rs = list::foldl(l, 0u, add);
assert (rs == 10u); assert (rs == 10u);
} }
#[test]
fn test_foldl2() {
fn sub(&&a: int, &&b: int) -> int {
a - b
}
let l = from_vec([1, 2, 3, 4]);
let sum = list::foldl(l, 0, sub);
assert sum == -10;
}
#[test] #[test]
fn test_find_success() { fn test_find_success() {
let l = from_vec([0, 1, 2]); let l = from_vec([0, 1, 2]);