3 ms·
A monoid is a type where we know how to combine two elements together. There are two parts: a function that combines and an identity for it. (The function is us
by tikhonj 11y ago
A monoid is a type where we know how to combine two elements together. There are two parts: a function that combines and an identity for it. (The function is usually written as an infix operator to make it easier to read.)
For example, we can combine two integers by adding (+) with 0 as an identity. Or we could combine them by (*) with 1 as an identity.
Lists are a monoid because we can append two lists and the empty list is the identity.
The combining operator has to be associative and the identity has to be an identity for it. (Combining something with the identity gives you that original thing back.)
And that's all. There's just not much structure to them. In fact, there's so little structure that mathematicians don't care much about them. It's an exotic-sounding name for a fairly pedestrian concept.
But they're useful in programming. The main reason is that they're so ubiquitous: so many different things form monoids, often in different ways. This means we have a single interface applicable to almost every domain you can think of which is useful even if the interface doesn't tell us much.
They're also a good fit for parallelism. Because the combining function is associative, we can a bunch of combinations in any order we like, making it easy to spread them out over multiple threads. It very naturally captures the reduce in map reduce.
But mostly it's a convenient abstraction that's minimal and simple enough to pop up everywhere while still being useful.