Having looked around for an answer to this question, there was little in terms of simple explanations this post serves to fill that gap. It’s a pretty simple concept and while it has big implications and the technicals of it are worth articulating extremely clearly it should have been simpler to find a good explanation hopefully this does a good job without getting prematurely in depth.

In category theory a monoid is a *set* where 1. there exists a binary operation (like addition or subtraction) that is associative and 2. there exists some element in that set that implements an identity. But for the sake of programming it’s just a set of laws or rules and people love to refer to them as* algebras* or *the algebra of a monoid*.

The monoid laws are those two properties we just talked about, the ability to perform some associative function where two elements of a type A are combined, which in almost every example meant to be read by a programmer has been named *op*. To be sure by associative the following must be true:

1 |
op(op(x, y), z) == op(x, op(y, z)) |

Basically it won’t matter what order these are performed in and a small amount of thinking about this concept of associativity and the word parallelism should help shine light on why this might be a nice to have. So that’s the first law and quoting one the main influences that inspired this post the second is also, *“embarrassingly simple”*. Its the identity element mentioned earlier basically all it does is guarantee that for any op with an element *x* of type A there is another value *zero* of type A such that it gives us *x*. To be clear:

1 |
op(zero, x) == x |

In scala examples of this abound

1 2 3 4 5 6 7 8 9 10 11 |
// Like This trait Monoid[A]{ def op(a1: A, a2: A): A def zero: A } // Or Like This trait Monoid[T] { def Zero: T def op: (T,T) => T } |

Wow the fact that you wanted to know what a monoid was enough to make it down here means you’re probably a genius.

Here are links that made this post possible: