pub trait Foldable: Kind1L1T {
// Required methods
fn fold_right<'a, A: 'a, B: 'a, F>(
f: F,
init: B,
fa: Apply1L1T<'a, Self, A>,
) -> B
where F: Fn(A, B) -> B + 'a;
fn fold_left<'a, A: 'a, B: 'a, F>(
f: F,
init: B,
fa: Apply1L1T<'a, Self, A>,
) -> B
where F: Fn(B, A) -> B + 'a;
fn fold_map<'a, A: 'a, M, F>(f: F, fa: Apply1L1T<'a, Self, A>) -> M
where M: Monoid + 'a,
F: Fn(A) -> M + 'a;
}Expand description
A type class for structures that can be folded to a single value.
A Foldable represents a structure that can be folded over to combine its elements
into a single result.
Required Methods§
Sourcefn fold_right<'a, A: 'a, B: 'a, F>(
f: F,
init: B,
fa: Apply1L1T<'a, Self, A>,
) -> Bwhere
F: Fn(A, B) -> B + 'a,
fn fold_right<'a, A: 'a, B: 'a, F>(
f: F,
init: B,
fa: Apply1L1T<'a, Self, A>,
) -> Bwhere
F: Fn(A, B) -> B + 'a,
Folds the structure by applying a function from right to left.
§Type Signature
forall a b. Foldable t => ((a, b) -> b, b, t a) -> b
§Parameters
f: The function to apply to each element and the accumulator.init: The initial value of the accumulator.fa: The structure to fold.
§Returns
The final accumulator value.
§Examples
use fp_library::classes::foldable::Foldable;
use fp_library::brands::OptionBrand;
let x = Some(5);
let y = OptionBrand::fold_right(|a, b| a + b, 10, x);
assert_eq!(y, 15);Sourcefn fold_left<'a, A: 'a, B: 'a, F>(
f: F,
init: B,
fa: Apply1L1T<'a, Self, A>,
) -> Bwhere
F: Fn(B, A) -> B + 'a,
fn fold_left<'a, A: 'a, B: 'a, F>(
f: F,
init: B,
fa: Apply1L1T<'a, Self, A>,
) -> Bwhere
F: Fn(B, A) -> B + 'a,
Folds the structure by applying a function from left to right.
§Type Signature
forall a b. Foldable t => ((b, a) -> b, b, t a) -> b
§Parameters
f: The function to apply to the accumulator and each element.init: The initial value of the accumulator.fa: The structure to fold.
§Returns
The final accumulator value.
§Examples
use fp_library::classes::foldable::Foldable;
use fp_library::brands::OptionBrand;
let x = Some(5);
let y = OptionBrand::fold_left(|b, a| b + a, 10, x);
assert_eq!(y, 15);Sourcefn fold_map<'a, A: 'a, M, F>(f: F, fa: Apply1L1T<'a, Self, A>) -> M
fn fold_map<'a, A: 'a, M, F>(f: F, fa: Apply1L1T<'a, Self, A>) -> M
Maps values to a monoid and combines them.
§Type Signature
forall a m. (Foldable t, Monoid m) => ((a) -> m, t a) -> m
§Parameters
f: The function to map each element to a monoid.fa: The structure to fold.
§Returns
The combined monoid value.
§Examples
use fp_library::classes::foldable::Foldable;
use fp_library::brands::OptionBrand;
use fp_library::types::string; // Import Monoid impl for String
let x = Some(5);
let y = OptionBrand::fold_map(|a: i32| a.to_string(), x);
assert_eq!(y, "5".to_string());Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.