3 ms·
Consider these equations for integers: x * 1 = x 1 * x = 1 x * (y * z) = (x * y) * z These should be familiar if you know about integers. Now con
by curryhoward 7y ago
Consider these equations for integers:
x * 1 = x
1 * x = 1
x * (y * z) = (x * y) * z
These should be familiar if you know about integers.
Now consider the following equations for strings:
concat(x, "") = x
concat("", x) = x
concat(x, concat(y, z)) = concat(concat(x, y), z)
These should be familiar if you know about strings.
Now consider the following equations for booleans:
x or false = x
false or x = x
x or (y or z) = (x or y) or z
These should be familiar if you know about booleans.
If you can see the pattern, you understand monoids. Monoids are everywhere in programming.
- deleted 7y ago[deleted]
- RangerScience 7y agoThis is fantastic, thank you! Alright, first thing I noticed was the presence of identity operators. But then you're replacing the identity "operator" with an expression. Combining this with some of what other people are saying, and one aspect of monoids is that they're... chainable? The value of a monoid expression is the same type as the parameters of the monoid expression; `bar someMonoidFunction(bar x, bar y)`...? This then has some interesting ramifications for chaining/composing, as you demonstrate in the third example of each group. There's... something further than this, I can tell, but it's not yet clear to me. Can you do one these wonderful - heh, koans, basically - for something like `sin(cos(x))`?
- BoiledCabbage 7y agoYou've pretty much got it. A monoid is a two argunent operation and a data type with 3 properties: It's 'chainable', or the more precise mathematical term is "closed". It has a value that can be used as an identity. And it's associative. Where associative means that when 'chaining' multiple operations (as you termed it) it doesn't matter how you group with parentheses; it'll produce the same result.
- kmill 7y agoFunction composition is a monoid: (f ∘ g) ∘ h = f ∘ (g ∘ h). For example, (sin ∘ cos) ∘ tan = sin ∘ (cos ∘ tan). It's not commutative in general; sin ∘ cos != cos ∘ sin (in fact, sin(cos(x)) != cos(sin(x)) no matter the value of x). The identity function I(x)=x is the identity: f ∘ I = f = I ∘ f.