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