Better Encoding With Monoids in Scala

Monoid has its root in abstract algebra. It is a semigroup with an identity; in other words, it has an associative binary operation and an identity element. In Scala, we can define it as follows:

Scala
 




xxxxxxxxxx
1


 
1
trait Monoid[A] {
2
  def id: A
3
  def op(a1: A, a2: A): A
4
}
5