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:

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: