2018-08-30 14:18:55 +02:00
|
|
|
//@ run-pass
|
|
|
|
|
2016-03-11 12:54:59 +02:00
|
|
|
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
|
2016-03-11 12:54:59 +02:00
|
|
|
U: Clone+Debug, T:Debug,
|
2015-01-02 17:32:54 -05:00
|
|
|
F: FnMut(U, &T) -> U,
|
2016-03-11 12:54:59 +02:00
|
|
|
{ match values {
|
2019-07-08 01:47:46 +02:00
|
|
|
&[ref head, ref tail @ ..] =>
|
2013-05-22 06:54:35 -04:00
|
|
|
foldl(tail, function(initial, head), function),
|
2016-03-11 12:54:59 +02:00
|
|
|
&[] => {
|
|
|
|
// FIXME: call guards
|
|
|
|
let res = initial.clone(); res
|
|
|
|
}
|
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 {
|
2019-07-08 01:47:46 +02:00
|
|
|
&[ref head @ .., ref tail] =>
|
2013-05-22 06:54:35 -04:00
|
|
|
foldr(head, function(tail, initial), function),
|
2016-03-11 12:54:59 +02:00
|
|
|
&[] => {
|
|
|
|
// FIXME: call guards
|
|
|
|
let res = initial.clone(); res
|
|
|
|
}
|
2013-02-27 03:58:46 +09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn main() {
|
2015-01-25 22:05:03 +01:00
|
|
|
let x = &[1, 2, 3, 4, 5];
|
2013-02-27 03:58:46 +09:00
|
|
|
|
2015-01-25 22:05:03 +01:00
|
|
|
let product = foldl(x, 1, |a, b| a * *b);
|
2013-05-18 22:02:45 -04:00
|
|
|
assert_eq!(product, 120);
|
2013-02-27 03:58:46 +09:00
|
|
|
|
2015-01-25 22:05:03 +01:00
|
|
|
let sum = foldr(x, 0, |a, b| *a + b);
|
2013-05-18 22:02:45 -04:00
|
|
|
assert_eq!(sum, 15);
|
2013-02-27 03:58:46 +09:00
|
|
|
}
|