![](/img/trans.png)
[英]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.