2024-02-16 20:02:50 +00:00
|
|
|
//@ run-pass
|
2018-08-30 12:18:55 +00:00
|
|
|
|
2016-03-11 10:54:59 +00:00
|
|
|
use std::fmt::Debug;
|
|
|
|
|
2015-01-02 22:32:54 +00:00
|
|
|
fn foldl<T, U, F>(values: &[T],
|
|
|
|
initial: U,
|
|
|
|
mut function: F)
|
|
|
|
-> U where
|
2016-03-11 10:54:59 +00:00
|
|
|
U: Clone+Debug, T:Debug,
|
2015-01-02 22:32:54 +00:00
|
|
|
F: FnMut(U, &T) -> U,
|
2016-03-11 10:54:59 +00:00
|
|
|
{ match values {
|
2019-07-07 23:47:46 +00:00
|
|
|
&[ref head, ref tail @ ..] =>
|
2013-05-22 10:54:35 +00:00
|
|
|
foldl(tail, function(initial, head), function),
|
2016-03-11 10:54:59 +00:00
|
|
|
&[] => {
|
|
|
|
// FIXME: call guards
|
|
|
|
let res = initial.clone(); res
|
|
|
|
}
|
2013-02-26 18:58:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-02 22:32:54 +00:00
|
|
|
fn foldr<T, U, F>(values: &[T],
|
|
|
|
initial: U,
|
|
|
|
mut function: F)
|
|
|
|
-> U where
|
|
|
|
U: Clone,
|
|
|
|
F: FnMut(&T, U) -> U,
|
|
|
|
{
|
2013-02-26 18:58:46 +00:00
|
|
|
match values {
|
2019-07-07 23:47:46 +00:00
|
|
|
&[ref head @ .., ref tail] =>
|
2013-05-22 10:54:35 +00:00
|
|
|
foldr(head, function(tail, initial), function),
|
2016-03-11 10:54:59 +00:00
|
|
|
&[] => {
|
|
|
|
// FIXME: call guards
|
|
|
|
let res = initial.clone(); res
|
|
|
|
}
|
2013-02-26 18:58:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn main() {
|
2015-01-25 21:05:03 +00:00
|
|
|
let x = &[1, 2, 3, 4, 5];
|
2013-02-26 18:58:46 +00:00
|
|
|
|
2015-01-25 21:05:03 +00:00
|
|
|
let product = foldl(x, 1, |a, b| a * *b);
|
2013-05-19 02:02:45 +00:00
|
|
|
assert_eq!(product, 120);
|
2013-02-26 18:58:46 +00:00
|
|
|
|
2015-01-25 21:05:03 +00:00
|
|
|
let sum = foldr(x, 0, |a, b| *a + b);
|
2013-05-19 02:02:45 +00:00
|
|
|
assert_eq!(sum, 15);
|
2013-02-26 18:58:46 +00:00
|
|
|
}
|