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; }
}
}
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(_, _));
}
#[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]);