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

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

    Just because I already implemented this another way, here is a non-recursive version that does not use return:

    new Ordering[Seq[String]]() {
      override def compare(x: Seq[String], y: Seq[String]): Int = {
        x.zip(y).foldLeft(None: Option[Int]){ case (r, (v, w)) =>
            if(r.isDefined){
              r
            } else {
              val comp = v.compareTo(w)
              if(comp == 0) None
              else Some(comp)
            }
          }.getOrElse(x.size.compareTo(y.size))
        }
      }
    

提交回复
热议问题