os-rust/tests/ui/array-slice-vec/vec-matching-fold.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

47 lines
1 KiB
Rust
Raw Normal View History

//@ run-pass
use std::fmt::Debug;
2015-01-02 17:32:54 -05:00
fn foldl<T, U, F>(values: &[T],
initial: U,
mut function: F)
-> U where
U: Clone+Debug, T:Debug,
2015-01-02 17:32:54 -05:00
F: FnMut(U, &T) -> U,
{ match values {
2019-07-08 01:47:46 +02:00
&[ref head, ref tail @ ..] =>
foldl(tail, function(initial, head), function),
&[] => {
// FIXME: call guards
let res = initial.clone(); res
}
}
}
2015-01-02 17:32:54 -05:00
fn foldr<T, U, F>(values: &[T],
initial: U,
mut function: F)
-> U where
U: Clone,
F: FnMut(&T, U) -> U,
{
match values {
2019-07-08 01:47:46 +02:00
&[ref head @ .., ref tail] =>
foldr(head, function(tail, initial), function),
&[] => {
// FIXME: call guards
let res = initial.clone(); res
}
}
}
pub fn main() {
2015-01-25 22:05:03 +01:00
let x = &[1, 2, 3, 4, 5];
2015-01-25 22:05:03 +01:00
let product = foldl(x, 1, |a, b| a * *b);
assert_eq!(product, 120);
2015-01-25 22:05:03 +01:00
let sum = foldr(x, 0, |a, b| *a + b);
assert_eq!(sum, 15);
}