Commutative

Trait Commutative 

Source
pub trait Commutative: Semigroup { }
Expand description

Commutative represents a binary operation that satisfies the following property

  1. Commutativity: op(a, b) = op(b, a)

The semigroup set that satisfies the commutativity property is often called commutative semigroup.

And the monoid set that satisfies the commutativity property is often called commutative monoid.

This is marker trait.

§Examples

§Deriving

Commutative can be derived like Semigroup, use commutative attribute.

use semigroup::Semigroup;
#[derive(Debug, Clone, PartialEq, Default, Semigroup)]
#[semigroup(commutative)]
pub struct ExampleStruct {
    #[semigroup(with = "semigroup::op::Sum")]
    pub sum: u32,
    #[semigroup(with = "semigroup::op::Min")]
    pub min: u32,
}

let a = ExampleStruct { sum: 1, min: 1 };
let b = ExampleStruct { sum: 10, min: 10 };
let c = ExampleStruct { sum: 100, min: 100 };

// #[test]
semigroup::assert_commutative!(&a, &b, &c);
assert_eq!(a.semigroup(b).semigroup(c), ExampleStruct { sum: 111, min: 1 });

§Construction

Commutative can be constructed like Semigroup, use commutative attribute.

use semigroup::{Construction, Semigroup};

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash, Construction)]
#[construction(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_commutative!(&a, &b, &c);
assert_eq!(a.semigroup(b).semigroup(c), Sum(6));

§Testing

Use crate::assert_commutative! macro.

The commutativity property is not guaranteed by Rust’s type system, so it must be verified manually using crate::assert_commutative!.

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<C: Counter> Commutative for HdrHistogram<C>
where HdrHistogramInner<C>: Commutative,

Available on crate feature histogram only.
Source§

impl<T> Commutative for Lazy<T>
where T: Commutative,

Source§

impl<T> Commutative for OptionMonoid<T>

Available on crate feature monoid only.
Source§

impl<T> Commutative for Reverse<T>

Source§

impl<T, A> Commutative for Annotated<T, A>

Source§

impl<T: Ord> Commutative for Max<T>

Source§

impl<T: Ord> Commutative for Min<T>

Source§

impl<T: Add<Output = T>> Commutative for Sum<T>

Source§

impl<T: Mul<Output = T>> Commutative for Prod<T>

Source§

impl<T: BitXor<Output = T>> Commutative for Xor<T>

Source§

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

Available on crate feature monoid only.
Source§

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

Available on crate feature monoid only.