scala - Beginner: How do I say "any superclass of generic A" -
scala - Beginner: How do I say "any superclass of generic A" -
i'm playing quicksort illustration @ start of scala example , trying adapt generic type a
, rather int
s.
what i've got working far is
def sort[a <: ordered[a]](xs: array[a])
which allows sort
run on types reflexively ordered, like richboolean
.
but i'd allow types a
extend ordered[b]
b superclass of (so, instance, extends ordered[any]
).
how can this?
what got work, agilesteel's answer:
case class x( : int ) extends ordered[x] { def compare( x : x ) = x.i - } class y( : int, j : int ) extends x(i) case class z( : int ) extends ordered[any] { def compare( : ) : int = { if (! a.isinstanceof[z] ) sys.error("whoops") val z = a.asinstanceof[z] z.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 { => 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, <: 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 = 1; var j = r while (i <= j) { while (xs(i) < pivot) += 1 while (xs(j) > pivot) j -= 1 if (i <= j) { swap(i, j) += 1 j += 1 } } if (l < j) sort1(l, j) if (j < r) sort1(i, r) } sort1(0, xs.length - 1) } }
i misled trying utilize richlong
, richboolean
test types, since aren't actuallly reflexively ordered
(they extend ordered[long]
, ordered[boolean]
instead).
something this?
def sort[b >: a, <: ordered[b]](xs: array[b])
generics scala
Comments
Post a Comment