Monoid

Trait Monoid 

Source
pub trait Monoid: Semigroup {
    // Required method
    fn empty() -> Self;

    // Provided method
    fn concat<I>(iter: I) -> Self
       where I: IntoIterator<Item = Self> { ... }
}
Expand description

A monoid: a semigroup with an identity element.

Laws (not enforced by type system):

  • Associative: a.combine(b).combine(c) == a.combine(b.combine(c))
  • Left identity: empty().combine(a) == a
  • Right identity: a.combine(empty()) == a

§Example

use algebra::Monoid;
use algebra::Semigroup;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Product(i32);

impl Semigroup for Product {
    fn combine(&self, other: &Self) -> Self {
        Product(self.0 * other.0)
    }
}

impl Monoid for Product {
    fn empty() -> Self {
        Product(1)
    }
}

let x = Product(3);
let y = Product(5);
assert_eq!(x.combine(&y), Product(15));
assert_eq!(Product::empty().combine(&x), x);
assert_eq!(x.combine(&Product::empty()), x);

Required Methods§

Source

fn empty() -> Self

The identity element.

Provided Methods§

Source

fn concat<I>(iter: I) -> Self
where I: IntoIterator<Item = Self>,

Fold an iterator using combine, starting from empty.

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§