MonoidHom

Trait MonoidHom 

Source
pub trait MonoidHom: SemigroupHom { }
Expand description

A monoid homomorphism: a structure-preserving map between monoids.

A homomorphism f: M → N preserves both the monoid operation and identity:

Laws (not enforced by type system):

  • Preserve combine: f(x.combine(y)) == f(x).combine(f(y))
  • Preserve identity: f(M::empty()) == N::empty()

§Example

use algebra_core::{Monoid, Semigroup, MonoidHom, SemigroupHom};
use std::collections::HashSet;

// Wrapper for usize with addition
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Sum(usize);

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

impl Monoid for Sum {
    fn empty() -> Self { Sum(0) }
}

// Set cardinality: a monoid homomorphism from (HashSet, ∪) to
// (Sum, +)
// Note: Exact homomorphism property holds for disjoint unions
struct Cardinality;

impl SemigroupHom for Cardinality {
    type Source = HashSet<i32>;
    type Target = Sum;

    fn apply(&self, s: &HashSet<i32>) -> Sum {
        Sum(s.len())
    }
}

impl MonoidHom for Cardinality {}

// Verify identity preservation: |∅| = 0
let card = Cardinality;
assert_eq!(card.apply(&HashSet::empty()), Sum::empty());

Implementors§