实现特征PartialOrdered [T]

时间:2013-05-04 14:13:30

标签: scala traits partial-ordering

作为练习,我应该实现一个特质PartialOrdered [T]。

trait PartialOrdered[T] {
  def below(that: T): Boolean
  def < (that: T): Boolean = (this below that) && !(that below this)  

  /* followed by other relations <=, >, >=, ==, .. */
}

扩展此特征的K类应该在下面实现

a.below(b: K) = { true   if a <= b, 
                  false  in any other case

但是,编译会出现以下错误:

value below is not a member of type parameter T
def < (that: T): Boolean = (this below that) && !(that below this)
                                                        ^

那我错过了什么?提前致谢

编辑:这是一个示例类Rectangle(在坐标系中),给出了两个相对的角,如果完全包含矩形,则矩形在另一个下面

case class Rectangle (x1: Int, y1: Int, x2: Int, y2: Int) 
  extends PartialOrdered[Rectangle] {

  def below(r: Rectangle): Boolean = {
    val (rx, ry) = r.topLeft
    val (tx, ty) = this.topLeft
    tx >= rx && ty <= ry &&
    tx + this.width <= rx + r.width &&
    ty - this.height >= ry - r.height
  }

  def width: Int = {...}
  def height: Int = {...}
  def topLeft:(Int, Int) = {...}
}

3 个答案:

答案 0 :(得分:2)

您必须告诉Scala TPartialOrdered[T]的子类型:

trait PartialOrdered[T <: PartialOrdered[T]] { this: T =>
  def below(that: T): Boolean
  def < (that: T): Boolean = (this below that) && !(that below this)  

  /* followed by other relations <=, >, >=, ==, .. */
}

另请参阅:scala self-type: value is not a member error

答案 1 :(得分:1)

这里需要两个概念。一个是F-有界多态,另一个是自我类型约束。

F-bounded多态,没有进入基础类型理论,本质上是使二元运算符起作用的原因。您基本上定义了一个特征,使其参数成为其自身的子类型:

trait PartialOrdered[T <: PartialOrdered[T]] {
  this: T =>
    def below(that: T): Boolean
    def <(that: T): Boolean =
      (this below that) && !(that below this)
}

不仅要this below that工作,还要that below this,我们还需要约束自我类型。这是通过this: T =>完成的,因此编译器知道this也是T的实例,而不仅仅是PartialOrdered[T]

然后定义一个类来使用该特征。它需要将自身扩展为类型参数:

case class Pair(x: Double, y: Double) extends PartialOrdered[Pair] {
  def below(that: Pair) =
    x <= that.x && y <= that.y
}

object Program extends App {
  println(Pair(1, 2) < Pair(2, 0))
  println(Pair(1, 2) < Pair(1, 3))
  println(Pair(1, 2) < Pair(0, 2))
  println(Pair(1, 2) < Pair(2, 2))
}

答案 2 :(得分:0)

T不一定是PartialOrdered[T]的实例,因此它没有以下方法。我想你的意思是

  def below(that: PartialOrdered[T]): Boolean
  def < (that: PartialOrdered[T]): Boolean = (this below that) && !(that below this)