1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use crate::hkt::HKT;
use crate::monoid::Monoid;
pub trait Foldable<B>: HKT<B> + Sized {
fn reduce<F>(self, b: B, ba: F) -> B
where
F: Fn(B, &<Self as HKT<B>>::Current) -> B;
fn reduce_right<F>(self, b: B, f: F) -> B
where
F: Fn(&<Self as HKT<B>>::Current, B) -> B;
}
pub fn fold_map<M, C, F>(container: C, mapper: F) -> M
where
M: Monoid,
C: Foldable<M>,
F: Fn(&<C as HKT<M>>::Current) -> M,
{
container.reduce(M::empty(), |acc, curr| acc.combine(mapper(curr)))
}
impl<A, B> Foldable<B> for Vec<A> {
fn reduce<F>(self, b: B, fa: F) -> B
where
F: Fn(B, &A) -> B,
{
self.iter().fold(b, fa)
}
fn reduce_right<F>(self, b: B, fa: F) -> B
where
F: Fn(&A, B) -> B,
{
self.iter().rev().fold(b, |x, y| fa(y, x))
}
}