Monoid

Pavel Gnatyuk
2 min readNov 22, 2020
Photo by Omar Ram on Unsplash

“If you have a monoid, you should have a demonoid too?” — my daughter asked me passing near by. I was watching a meet-up video about the functional programming.

We demonise the monoid. It is a pretty simple thing. Simple for every body.

Let’s talk about a set of elements, a collection. There is an operation defined in this set. It takes two elements and creates a new element from this set. This operation is binary — because it works with two elements.

If the operation result does not depend on the order of the element in it, the operation is associative. This set with this operation has a special name — semigroup. For example, integer numbers and addition operation create the semigroup.

If this semigroup contains a neutral element that does not change the second element when used in the operation…. We got the monoid.

That’s it!

We can continue this way. We have a neutral element — a zero element. We may find two elements that give the zero element in this binary operation. We name these elements as inverse elements. And this is the group.

For example, two integer numbers, 5 and -5 gives 0. Any integer number has an inverse element for the addition operation. This is an example of a group.

Continue this simplified way. We will get to other algebraic structures: abelian group, cyclic group and so on.

It is simple in algebra and applicable in the programming. We use it without paying a lot of attention. Even without knowing it, experienced programmers invent it themselves.

For example, string concatenation: we take two strings and combine them together. It generates another string. It is a binary operation. The empty string is the neutral element. We are talking about the monoid.

In Swift the following protocol presents it:

protocol Monoid {      static var neutral: Self { get }      func operation(_ other: Self) -> Self}

Let’s extend the String:

extension String: Monoid {       static var neutral: String = ""       func operation(_ other: String) -> String {           self + other       }}

String is a monoid in respect to string concatenation.

Other examples?

Array of elements and the concatenation. The empty element is the empty array.

And now check this line of code:

[“H”, “e”, “l”, “l”, “o”].reduce(“”) { $0 + $1 }

In this line we see the set of elements: “H”, “e”, “l”, “l”, “o”, and the empty element “” and the concatenation operation.

--

--