I play with the QuickSort example at the beginning of Scala as an example and try to adapt it to a generic type A, not just Ints.
Still working for me
def sort[A <: Ordered[A]](xs: Array[A])
That allows you to sortrun on all types that are reflexively ordered, likeRichBoolean .
But that I would also like to allow types Awhere they extend Ordered[B], where B is the superclass of A (so, for example, everything that extends Ordered[Any]).
How can I say that?
What I actually got is thanks to agilesteel's answer :
case class X( i : Int ) extends Ordered[X] {
def compare( x : X ) = x.i - i
}
class Y( i : Int, j : Int ) extends X(i)
case class Z( i : Int ) extends Ordered[Any] {
def compare( a : Any ) : Int = {
if (! a.isInstanceOf[Z] )
sys.error("whoops")
val z = a.asInstanceOf[Z]
z.i - i
}
}
object QuickSort {
def main( args : Array[String] ) {
val xs = Array( 3, 1, 2, 4 ) map X
sort( xs );
val ys = Array( 3, 1, 2, 4 ) map { i => new Y(i, -i) }
sort[X,Y]( ys );
val zs = Array( 3, 1, 2, 4 ) map Z
sort[Any,Z]( zs );
}
def sort[B >: A, A <: Ordered[B]](xs: Array[A]) {
def swap(i: Int, j: Int) {
val t = xs(i); xs(i) = xs(j); xs(j) = t;
}
def sort1(l: Int, r: Int) {
val pivot = xs((l + r) / 2)
var i = 1; var j = r
while (i <= j) {
while (xs(i) < pivot) i += 1
while (xs(j) > pivot) j -= 1
if (i <= j) {
swap(i, j)
i += 1
j += 1
}
}
if (l < j) sort1(l, j)
if (j < r) sort1(i, r)
}
sort1(0, xs.length - 1)
}
}
, RichLong RichBoolean , Ordered ( Ordered[Long] Ordered[Boolean]).