Monoid is just one of subsets of Magmas. There are others, like a semigroup.
Semigroups is a superset of monoids. Every monoid is a semigroup, while the opposite is not true. They have very similar requirements as monoids, with an exception for the identity element - it does not have to exist for a semigroup to be formed.
With that, a semigroup is a tuple consisting of:
- a set
- a binary operation
All the other Monoid rules still apply:
- arguments of the operation must be of the same type as the returned value
An example of a semigroup is a set of real numbers, and the MIN operation. Since there is no identity element (real numbers go from -Inf to +Inf), we cannot call that semigroup a monoid.
Similarly, MAX operation could form a semigroup, but not a monoid.
Other examples of semigroups, that are not monoids, include:
- T First(T first, T second)
Just like monoids, semigroups may be accumulated. Having multiple values from some set, we can accumulate them into one element, with the use of semigroup’s binary operation.
Since semigroups do not have an identity element, in the example above we have
to make sure that the collection is not empty. Otherwise, what would a
Math.Min return? In case of monoids, where identity/neutral element exists,
that element would be returned from an accumulation.
Another subset of Magmas is Quasigroups. A quasigroup is a set Q with a binary operation * that satisfies the Latin square property. Quasigroups don’t require an identity element to be there, or an operation to be associative.
An example of a quasigroup that is neither a monoid or a semigroup is a set of integers and the subtraction operation. Subtraction satisfies Latin square property.
Quasigroups are not that useful in the programming area.
We’ve gone from monoids to quasigroups, and all of them are subset of a greater set of Magmas.
Magmas is simply a set with a binary operation - no other requirements there!
Rock Paper Scissors
The Rock, Paper, Scissors game may be thought of as a Magma. If you think about it, the game may be modeled with a binary function:
The function above (operation) does not have an identity element (not a Monoid), and it is not associative (not a Semigroup), and it does not satisfy the Latin Square Property (not a Quasigroup). However, it is a binary operation, so it certainly is a Magma.
Interestingly, the Rock Paper Scissors “operation” is commutative (ab = ba), but in the world of magmas that doesn’t have any impact. Associativity would at least give us a Semigroups, commutativity does not.