If A
has the Ordered[A]
trait, I\'d like to be able to have code that works like this
val collection: List[List[A]] = ... // constr
(11 minutes ago I actually didn't know how to do this, I hope it's considered okay to answer my own question.)
implicit def List2OrderedList[A <% Ordered[A]](list1: List[A]): Ordered[List[A]] = {
new Ordered[List[A]] {
def compare(list2: List[A]): Int = {
for((x,y) <- list1 zip list2) {
val c = x compare y
if(c != 0) return c
}
return list1.size - list2.size
}
}
}
An important thing to note here is the 'view bound' A <% Ordered[A]
, which ensures that A
needn't itself by an Ordered[A]
, just that there's a way to do this conversion. Happily, the Scala library's object Predef
has an implicit conversion from Int
s to RichInt
s, which in particular are Ordered[Int]
s.
The rest of the code is just implementing lexicographic ordering.