2014-02-05 16:33:10 -06:00
|
|
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
|
|
|
|
// file at the top-level directory of this distribution and at
|
|
|
|
// http://rust-lang.org/COPYRIGHT.
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
|
|
|
// option. This file may not be copied, modified, or distributed
|
|
|
|
// except according to those terms.
|
|
|
|
|
2014-09-06 13:52:07 -07:00
|
|
|
#![feature(advanced_slice_patterns)]
|
|
|
|
|
2015-01-02 17:32:54 -05:00
|
|
|
fn foldl<T, U, F>(values: &[T],
|
|
|
|
initial: U,
|
|
|
|
mut function: F)
|
|
|
|
-> U where
|
|
|
|
U: Clone,
|
|
|
|
F: FnMut(U, &T) -> U,
|
|
|
|
{
|
2013-02-27 03:58:46 +09:00
|
|
|
match values {
|
2014-09-06 15:23:55 -07:00
|
|
|
[ref head, tail..] =>
|
2013-05-22 06:54:35 -04:00
|
|
|
foldl(tail, function(initial, head), function),
|
2013-03-15 18:27:15 -04:00
|
|
|
[] => initial.clone()
|
2013-02-27 03:58:46 +09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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,
|
|
|
|
{
|
2013-02-27 03:58:46 +09:00
|
|
|
match values {
|
2014-09-06 15:23:55 -07:00
|
|
|
[head.., ref tail] =>
|
2013-05-22 06:54:35 -04:00
|
|
|
foldr(head, function(tail, initial), function),
|
2013-03-15 18:27:15 -04:00
|
|
|
[] => initial.clone()
|
2013-02-27 03:58:46 +09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn main() {
|
2014-11-17 21:39:01 +13:00
|
|
|
let x = &[1i, 2, 3, 4, 5];
|
2013-02-27 03:58:46 +09:00
|
|
|
|
2014-04-21 17:58:52 -04:00
|
|
|
let product = foldl(x, 1i, |a, b| a * *b);
|
2013-05-18 22:02:45 -04:00
|
|
|
assert_eq!(product, 120);
|
2013-02-27 03:58:46 +09:00
|
|
|
|
2014-04-21 17:58:52 -04:00
|
|
|
let sum = foldr(x, 0i, |a, b| *a + b);
|
2013-05-18 22:02:45 -04:00
|
|
|
assert_eq!(sum, 15);
|
2013-02-27 03:58:46 +09:00
|
|
|
}
|