Monoid

Trait Monoid 

Source
pub trait Monoid: Semigroup {
    // Required method
    fn unit() -> Self;
}
Available on crate feature monoid only.
Expand description

Monoid represents a binary operation that satisfies the following properties

  1. Closure: op: T × T → T
  2. Associativity: op(op(a, b), c) = op(a, op(b, c))
  3. Existence of identity element: op(unit(), a) = a = op(a, unit())

§Deriving

Monoid can be derived like Semigroup, use monoid attribute.

use semigroup::{Semigroup, Monoid};
#[derive(Debug, Clone, PartialEq, Default, Semigroup)]
#[semigroup(monoid, with = "semigroup::op::Coalesce")]
pub struct ExampleStruct<'a> {
    pub str: Option<&'a str>,
    #[semigroup(with = "semigroup::op::Sum")]
    pub sum: u32,
}

let a = ExampleStruct::unit();
let b = ExampleStruct { str: Some("ten"), sum: 10 };
let c = ExampleStruct { str: None, sum: 100 };

// #[test]
semigroup::assert_monoid!(&a, &b, &c);
assert_eq!(a.semigroup(b).semigroup(c), ExampleStruct { str: Some("ten"), sum: 110 });

§Construction

Monoid can be constructed by crate::ConstructionMonoid like Semigroup, use monoid attribute.

Some operations are already provided by crate::op.

use semigroup::{Construction, Semigroup, Monoid};

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash, Construction)]
#[construction(monoid, commutative, unit = Self(0))]
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::unit(), Sum(2), Sum(3));
// #[test]
semigroup::assert_monoid!(&a, &b, &c);
assert_eq!(a.semigroup(b).semigroup(c), Sum(5));

§Optional Semigroup

Option<Semigroup> can behave like Monoid. In such case, OptionMonoid is useful.

§Testing

Use crate::assert_monoid! macro.

The closure and associativity properties are same as Semigroup, so they are guaranteed by crate::assert_semigroup!. However, existence of identity element is not guaranteed the macro, so it must be verified manually using crate::assert_monoid!.

Required Methods§

Source

fn unit() -> Self

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§

Source§

impl<T> Monoid for Coalesce<T>

Source§

impl<T> Monoid for Max<T>
where T: Bounded + Ord,

Source§

impl<T> Monoid for Min<T>
where T: Bounded + Ord,

Source§

impl<T> Monoid for Prod<T>
where T: One + Mul<Output = T>,

Source§

impl<T> Monoid for Sum<T>
where T: Zero + Add<Output = T>,

Source§

impl<T> Monoid for Xor<T>
where T: Zero + BitXor<Output = T>,

Source§

impl<T: IntoIterator + FromIterator<T::Item>> Monoid for Concat<T>

Source§

impl<T: Counter> Monoid for HdrHistogram<T>

Available on crate feature histogram only.
Source§

impl<T: Unsigned + Integer + Clone> Monoid for Gcd<T>

Source§

impl<T: Unsigned + Integer + Clone> Monoid for Lcm<T>

Source§

impl<T: Semigroup> Monoid for OptionMonoid<T>