rust/src/test/run-pass/vec-matching-fold.rs
Niko Matsakis 5851d3242c Move checking for moves and initialization of local variables and patterns into
borrow checker and generalize what moves are allowed. Fixes a nasty
bug or two in the pattern move checking code. Unifies dataflow code
used for initialization and other things. First step towards
once fns. Everybody wins.

Fixes #4384. Fixes #4715. cc once fns (#2202), optimizing local moves (#5016).
2013-05-28 20:22:14 -04:00

34 lines
726 B
Rust

fn foldl<T, U: Copy+Clone>(
values: &[T],
initial: U,
function: &fn(partial: U, element: &T) -> U
) -> U {
match values {
[ref head, ..tail] =>
foldl(tail, function(initial, head), function),
[] => initial.clone()
}
}
fn foldr<T, U: Copy+Clone>(
values: &[T],
initial: U,
function: &fn(element: &T, partial: U) -> U
) -> U {
match values {
[..head, ref tail] =>
foldr(head, function(tail, initial), function),
[] => initial.clone()
}
}
pub fn main() {
let x = [1, 2, 3, 4, 5];
let product = foldl(x, 1, |a, b| a * *b);
assert_eq!(product, 120);
let sum = foldr(x, 0, |a, b| *a + b);
assert_eq!(sum, 15);
}