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

前端 未结 6 1745
清酒与你
清酒与你 2020-12-09 18:38

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         


        
6条回答
  •  情书的邮戳
    2020-12-09 19:12

    In 2.8, you should be able to just do collection.sorted. sorted takes an implicit Ordering parameter. Any type that implements Ordered has a corresponding Ordering (thanks to the implicit conversion Ordering.ordered). There is also the implicit Ordering.Iterable that makes an Iterable[T] have an Ordering if T has an Ordering.

    However, if you try this it doesn't work:

    scala> def sort[A <: Ordered[A]](coll: List[List[A]]) = coll.sorted
    
    :5: error: could not find implicit value for parameter ord: Ordering[List[A]]
           def sort[A <: Ordered[A]](coll: List[List[A]]) = coll.sorted
                                                                 ^
    

    You need to explicitly specify that you want the Ordering[Iterable[A]]:

    def sort[A <: Ordered[A]](coll: List[List[A]]) = coll.sorted[Iterable[A]]
    

    I'm not sure why the compiler can't find the Ordering[Iterable[A]] if the element type of the collection is List[A].

提交回复
热议问题