Taken from scala-with-cats by Noel Welsh and Dave Gurnell
A monoid for a type B
is:
- an operation combine with type
(B, B) => B
- an element empty of type
B
trait Monoid[B] {
def combine(x: B, y: B): B
def empty: B
}
def associativeLaw[A](x: A, y: A, z: A)(implicit m: Monoid[A]): Boolean = {
m.combine(x, m.combine(y, z)) == m.combine(m.combine(x, y), z)
}
"" ++ "Hello" == "Hello" ++ ""
the order in which the elements are combined shouldn' affect the result of type B
.
def identityLaw[A](x: A)(implicit m: Monoid[A]): Boolean = {
(m.combine(x, m.empty) == x) && (m.combine(m.empty, x) == x)
}
("One" ++ "Two") ++ "Three" == "One" ++ ("Two" ++ "Three")