]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/vec-matching-fold.rs
rustdoc: Replace no-pretty-expanded with pretty-expanded
[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 // pretty-expanded FIXME #23616
12
13 #![feature(advanced_slice_patterns)]
14
15 fn foldl<T, U, F>(values: &[T],
16                   initial: U,
17                   mut function: F)
18                   -> U where
19     U: Clone,
20     F: FnMut(U, &T) -> U,
21 {
22     match values {
23         [ref head, tail..] =>
24             foldl(tail, function(initial, head), function),
25         [] => initial.clone()
26     }
27 }
28
29 fn foldr<T, U, F>(values: &[T],
30                   initial: U,
31                   mut function: F)
32                   -> U where
33     U: Clone,
34     F: FnMut(&T, U) -> U,
35 {
36     match values {
37         [head.., ref tail] =>
38             foldr(head, function(tail, initial), function),
39         [] => initial.clone()
40     }
41 }
42
43 pub fn main() {
44     let x = &[1, 2, 3, 4, 5];
45
46     let product = foldl(x, 1, |a, b| a * *b);
47     assert_eq!(product, 120);
48
49     let sum = foldr(x, 0, |a, b| *a + b);
50     assert_eq!(sum, 15);
51 }