Idempotent Monoid
IdempotentMonoid is a monoid that is also idempotent, i.e. adding a value to itself yields the same value.
IdempotentMonoid must satisfy the laws of its parent types:
- Closure (closure): for \(\forall x, y \in IM\), \(x + y \in IM\).
- Associativity (associativity): for \(\forall x, y, z \in IM\), \((x + y) + z = x + (y + z)\).
- Identity (identity): there exists \(\exists e \in IM\) such that for \(\forall x \in IM\), \(e + x = x + e = x\)
- Idempotency (idempotency): for \(\forall x \in IM\), \(x + x = x\).
Code
trait IdempotentMonoid[A] extends Monoid[A], Band[A]:
override def combineN(a: A, n: Int): Either[String, A] =
if n < 0 then
Left("Repeated combining for monoids must have n >= 0")
else if n == 0 then Right(empty)
else Right(a) // combine(a, a) == a
Sets
Some set operations are idempotent: union, intersection, etc.
For example, the union of sets forms an IdempotentMonoid:
given [A]: IdempotentMonoid[Set[A]] with
def empty: Set[A] = Set.empty[A]
def combine(x: Set[A], y: Set[A]): Set[A] = x ++ y
Laws
Laws are inherited from monoid and idempotent semigroup.
Diagram
classDiagram
class Semigroup~A~{
+combine(x: A, y: A) A
}
class IdempotentSemigroup~A~
Semigroup <|-- IdempotentSemigroup
class Monoid~A~{
+empty() A
}
Semigroup <|-- Monoid
class IdempotentMonoid~A~
IdempotentSemigroup <|-- IdempotentMonoid
Monoid <|-- IdempotentMonoid
References: