Algorithm 如何定义在Scala中接受有序[T]数组的方法?
我正在用Scala构建一些基本算法(遵循Cormen的书)来更新我对这个主题的认识,我正在构建插入排序算法。这样做,它可以正常工作:Algorithm 如何定义在Scala中接受有序[T]数组的方法?,algorithm,generics,scala,Algorithm,Generics,Scala,我正在用Scala构建一些基本算法(遵循Cormen的书)来更新我对这个主题的认识,我正在构建插入排序算法。这样做,它可以正常工作: class InsertionSort extends Sort { def sort ( items : Array[Int] ) : Unit = { if ( items.length < 2 ) { throw new IllegalArgumentException( "Array must be bigger than
class InsertionSort extends Sort {
def sort ( items : Array[Int] ) : Unit = {
if ( items.length < 2 ) {
throw new IllegalArgumentException( "Array must be bigger than 1" )
}
1.until( items.length ).foreach( ( currentIndex ) => {
val key = items(currentIndex)
var loopIndex = currentIndex - 1
while ( loopIndex > -1 && items(loopIndex) > key ) {
items.update( loopIndex + 1, items(loopIndex) )
loopIndex -= 1
}
items.update( loopIndex + 1, key )
} )
}
}
以下规范未编译:
"sort correctly with merge sort" in {
val items = Array[RichInt](5, 2, 4, 6, 1, 3)
insertionSort.sort( items )
items.toList === Array[RichInt]( 1, 2, 3, 4, 5, 6 ).toList
}
编译器错误是:
Type mismatch, expected: Array[Ordered[_]], actual Array[RichInt]
但是RichInt不是一个有序的[RichInt]吗?我应该如何定义这个方法签名,使它能够接受任何有序对象
编辑
如果有人感兴趣,最终的源代码是可用的。实际上
RichInt
不是有序的[RichInt]
,而是有序的[Int]
。但是scala.runtime.RichInt def[T有序[T])布尔值
scala>f(数组(1,2,3))
res2:Boolean=true
斯卡拉>
您可以使用类型参数上的
scala> def foo[T : Ordering](arr: Array[T]) = {
| import math.Ordering.Implicits._
| arr(0) < arr(1)
| }
foo: [T](arr: Array[T])(implicit evidence$1: Ordering[T])Boolean
这样做的好处是,如果不需要,则不需要类型的默认顺序:
scala> foo(Array("z", "bc"))
res4: Boolean = false
scala> foo(Array("z", "bc"))(Ordering.by(_.length))
res3: Boolean = true
scala> def foo[T : Ordering](arr: Array[T]) = {
| import math.Ordering.Implicits._
| arr(0) < arr(1)
| }
foo: [T](arr: Array[T])(implicit evidence$1: Ordering[T])Boolean
scala> foo(Array(2.3, 3.4))
res1: Boolean = true
scala> foo(Array("z", "bc"))
res4: Boolean = false
scala> foo(Array("z", "bc"))(Ordering.by(_.length))
res3: Boolean = true