Monoid[String] 真的是 Scala 中的 Monoid 吗

Is Monoid[String] really a Monoid in scala

我目前正在学习 Scala 中的范畴论和结合律

(x + y) + z = x + (y + z)

处理两个以上的值时就没问题了

("Foo" + "Bar") + "Test" == "Foo" + ("Bar" + "Test") // true

在那种情况下,顺序无关紧要。但是如果只有两个值呢?如果对于数字它仍然有效(可交换)但是当用字符串做同样的事情时它会失败。

3+1==1+3 // True
("Foo" + "Bar") == ("Bar" + "Foo") // Not commuative

那么说结合性需要交换性来满足幺半群定律是否合法?那么 String Monoid 无论如何都有效吗?

So is it legal to say that associativity requires commutativity to fulfill the monoid law?

没有。二元运算不需要是可交换的才能结合。 ("Foo" + "Bar") == ("Bar" + "Foo") 为假的事实与 +String.

相关的事实无关

And so is a String Monoid valid anyway?

是的,你可以 Monoid[String]

根据定义:

A monoid is a set that is closed under an associative binary operation +and has an identity element I in S such that for all a in S, I + a = a + I = a.

A monoid must contain at least one element.

+Monoid[String]的二元运算。对于任意两个字符串,aba + b也是一个String,所以二元运算在String类型上是封闭的。不用严格证明,我们也知道它是结合的。

即对于所有字符串 abc:

(a + b) + c == a + (b + c)

我们还有一个标识元素 ""(空字符串),因为对于任何字符串 aa + "" == a"" + a == a.

二元运算也是可交换的幺半群称为可交换幺半群。并且您显然不能使用 + 操作为 String 获得可交换的幺半群。