Learn the law of Monoid from a Scala developer’s perspective, how it works in Scala, and various useful encoding patterns using Monoid.
Join the DZone community and get the full member experience. 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: In this article, we will discuss the law of Monoid from a Scala developer’s perspective, how it works in Scala, and various useful encoding patterns using Monoid. The Monoid law is the combination of the law of associativity and the law of identity. A monoid consists of the following: The law of associativity states that the grouping of the binary operation does not change the result. For instance, the binary operation can be addition: (a + b) + c = a + (b+c) Or the binary operation can be multiplication: (a*b)*c = a*(b*c) The law of identity indicates both left identity and right identity; when applied with any value of type A in the associative operation; it does not change the result. For instance,0 is the identity for addition: 0 + a = a + 0 = a And,1 is the identity for multiplication: 1*a = a*1 = a Thus, an instance of monoid shall have all three terms defined: a type, an associative operator, and an identity value. For instance, Monoid(Int, addition,0), Monoid(Int, multiplication,1), are all different instances of monoid that comply with the law of monoid. Thus, in Scala, a monoid instance is a tuple of three terms of Monoid trait: a type parameter, an identity value, and an associative function: where A defines a type, z is the identity value, and f is an associative function. Monoid implementation is typically type classes. As an important design pattern in Scala, type class is an approach to ad-hoc polymorphism; thus, each implementation of a parameterized type is an ad-hoc to Monoid trait.