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]] = ... // construct a list of lists of As
val sorted = collection sort { _ < _ }
and get something where the lists have been sorted in lexicographic order. Of course, just because A
has the trait Ordered[A]
doesn't mean that List[A]
has the trait Ordered[List[A]]
. Presumably, however, the 'scala way' to do this is with an implicit def.
How do I implicitly convert a List[A]
to a Ordered[List[A]]
, assuming A has the trait Ordered[A]
(so that the code above just works)?
I have in mind using the lexicographic ordering on List[A]
objects, but I'd like code that can be adapted to others orderings.
Inspired by Ben Lings' answer, I managed to work out what seems like the simplest way to sort lists lexicographically: add the line
import scala.math.Ordering.Implicits._
before doing your List[Int] comparison, to ensure that the implicit function infixOrderingOps
is in scope.