2016-01-12 101 views
0

我正在使用horstmann的書「Scala for impatient」來學習scala。在Scala中提供隱式轉換函數作爲參數

作者提出了一個練習來定義一個函數Fraction => Ordered [Fraction],並在調用中提供它,或使其可用作爲含蓄 val。

這是我在Scala工作表中實現的完整代碼。

case class Fraction (n:Int,d:Int) { 
     def *(that: Fraction):Fraction = new Fraction(n * that.n , d * that.d) 
    } 

def smaller[T](a:T,b:T)(implicit order:T => Ordered[T]) = { 
    if(a<b) a else b 
} 

implicit def compareFraction(a:Fraction,b:Fraction) ={ 
    if(a.n * b.d > a.d * b.n) a else b 
    } 

smaller(Fraction(4,5),Fraction(4,6)) (compareFraction) 

較小的函數在調用2個Fraction參數時拋出錯誤。

的錯誤是

Type mismatch, expected:(Fraction) => Ordered[Fraction], actual:(Fraction,Fraction) => Ordered. 

我創造一個函數,它接受單一的分數作爲參數,並轉化成相同有序[率]來襲。

任何人都可以幫助我實現下面兩種方式相同。

  1. 定義一個函數分數=>有序[率]和任一呼叫中的供給它

  2. 使其可作爲 VAL。

在此先感謝。

回答

0

我相信你想要的東西是這樣的:

case class Fraction (n:Int,d:Int) { 
    def *(that: Fraction):Fraction = new Fraction(n * that.n , d * that.d) 
} 

def smaller[T](a:T,b:T)(implicit order:T => Ordered[T]) = { 
    if(a<b) a else b 
} 

implicit def fractionToOrdered(fraction: Fraction):Ordered[Fraction] = new Ordered[Fraction] { 
    override def compare(that: Fraction): Int = ??? 
} 

smaller[Fraction](Fraction(4,5),Fraction(4,6)) 
+0

請您提供實施也比較方法。 –