rust_fp_categories/
foldable.rs

1pub trait Foldable: Sized {
2    type Elm;
3
4    fn fold_left<B, F>(&self, b: B, f: F) -> B
5    where
6        F: Fn(B, &Self::Elm) -> B;
7
8    fn fold_right<B, F>(&self, b: B, f: F) -> B
9    where
10        F: Fn(&Self::Elm, B) -> B;
11}
12
13impl<A> Foldable for Vec<A> {
14    type Elm = A;
15
16    fn fold_left<B, F>(&self, b: B, f: F) -> B
17    where
18        F: Fn(B, &Self::Elm) -> B,
19    {
20        self.iter().fold(b, f)
21    }
22
23    fn fold_right<B, F>(&self, b: B, f: F) -> B
24    where
25        F: Fn(&Self::Elm, B) -> B,
26    {
27        self.iter().rev().fold(b, |x, y| f(y, x))
28    }
29}