]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/vec-matching-fold.rs
Rollup merge of #34175 - rwz:patch-2, r=alexcrichton
[rust.git] / src / test / run-pass / vec-matching-fold.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11
12 #![feature(advanced_slice_patterns)]
13 #![feature(slice_patterns)]
14 #![feature(rustc_attrs)]
15
16 use std::fmt::Debug;
17
18 #[rustc_mir(graphviz="mir.gv")]
19 fn foldl<T, U, F>(values: &[T],
20                   initial: U,
21                   mut function: F)
22                   -> U where
23     U: Clone+Debug, T:Debug,
24     F: FnMut(U, &T) -> U,
25 {    match values {
26         &[ref head, ref tail..] =>
27             foldl(tail, function(initial, head), function),
28         &[] => {
29             // FIXME: call guards
30             let res = initial.clone(); res
31         }
32     }
33 }
34
35 #[rustc_mir]
36 fn foldr<T, U, F>(values: &[T],
37                   initial: U,
38                   mut function: F)
39                   -> U where
40     U: Clone,
41     F: FnMut(&T, U) -> U,
42 {
43     match values {
44         &[ref head.., ref tail] =>
45             foldr(head, function(tail, initial), function),
46         &[] => {
47             // FIXME: call guards
48             let res = initial.clone(); res
49         }
50     }
51 }
52
53 pub fn main() {
54     let x = &[1, 2, 3, 4, 5];
55
56     let product = foldl(x, 1, |a, b| a * *b);
57     assert_eq!(product, 120);
58
59     let sum = foldr(x, 0, |a, b| *a + b);
60     assert_eq!(sum, 15);
61 }