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

前端 未结 6 1726
清酒与你
清酒与你 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:26

    (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 Ints to RichInts, which in particular are Ordered[Int]s.

    The rest of the code is just implementing lexicographic ordering.

提交回复
热议问题