为什么对于任何给定的类型参数,只能有一个类型类的实现?

时间:2019-05-31 14:49:29

标签: scala functional-programming typeclass implicit

我正在阅读《凡人使用的FP》这本书,其中包含以下内容:

  

对于任何给定的类型参数,只有一个类型类的实现,该属性称为 typeclass coherence 。类型类从表面上看类似于上一章的代数接口,但是代数不必是连贯的。

我不完全理解本段。假设我们有以下类型类:

trait Ordering[T] {
  def compare(x: T, y: T): Int
}

我可以为Int类型创建两个实现,如下所示:

val ord1: Ordering[Int] = new Ordering[Int] {
  def compare(x: Int, y: Int): Int =
    if (x > y) 1 else if (x == y) 0 else -1
}

val ord2: Ordering[Int] = new Ordering[Int] {
  def compare(x: Int, y: Int): Int =
    if (x > y) -1 else if (x == y) 0 else 1
}

当作者说类型类只能有一个实现时,这是什么意思?它不适用于类型类的实例,因为我们可以为同一类型有多个实例。适用于什么?还有为什么ADT在这种意义上不连贯?

1 个答案:

答案 0 :(得分:3)

类型类的实例被定义为隐式的。

implicit val ord1: Ordering[Int] = new Ordering[Int] {
  def compare(x: Int, y: Int): Int =
    if (x > y) 1 else if (x == y) 0 else -1
}

implicit val ord2: Ordering[Int] = new Ordering[Int] {
  def compare(x: Int, y: Int): Int =
    if (x > y) -1 else if (x == y) 0 else 1
}

如果您问implicitly[Ordering[Int]],您将有

Error: ambiguous implicit values:
 both value ord1 in object App of type => App.Ordering[Int]
 and value ord2 in object App of type => App.Ordering[Int]
 match expected type App.Ordering[Int]