/ scala

TOTD: Scala - Monoids

Today we're going to discuss Monoids. Ignoring the lingo for a minute, Monoids are things that can be combined and also obey the law of associativity. Monoids are also instances that have an identity. Do you obey laws? Do you know who you are? Integers happen to be Monoids over addition and multiplication. Observe:

1 + (2 + 3) = (1 + 2) + 3
let identity = 0
1 + 0 = 1
  • and -
1 * (2 * 3) = (1 * 2) * 3
let identity = 1
2 * 1 = 2

However, Integers are NOT Monoids over substraction or division:

1 - (2 - 3) != (1 - 2) - 3 // FAIL

Knowing these general properties of Monoids, we can reason about logic without caring about the implementation. We just need to trust that every instance obeys the law.

For those that care about lingo, Monoids are also Semigroups. This is THE reason why they can be combined. Monoids bring identity to the table via empty.