Skip to content

Instantly share code, notes, and snippets.

@tjheslin1
Last active November 27, 2017 17:22
Show Gist options
  • Save tjheslin1/7c2a7996579043dc64558026e8f552c7 to your computer and use it in GitHub Desktop.
Save tjheslin1/7c2a7996579043dc64558026e8f552c7 to your computer and use it in GitHub Desktop.

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
}

Laws of Monoid

empty must be an identify element (e.g "" for addition of string's)

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" ++ ""

For all values x, y and z, in B, combine must be associative

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")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment