pub trait Semigroup {
// Required method
fn op(base: Self, other: Self) -> Self;
// Provided method
fn semigroup(self, other: Self) -> Self
where Self: Sized { ... }
}Expand description
Semigroup represents a binary operation that satisfies the following properties
- Closure:
op: T × T → T - Associativity:
op(op(a, b), c) = op(a, op(b, c))
§Deriving
When fields do not implement Semigroup, use with attribute.
use semigroup::Semigroup;
#[derive(Debug, Clone, PartialEq, Semigroup)]
#[semigroup(with = "semigroup::op::Coalesce")]
pub struct ExampleStruct<'a> {
pub str: Option<&'a str>,
#[semigroup(with = "semigroup::op::Overwrite")]
pub boolean: bool,
#[semigroup(with = "semigroup::op::Sum")]
pub sum: u32,
}
let a = ExampleStruct { str: None, boolean: true, sum: 1 };
let b = ExampleStruct { str: Some("ten"), boolean: false, sum: 10 };
let c = ExampleStruct { str: None, boolean: false, sum: 100 };
// #[test]
semigroup::assert_semigroup!(&a, &b, &c);
assert_eq!(a.semigroup(b).semigroup(c), ExampleStruct { str: Some("ten"), boolean: false, sum: 111 });§Construction
Semigroup can be constructed by crate::Construction.
Some operations are already provided by crate::op.
use semigroup::{Construction, Semigroup};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash, Construction)]
#[construction(monoid, commutative)]
pub struct Sum(u64);
impl Semigroup for Sum {
fn op(base: Self, other: Self) -> Self {
Self(base.0 + other.0)
}
}
let (a, b, c) = (Sum(1), Sum(2), Sum(3));
// #[test]
semigroup::assert_semigroup!(&a, &b, &c);
assert_eq!(a.semigroup(b).semigroup(c), Sum(6));§Testing
Use crate::assert_semigroup! macro.
The closure property is guaranteed by Rust’s type system,
but associativity must be verified manually using crate::assert_semigroup!.
Required Methods§
Provided Methods§
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.
Implementors§
impl<T> Semigroup for Coalesce<T>
impl<T> Semigroup for Overwrite<T>
impl<T: Ord> Semigroup for Max<T>
impl<T: Ord> Semigroup for Min<T>
impl<T: IntoIterator + FromIterator<T::Item>> Semigroup for Concat<T>
impl<T: Add<Output = T>> Semigroup for Sum<T>
impl<T: Mul<Output = T>> Semigroup for Prod<T>
impl<T: BitXor<Output = T>> Semigroup for Xor<T>
impl<T: Counter> Semigroup for HdrHistogram<T>
Available on crate feature
histogram only.impl<T: Unsigned + Integer + Clone> Semigroup for Gcd<T>
Available on crate feature
monoid only.impl<T: Unsigned + Integer + Clone> Semigroup for Lcm<T>
Available on crate feature
monoid only.impl<T: AnnotatedSemigroup<A>, A> Semigroup for Annotated<T, A>
impl<T: Semigroup> Semigroup for OptionMonoid<T>
Available on crate feature
monoid only.