From 39b729e36f813a58de6b1f5641c94f47b7a6c277 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Fri, 28 Oct 2011 13:45:32 -0700 Subject: [PATCH] stdlib: Fix the list::foldl implementation --- src/lib/list.rs | 14 +++++++------- src/test/stdtest/list.rs | 12 +++++++++++- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/src/lib/list.rs b/src/lib/list.rs index 955ba5fda5c..07605d995c7 100644 --- a/src/lib/list.rs +++ b/src/lib/list.rs @@ -34,22 +34,22 @@ Function: foldl Left fold -Applies `f` to the first argument in the list and `u`, then applies -`f` to the second argument and the result of the previous call, +Applies `f` to `u` and the first element in the list, then applies +`f` to the result of the previous call and the second element, and so on, returning the accumulated result. Parameters: ls - The list to fold -u - The initial value +z - The initial value f - The function to apply */ -fn foldl(ls: list, u: U, f: block(T, U) -> U) -> U { - let accum: U = u; +fn foldl(ls: list, z: T, f: block(T, U) -> T) -> T { + let accum: T = z; let ls = ls; while true { alt ls { - cons(hd, tl) { accum = f(hd, accum); ls = *tl; } + cons(hd, tl) { accum = f(accum, hd); ls = *tl; } nil. { break; } } } @@ -100,7 +100,7 @@ Function: len Returns the length of a list */ fn len(ls: list) -> uint { - fn count(_t: T, &&u: uint) -> uint { ret u + 1u; } + fn count(&&u: uint, _t: T) -> uint { ret u + 1u; } ret foldl(ls, 0u, bind count(_, _)); } diff --git a/src/test/stdtest/list.rs b/src/test/stdtest/list.rs index 980f0535e7a..9b0b78bb810 100644 --- a/src/test/stdtest/list.rs +++ b/src/test/stdtest/list.rs @@ -25,11 +25,21 @@ fn test_from_vec_mut() { #[test] fn test_foldl() { 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); 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] fn test_find_success() { let l = from_vec([0, 1, 2]);