为什么对于任何给定的类型参数只能有一个类型类的实现?
Why there can be only one implementation of a typeclass for any given type parameter?
我正在阅读 FP for Mortals 书,其中包含以下行:
There can only be one implementation of a typeclass for any given type parameter, a property known as typeclass coherence. Typeclasses look superficially similar to algebraic interfaces from the previous chapter, but algebras do not have to be coherent.
我没有完全理解这一段。假设我们有以下类型类:
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 在这个意义上不连贯?
类型 class 的实例被定义为隐式。
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]
我正在阅读 FP for Mortals 书,其中包含以下行:
There can only be one implementation of a typeclass for any given type parameter, a property known as typeclass coherence. Typeclasses look superficially similar to algebraic interfaces from the previous chapter, but algebras do not have to be coherent.
我没有完全理解这一段。假设我们有以下类型类:
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 在这个意义上不连贯?
类型 class 的实例被定义为隐式。
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]