5

我正在阅读《Scala 编程》这本书(红皮书)。

在关于 Monoids 的章节中,我了解了 Monoid 同态是什么,例如:M具有连接和length函数的 String Monoidf保留了幺半群结构,因此是同态的。

M.op(f(x), f(y)) == M.op(f(x) + f(y))
// "Lorem".length + "ipsum".length == ("Lorem" + "ipsum").length

引用这本书(凭记忆,如果我错了,请纠正我:

当这发生在两个方向上时,它被命名为 Monoid isomorphisim,这意味着对于 monoidsM, N和函数f, gf andThen g并且g andThen fidentity函数。例如StringMonoid 和List[Char]具有连接的 Monoid 是同构的。

但是我看不到一个实际的例子,我只能认为是f函数length,但是会发生什么g

注意:我看过这个问题:What are isomorphism and homomorphisms

4

2 回答 2

5

要查看 和 之间的同构StringList[Char]我们有toList: String -> List[Char]mkString: List[Char] -> String

length是从 String 幺半群到加法的自然数幺半群的同态。

字符串幺半群的内同态的几个例子是toUpperCasetoLowerCase

对于列表,我们有很多同态,其中许多只是fold.

于 2019-09-11T11:48:04.830 回答
2

这是 siyopao 的答案,表示为 ScalaCheck 程序

object IsomorphismSpecification extends Properties("f and g") {
  val f: String => List[Char] = _.toList
  val g: List[Char] => String = _.mkString

  property("isomorphism") = forAll { (a: String, b: List[Char]) =>
    (f andThen g)(a) == a && (g andThen f)(b) == b
  }
}

哪个输出

+ f and g.isomorphism: OK, passed 100 tests.
于 2019-09-11T12:58:43.833 回答