pub trait Alt: Functor {
// Required method
fn alt<'a, A: 'a>(
fa1: <Self as Kind_cdc7cd43dac7585f>::Of<'a, A>,
fa2: <Self as Kind_cdc7cd43dac7585f>::Of<'a, A>,
) -> <Self as Kind_cdc7cd43dac7585f>::Of<'a, A>;
}Expand description
A type class for associative choice on type constructors.
Alt is similar to Semigroup, except that it applies to types of
kind * -> * (like Option or Vec) rather than concrete types
(like String or i32).
A common use case is to select the first “valid” item, or, if all items are “invalid”, fall back to the last item.
§Laws
Alt instances must satisfy the following laws:
- Associativity:
alt(alt(x, y), z) = alt(x, alt(y, z)). - Distributivity:
map(f, alt(x, y)) = alt(map(f, x), map(f, y)).
§Examples
Alt laws for Option:
use fp_library::{
brands::*,
classes::*,
functions::explicit::*,
};
// Associativity: alt(alt(x, y), z) = alt(x, alt(y, z))
let x: Option<i32> = None;
let y = Some(1);
let z = Some(2);
assert_eq!(
alt::<OptionBrand, _, _, _>(alt::<OptionBrand, _, _, _>(x, y), z),
alt::<OptionBrand, _, _, _>(x, alt::<OptionBrand, _, _, _>(y, z)),
);
// Distributivity: map(f, alt(x, y)) = alt(map(f, x), map(f, y))
let f = |i: i32| i * 2;
let x = Some(3);
let y: Option<i32> = None;
assert_eq!(
map::<OptionBrand, _, _, _, _>(f, alt::<OptionBrand, _, _, _>(x, y)),
alt::<OptionBrand, _, _, _>(
map::<OptionBrand, _, _, _, _>(f, x),
map::<OptionBrand, _, _, _, _>(f, y)
),
);Required Methods§
Sourcefn alt<'a, A: 'a>(
fa1: <Self as Kind_cdc7cd43dac7585f>::Of<'a, A>,
fa2: <Self as Kind_cdc7cd43dac7585f>::Of<'a, A>,
) -> <Self as Kind_cdc7cd43dac7585f>::Of<'a, A>
fn alt<'a, A: 'a>( fa1: <Self as Kind_cdc7cd43dac7585f>::Of<'a, A>, fa2: <Self as Kind_cdc7cd43dac7585f>::Of<'a, A>, ) -> <Self as Kind_cdc7cd43dac7585f>::Of<'a, A>
Chooses between two values in a context.
This method provides an associative binary operation on type constructors.
For Option, this returns the first Some value. For Vec, this
concatenates the two vectors.
§Type Signature
forall A. (Self A, Self A) -> Self A
§Type Parameters
'a: The lifetime of the values.A: The type of the value inside the context.
§Parameters
fa1: The first value.fa2: The second value.
§Returns
The chosen/combined value.
§Examples
use fp_library::{
brands::*,
classes::*,
functions::explicit::*,
};
let x: Option<i32> = None;
let y = Some(5);
let z = alt::<OptionBrand, _, _, _>(x, y);
assert_eq!(z, Some(5));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.