"foo".length + "bar".length == ("foo" + "bar").length
To be precise, this is saying that length
is a monoid homomorphism between the monoid of strings with concatenation, and the monoid of natural numbers with addition. That these two structures are monoids are easy to see if you put in the effort.
The reason length
is a monoid homomorphism is because it has the properties that "".length = 0
and x.length ⊕ y.length = (x ⊗ y).length
. Here, I've deliberately used two different symbols for the two monoid operations, to stress the fact that we are either applying the addition operation on the results of applying length
vs the string concatenation operation on the two arguments before applying length
. It is just unfortunate notation that the example you're looking at uses the same symbol +
for both operations.
Edited to add: The question poster asked for some further details on what exactly is a monoid homomorphism.
OK, so suppose we have two monoids (A, ⊕, a) and (B, ⊗, b), meaning A and B are our two carriers, ⊕ : A × A → A and ⊗ : B × B → B are our two binary operators, and a ∈ A and b ∈ B are our two neutral elements. A monoid homomorphism between these two monoids is a function f : A → B with the following properties:
- f(a) = b, i.e. if you apply f on the neutral element of A, you get the neutral element of B
- f(x ⊕ y) = f(x) ⊗ f(y), i.e. if you apply f on the result of the operator of A on two elements, it is the same as applying it twice, on the two A elements, and then combining the results using the operator of B.
The point is that the monoid homomorphism is a structure-preserving mapping (which is what a homomorphism is; break down the word to its ancient Greek roots and you will see that it means 'same-shaped-ness').
OK, you asked for examples, here are some examples!
- The one from the above example:
length
is a monoid homomorphism from the free monoid (A, ·, ε)* to (ℕ, +, 0)
- Negation is a monoid homomorphism from (Bool, ∨, false) to (Bool, ∧, true) and vice verse.
- exp is a monoid homomorphism from (ℝ, +, 0) to (ℝ\{0}, *, 1)
- In fact, every group homomorphism is also, of course, a monoid homomorphism.