fp_core/
foldable.rs

1use crate::hkt::HKT;
2use crate::monoid::Monoid;
3
4// Cheating: all HKT instances exist for any B,
5// so HKT<B> here isn't about Self<B> having any meaning,
6// it's about folding on some Self<A> -- the HKT lets us
7// have an A to speak of.
8pub 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
18// Biggest hardship with trying to put this into the above:
19// we cannot have B constrained to be a Monoid, so having
20// a default implementation becomes impossible. That said,
21// having this as a separate function might make more sense
22// (in particular, it might be easier to implement Foldable for
23// rust containers as above and not have to worry about our Monoid
24// until "later" -- when this function is handy).
25pub 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    // TODO: make sure this is correct.
43    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}