Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort a collection of Lists in lexicographic order in Scala?

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.

like image 761
Scott Morrison Avatar asked Jun 29 '10 04:06

Scott Morrison


1 Answers

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.

like image 110
Carl Witty Avatar answered Sep 28 '22 03:09

Carl Witty