]> git.lizzy.rs Git - rust.git/commitdiff
stdlib: Fix the list::foldl implementation
authorBrian Anderson <banderson@mozilla.com>
Fri, 28 Oct 2011 20:45:32 +0000 (13:45 -0700)
committerBrian Anderson <banderson@mozilla.com>
Fri, 28 Oct 2011 20:45:32 +0000 (13:45 -0700)
src/lib/list.rs
src/test/stdtest/list.rs

index 955ba5fda5cd2c852ed27ce444e368b5d8e0d62a..07605d995c7acc511c5b72fac72678364aa30e23 100644 (file)
@@ -34,22 +34,22 @@ fn from_vec<T>(v: [mutable? T]) -> list<T> {
 
 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<T, U>(ls: list<T>, u: U, f: block(T, U) -> U) -> U {
-    let accum: U = u;
+fn foldl<T, U>(ls: list<U>, 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 @@ fn has<T>(ls: list<T>, elt: T) -> bool {
 Returns the length of a list
 */
 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(_, _));
 }
 
index 980f0535e7a84a3e7b8d88044a7a940de028f181..9b0b78bb810a20b99eecf106a41126b5af557b67 100644 (file)
@@ -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]);