比较提示语法错误

时间:2016-12-10 02:58:32

标签: scala

对于以下代码,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))
}

}

2 个答案:

答案 0 :(得分:2)

如果您使用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)) } } 比较所需的隐含权。

{% macro directive(name, value) %}
{% if value is defined %}
{{ name }}={{ value }} # a newline hardcoded in macro follows
{% endif %}
{% endmacro -%}

# {{ ansible_managed }}

[Unit 1]
{{ directive('Description', service.description) }}# 1st hardcoded newline follows
{{ directive('Documentation', service.documentation) }}# 2nd hardcoded newline follows
{{ directive('Requires', service.requires) }}# 3rd hardcoded newline follows

答案 1 :(得分:2)

xy属于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]的隐式对象。