ELI5: Monoids

Monoid:

We have a thing, perform some action on it, get that same type of thing back.

Say I have a big bowl of candy:

  • I can add another smaller bowl of candies to that bowl and I'd still have a big bowl of candies

  • I can dump an empty bowl of candy into my big bowl of candy and I'd end up with the same big bowl of candy

  • I can add to the big bowl of candies:

    • all the candies from a little red bowl and then add all the candies from a little blue bowl

    OR

    • all the candies from a little blue bowl and then add all the candies from a little red bowl

It doesn't matter how I do this because I'll still have a big bowl of candy at the end.


And now for the non-ELI5:

The important thing to note here is that the above would not be true for all "things" or for all "actions". Say for instance instead of "big bowl of candies" I instead used, "Getting ready for school in the morning (showering then getting dressed)". We see a logical failure immediately:

  • I can't get dressed before I take a shower (that would be a mess)

So "being ready for school in the morning" under the action "showering" is not a monoid.

Monoid is a grossly academic/mathematic word that basically means a set that is closed under a specific action (operation). To be more "computer science-y", strings (being the set) under concatenation (the operation) are a monoid:

  • (Closure) Adding a string to a string still results in a string, i.e. we're still in the "set" of strings
  • (Associativity) Adding an empty string to a string (say, '' + 'cat') will give you 'cat' back
  • (Identity) Adding string1 to string2 or vice versa will still give you a string back, i.e. we're still in the "set" of strings

This wouldn't work for strings under the operation of equality (==) because instead of having a string returned to us, we'd instead get a boolean.

So...

  • A Monoid is just a thing that holds true to the above three rules

Hopefully you are now a more enlightened five-year-old.

comment

Comments