[英]Problem with sort in scala, got "Diverging implicit expansion ....." error. Sorting a list of tuples based on its first element but in reverse order
[英]diverging implicit expansion for type scala.math.Ordering
我很抱歉這個問題,但我無法從之前的問題中得到答案。 我有一個 Scala 課程
case class Problem (
ref: Ref,
v1: Option[String],
v2: Option[Int],
v3: Option[Int]
) extends Ordered[Problem] {
def v = ref.v
def compare(other: Problem) = {
import scalaz._
import Scalaz._
val v1Comp = ( v1 |@| other.v1 ) { case (r1, r2) => r1.compare(r2)}
val v2Comp = ( v2 |@| other.2 ) { case (sr1, sr2) => sr1.compare(sr2)}
val v3Comp = Some( v3.compare(other.v3) )
(v1Comp, v2Comp, v3Comp) match {
case (Some(v),_,_,_) if v!=0 => v
case (_,Some(v),_,_) if v!=0 => v
case (_,_,Some(v),_) if v!=0 => v
case _ => ref.v.compare(other.ref.v)
}
}
}
現在在另一堂課上,我有這樣的聲明:-
val probList = List(problem1, problem2).sorted
但是會引發編譯時問題:-
diverging implicit expansion for type Option[package.Problem] => Comparable[Option[package.Problem]]
調用 sorted 方法時。
我不明白的另一件事是相同的代碼適用於 Scala 2.10.x,但將其升級到 2.11.x 會導致此問題。
任何幫助或指導將不勝感激。 提前致謝
注意:- 類和變量的名稱略有變化,但結構保持完全相同
我想正確的是
case class Ref(
v: Int
)
case class Problem(
ref: Ref,
v1: Option[String],
v2: Option[Int],
v3: Option[Int]
) extends Ordered[Problem] {
def v = ref.v
def compare(other: Problem) = {
import scalaz._
import Scalaz._
val v1Comp = (v1 |@| other.v1) { case (r1, r2) => r1.compare(r2) }
val v2Comp = (v2 |@| other.v2) { case (r1, r2) => r1.compare(r2) }
val v3Comp = (v3 |@| other.v3) { case (r1, r2) => r1.compare(r2) }
(v1Comp, v2Comp, v3Comp) match {
case (Some(v), _, _) if v != 0 => v
case (_, Some(v), _) if v != 0 => v
case (_, _, Some(v)) if v != 0 => v
case _ => ref.v.compare(other.ref.v)
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.