对于以下代码,x<y
部分提示语法错误,我可以知道是否应该对其进行修改以启用比较?
class SortAlgo {
def insert[T](x:T, xs:List[T]): List[T]= xs match{
case Nil=> List(x)
case y::ys=>
if(x<y) x::xs
else y::insert(x,ys)
}
def isort[T:Comparable](xs:List[T]): List[T]=xs match{
case Nil => Nil
case x :: xs1 => insert(x, isort(xs1))
}
}
如果使用Ordering
,而不是Comparable
,则可以import
启用<
比较的必要隐含。
import Ordering.Implicits._
class SortAlgo[T: Ordering] {
def insert(x:T, xs:List[T]): List[T]= xs match {
case Nil=> List(x)
case y::ys=>
if(x<y) x::xs
else y::insert(x,ys)
}
def isort(xs:List[T]): List[T]=xs match {
case Nil => Nil
case x :: xs1 => insert(x, isort(xs1))
}
}
x
和 y
是类型T
,但没有任何表明T
具有<
方法。
两个选项:
1-要求T
扩展Ordered[T]
:
def insert[T <: Ordered[T]](x:T, xs:List[T]): List[T] = ...
2-提供了Ordering
:
def insert[T](x: T, xs: List[T])(ordering: Ordering[T]): List[T] = {
case Nil => List(x)
case y::ys =>
if (ordering.compare(x, y) < 0) => x::xs
else y::insert(x, ys)
}
您可能需要到 ordering
隐式,因此您可以创建隐式对象扩展Ordering[T]
。