# Chapter 13: Monoids bring it all together

## Wild combination

In this chapter, we will examine *monoids* by way of *semigroup*. *Monoids* are the bubblegum in the hair of mathematical abstraction. They capture an idea that spans multiple disciplines, figuratively and literally bringing them all together. They are the ominous force that connects all that calculates. The oxygen in our code base, the ground on which it runs, quantum entanglement encoded.

*Monoids* are about combination. But what is combination? It can mean so many things from accumulation to concatenation to multiplication to choice, composition, ordering, even evaluation! We'll see many examples here, but we'll only tip-toe on the foothills of monoid mountain. The instances are plentiful and applications vast. The aim of this chapter is to provide a good intuition so you can make some *monoids* of your own.

## Abstracting addition

Addition has some interesting qualities I'd like to discuss. Let's have a look at it through our abstraction goggles.

For starters, it's a binary operation, that is, an operation which takes two values and returns a value, all within the same set.

See? Two values in the domain, one value in the codomain, all the same set - numbers, as it were. Some might say numbers are "closed under addition", meaning the type won't ever change no matter which ones get tossed into the mix. That means we can chain the operation since the result is always another number:

In addition to that (what a calculated pun...), we have associativity which buys us the ability to group operations however we please. Incidentally, an associative, binary operation is a recipe for parallel computation because we can chunk and distribute work.

Now, don't go confusing this with commutativity which allows us to rearrange the order. While that holds for addition, we're not particularly interested in that property at the moment - too specific for our abstraction needs.

Come to think of it, what properties should be in our abstract superclass anyways? What traits are specific to addition and what ones can be generalized? Are there other abstractions amidst this hierarchy or is it all one chunk? It's this kind of thinking that our mathematical forefathers applied when conceiving the interfaces in abstract algebra.

As it happens, those old school abstractionists landed on the concept of a *group* when abstracting addition. A *group* has all the bells and whistles including the concept of negative numbers. Here, we're only interested in that associative binary operator so we'll choose the less specific interface *Semigroup*. A *Semigroup* is a type with a `concat`

method which acts as our associative binary operator.

Let's implement it for addition and call it `Sum`

:

Note we `concat`

with some other `Sum`

and always return a `Sum`

.

I've used an object factory here instead of our typical prototype ceremony, primarily because `Sum`

is not *pointed* and we don't want to have to type `new`

. Anyways, here it is in action:

Just like that, we can program to an interface, not an implementation. Since this interface comes from group theory it has centuries of literature backing it up. Free docs!

Now, as mentioned, `Sum`

is not *pointed*, nor a *functor*. As an exercise, go back and check the laws to see why. Okay, I'll just tell you: it can only hold a number, so `map`

does not make sense here as we cannot transform the underlying value to another type. That would be a very limited `map`

indeed!

So why is this useful? Well, as with any interface, we can swap out our instance to achieve different results:

This isn't limited to numbers, though. Let's see some other types:

If you stare at these long enough the pattern will pop out at you like a magic eye poster. It's everywhere. We're merging data structures, combining logic, building strings...it seems one can bludgeon almost any task into this combination based interface.

I've used `Map`

a few times now. Pardon me if you two weren't properly introduced. `Map`

simply wraps `Object`

so we can embellish it with some extra methods without altering the fabric of the universe.

## All my favourite functors are semigroups.

The types we've seen so far which implement the functor interface all implement semigroup one as well. Let's look at `Identity`

(the artist previously known as Container):

It is a *semigroup* if and only if its `__value`

is a *semigroup*. Like a butterfingered hang glider, it is one whilst it holds one.

Other types have similar behavior:

This gets particularly useful when we stack these semigroups into a cascading combination:

In the top example, we've combined an `IO`

holding an `Either`

holding a `Map`

to validate and merge form values. Next, we've hit a couple of different servers and combined their results in an async way using `Task`

and `Array`

. Lastly, we've stacked `Task`

, `Maybe`

, and `Map`

to load, parse, and merge multiple settings.

These can be `chain`

ed or `ap`

'd, but *semigroups* capture what we'd like to do much more concisely.

This extends beyond functors. In fact, it turns out that anything made up entirely of semigroups, is itself, a semigroup: if we can concat the kit, then we can concat the caboodle.

See, everything knows how to combine itself nicely. Turns out, we could do the same thing for free just by using the `Map`

type:

We can stack and combine as many of these as we'd like. It's simply a matter of adding another tree to the forest, or another flame to the forest fire depending on your codebase.

The default, intuitive behavior is to combine what a type is holding, however, there are cases where we ignore what's inside and combine the containers themselves. Consider a type like `Stream`

:

We can combine event streams by capturing events from both as one new stream. Alternatively, we could have combined them by insisting they hold a semigroup. In fact, there are many possible instances for each type. Consider `Task`

, we can combine them by choosing the earlier or later of the two. We can always chose the first `Right`

instead of short circuiting on `Left`

which has the effect of ignoring errors. There is an interface called *Alternative* which implements some of these, well, alternative instances, typically focused on choice rather than cascading combination. It is worth looking into if you are in need of such functionality.

## Monoids for nothing

We were abstracting addition, but like the Babylonians, we lacked the concept of zero (there were zero mentions of it).

Zero acts as *identity* meaning any element added to `0`

, will return back that very same element. Abstraction-wise, it's helpful to think of `0`

as a kind of neutral or *empty* element. It's important that it act the same way on the left and right side of our binary operation:

Let's call this concept `empty`

and create a new interface with it. Like so many startups, we'll choose a heinously uninformative, yet conveniently googleable name: *Monoid*. The recipe for *Monoid* is to take any *semigroup* and add a special *identity* element. We'll implement that with an `empty`

function on the type itself:

When might an empty, identity value prove useful? That's like asking why zero is useful. Like not asking anything at all...

When we have nothing else, who can we count on? Zero. How many bugs do we want? Zero. It's our tolerance for unsafe code. A fresh start. The ultimate price tag. It can annihilate everything in its path or save us in a pinch. A golden life saver and a pit of despair.

Codewise, they correspond to sensible defaults:

Or to return a useful value when we have nothing else:

They are also the perfect initial value for an accumulator...

## Folding down the house

It just so happens that `concat`

and `empty`

fit perfectly in the first two slots of `reduce`

. We can actually `reduce`

an array of *semigroup*'s down by ignoring the *empty* value, but as you can see, that leads to a precarious situation:

Boom goes the dynamite. Like a twisted ankle in a marathon, we have ourselves a runtime exception. JavaScript is more than happy to let us strap pistols to our sneakers before running - it is a conservative sort of language, I suppose, but it stops us dead in our tracks when the array is barren. What could it return anyhow? `NaN`

, `false`

, `-1`

? If we were to continue on in our program, we'd like a result of the right type. It could return a `Maybe`

to indicate the possibility of failure, but we can do one better.

Let's use our curried `reduce`

function and make a safe version where the `empty`

value is not optional. It shall henceforth be known as `fold`

:

The initial `m`

is our `empty`

value - our neutral, starting point, then we take an array of `m`

's and crush them down to one beautiful diamond like value.

We've provided a manual `empty`

value for those last two since we can't define one on the type itself. That's totally fine. Typed languages can figure that out by themselves, but we have to pass it in here.

## Not quite a monoid

There are some *semigroups* that cannot become *monoids*, that is provide an initial value. Look at `First`

:

We'll merge a couple of accounts and keep the `First`

id. There is no way to define an `empty`

value for it. Doesn't mean it's not useful.

## Grand unifying theory

## Group theory or Category theory?

The notion of a binary operation is everywhere in abstract algebra. It is, in fact, the primary operation for a *category*. We cannot, however, model our operation in category theory without an *identity*. This is the reason we start with a semi-group from group theory, then jump to a monoid in category theory once we have *empty*.

Monoids form a single object category where the morphism is `concat`

, `empty`

is the identity, and composition is guaranteed.

### Composition as a monoid

Functions of type `a -> a`

, where the domain is in the same set as the codomain, are called *endomorphisms*. We can make a *monoid* called `Endo`

which captures this idea:

Since they are all the same type, we can `concat`

via `compose`

and the types always line up.

### Monad as a monoid

You may have noticed that `join`

is an operation which takes two (nested) monads and squashes them down to one in an associative fashion. It is also a natural transformation or "functor function". As previously stated, we can make a category of functors as objects with natural transformations as morphisms. Now, if we specialize it to *Endofunctors*, that is functors of the same type, then `join`

provides us with a monoid in the category of Endofunctors also known as a Monad. To show the exact formulation in code takes a little finagling which I encourage you to google, but that's the general idea.

### Applicative as a monoid

Even applicative functors have a monoidal formulation known in the category theory as a *lax monoidal functor*. We can implement the interface as a monoid and recover `ap`

from it:

## In summary

So you see, everything is connected, or can be. This profound realization makes *Monoids* a powerful modelling tool for broad swaths of app architecture to the tiniest pieces of datum. I encourage you to think of *monoids* whenever direct accumulation or combination is part of your application, then once you've got that down, start to stretch the definition to more applications (you'd be surprised how much one can model with a *monoid*).

## Exercises

Last updated