toString on sorted sets

I’ve picked this up again after a bit of a break so am a bit rusty. This problem seems a trivial one.

With my custom set show method:

implicit def myShowForSet[A: Show]: Show[Set[A]] = new Show[Set[A]] {
  def show(xs: Set[A]): String = {
    xs match {
      case ss: SortedSet[A] => 
        println(ss)
        ss.map(_.show).mkString(green("{"),green(", "),green("}"))
      case _  => xs.map(_.show).mkString(red("{"), red(", "), red("}"))
    }
  }
}

if I call it on a SortedSet of integers, since it recursively maps show on the sets elements, I think it reconstructs a new SortedSet but orders according to string ordering rather than integer ordering?

TreeSet(100, 200, 300, 400, 500, 600, 700, 800, 900, 1000)
res4: String = {100, 1000, 200, 300, 400, 500, 600, 700, 800, 900}

Is this fixable?

I think I would do set.iterator.map(...).mkString(...).

3 Likes

That works - thanks.