I am currently learning about category theory in scala and the law of associativity says
(x + y) + z = x + (y + z)
Thats just fine when working with more than two values
("Foo" + "Bar") + "Test" == "Foo" + ("Bar" + "Test") // true
In that case order doesn't matter. But what if there are only two values. In case for numbers its still working ( commutative ) but when doing the same thing with strings it fails.
3+1==1+3 // True
("Foo" + "Bar") == ("Bar" + "Foo") // Not commuative
So is it legal to say that associativity requires commudativity to fullfill the monoid law ? And so is a String Monoid valid anyway ?
So is it legal to say that associativity requires commutativity to fulfill the monoid law?
No. A binary operation does not need to be commutative to be associative. The fact that ("Foo" + "Bar") == ("Bar" + "Foo")
is false is irrelevant to the fact that +
is associative for String.
And so is a String Monoid valid anyway?
Yes, you can have a Monoid[String]
.
By definition:
A monoid is a set that is closed under an associative binary operation
+
and has an identity elementI
inS
such that for alla
inS
, I+ a = a + I = a
.A monoid must contain at least one element.
Let +
be the binary operation for a Monoid[String]
. For any two strings, a
and b
, a + b
is also a String
, so the binary operation is closed over the type String
. Without rigorous proof, we also know that it is associative.
ie for all strings a
, b
, and c
:
(a + b) + c == a + (b + c)
We also have an identity element ""
(the empty string), because for any string a
, a + "" == a
and "" + a == a
.
A monoid whose binary operation is also a commutative is called a commutative monoid . And you clearly cannot have a commutative monoid for String
using the +
operation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.