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
pub trait Foldable: Sized { type Elm; fn fold_left<B, F>(&self, b: B, f: F) -> B where F: Fn(B, &Self::Elm) -> B; fn fold_right<B, F>(&self, b: B, f: F) -> B where F: Fn(&Self::Elm, B) -> B; } impl<A> Foldable for Vec<A> { type Elm = A; fn fold_left<B, F>(&self, b: B, f: F) -> B where F: Fn(B, &Self::Elm) -> B, { self.iter().fold(b, f) } fn fold_right<B, F>(&self, b: B, f: F) -> B where F: Fn(&Self::Elm, B) -> B, { self.iter().rev().fold(b, |x, y| f(y, x)) } }