0

Given an Ordering[Seq[String] like this:

new Ordering[Seq[String]]() {
  override def compare(x: Seq[String], y: Seq[String]): Int = {
    var i = 0
    while (i < Math.min(x.size, y.size)) {
      val c = x(i).compareTo(y(i))
      if (c != 0) return c
      i += 1
    }
    Integer.compare(x.size, y.size)
  }
}

This sorts a Seq[Seq[String]] according to the first String that differs from the comparing sequence - or according to the sequences size if there are no differing Strings.

While this implementation works well, I would like to have an implementation without any vars or returns but cannot wrap my head around how to implement such a (more functional) ordering.

Florian Baierl
  • 2,378
  • 3
  • 25
  • 50

1 Answers1

1

Looking at an older thread, lexicographic ordering of sequences of sequences is already provided by a standard implicit:

import scala.math.Ordering.Implicits._
Seq(
  Seq("a", "c"),
  Seq("a", "b"),
  Seq("a")
).sorted
// => List(List(a), List(a, b), List(a, c))
Thilo
  • 257,207
  • 101
  • 511
  • 656