2013-07-10 16:43:25 -05:00
|
|
|
fn foldl<T,U:Clone>(values: &[T],
|
|
|
|
initial: U,
|
|
|
|
function: &fn(partial: U, element: &T) -> U)
|
|
|
|
-> U {
|
2013-02-26 12:58:46 -06:00
|
|
|
match values {
|
2013-05-22 05:54:35 -05:00
|
|
|
[ref head, ..tail] =>
|
|
|
|
foldl(tail, function(initial, head), function),
|
2013-03-15 17:27:15 -05:00
|
|
|
[] => initial.clone()
|
2013-02-26 12:58:46 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-07-10 16:43:25 -05:00
|
|
|
fn foldr<T,U:Clone>(values: &[T],
|
|
|
|
initial: U,
|
|
|
|
function: &fn(element: &T, partial: U) -> U)
|
|
|
|
-> U {
|
2013-02-26 12:58:46 -06:00
|
|
|
match values {
|
2013-05-22 05:54:35 -05:00
|
|
|
[..head, ref tail] =>
|
|
|
|
foldr(head, function(tail, initial), function),
|
2013-03-15 17:27:15 -05:00
|
|
|
[] => initial.clone()
|
2013-02-26 12:58:46 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn main() {
|
|
|
|
let x = [1, 2, 3, 4, 5];
|
|
|
|
|
|
|
|
let product = foldl(x, 1, |a, b| a * *b);
|
2013-05-18 21:02:45 -05:00
|
|
|
assert_eq!(product, 120);
|
2013-02-26 12:58:46 -06:00
|
|
|
|
|
|
|
let sum = foldr(x, 0, |a, b| *a + b);
|
2013-05-18 21:02:45 -05:00
|
|
|
assert_eq!(sum, 15);
|
2013-02-26 12:58:46 -06:00
|
|
|
}
|