Semigroup is probably the simplest yet most useful algebraic structure. It is fully defined by two qualities:
- It is defined for some (possibly infinite) set of elements
- It has a binary operation defined for any pairs of elements in this set
It also has the following two properties:
- The operation is closed, which means that the result of the operation belongs to the same set as its operands
- The operation is associative, meaning that multiple operations should produce the same result, regardless of the order in which they are applied
We can translate these definitions into the Scala code almost literally:
trait Semigroup[S] {
def op(l: S, r: S): S
}
S denotes the type that the set elements belong to, and op denotes the operation. The result type is also S—we have defined the property of closeness of the operation on the type level. Formally, it is said that S...