]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/tests/pass/vec-matching-fold.rs
Auto merge of #104915 - weihanglo:update-cargo, r=ehuss
[rust.git] / src / tools / miri / tests / pass / vec-matching-fold.rs
1 use std::fmt::Debug;
2
3 fn foldl<T, U, F>(values: &[T], initial: U, mut function: F) -> U
4 where
5     U: Clone + Debug,
6     T: Debug,
7     F: FnMut(U, &T) -> U,
8 {
9     match values {
10         [head, tail @ ..] => foldl(tail, function(initial, head), function),
11         [] => {
12             let res = initial.clone();
13             res
14         }
15     }
16 }
17
18 fn foldr<T, U, F>(values: &[T], initial: U, mut function: F) -> U
19 where
20     U: Clone,
21     F: FnMut(&T, U) -> U,
22 {
23     match values {
24         [head @ .., tail] => foldr(head, function(tail, initial), function),
25         [] => {
26             let res = initial.clone();
27             res
28         }
29     }
30 }
31
32 pub fn main() {
33     let x = &[1, 2, 3, 4, 5];
34
35     let product = foldl(x, 1, |a, b| a * *b);
36     assert_eq!(product, 120);
37
38     let sum = foldr(x, 0, |a, b| *a + b);
39     assert_eq!(sum, 15);
40 }