2013-05-04 59 views
1

作爲練習,我應該實現一個特性PartialOrdered [T]。實現特質PartialOrdered [T]

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

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

擴展這一性狀A 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) 
                 ^

所以我缺少什麼?由於事先

編輯:這是一個示例類矩形(在座標系統中),具有兩個相對的角部給出的,其中,一個矩形低於另一如果它被完全包含

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) = {...} 
} 

回答

2

你必須告訴斯卡拉說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

+0

這確實奏效,但超出了我之前學過的東西。我曾嘗試過類似的東西,它不適用於使用'<%'而不是'<:''this:T =>'的目的是什麼? – marius 2013-05-04 15:25:12

0

T不必然是PartialOrdered[T]的一個實例,所以它沒有下面的方法。我想你的意思是

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

+0

我試過了,編譯會要求在Rectangle類中'below'的正確實現。但是隻想比較矩形和矩形。 – marius 2013-05-04 15:02:47

+0

然後看到Debilski的回答。 – Cubic 2013-05-04 15:20:16

1

您這裏需要兩個概念。一個是F-bound多態,另一個是自我類型約束。

F-bound多態性,沒有深入底層類型理論,實質上是二元操作符的工作原理。基本上,你定義一個特徵有它的參數是自身的亞型:

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)) 
} 
相關問題