title: Scala SortedSet - sorted by one Ordering and unique by something else?
body: <p>Say I have a set of Strings that I want to be ordered by length but unique by the normal <code>String</code> uniqueness. What I mean is that I that I could have more than one String of same length in the <code>Set</code>, but that they should be sorted by length.</p>
  
  <p>I want to express the ordering like this:</p>
  
  <pre><code>val orderByLength = Ordering[Int].on[String](_ length)
  </code></pre>
  
  <p>which I think looks really nice. But if I were to throw this into a SortedSet, say like this:</p>
  
  <pre><code>scala&gt; val s = SortedSet("foo", "bar")(orderByLength)
  s: scala.collection.immutable.SortedSet[java.lang.String] = TreeSet(bar)
  </code></pre>
  
  <p>I only get 'bar'. This is because the <code>Ordering</code> represents a total ordering and so when <code>compare</code> returns 0 the elements are considered identical.</p>
  
  <p>Therefore I'm thinking I need to make a chained ordering and compare the Strings if the lengths are equal. To do this I used the "pimp my library"-pattern like this:</p>
  
  <pre><code>trait ChainableOrderings {
    class ChainableOrdering[T](val outer: Ordering[T]) {
      def ifEqual(next: Ordering[T]): Ordering[T] = new Ordering[T] {
        def compare(t1: T, t2: T) = {
          val first = outer.compare(t1, t2)
          if (first != 0) first else next.compare(t1, t2)
        }
      }
    }
    implicit def chainOrdering[T](o: Ordering[T]) = new ChainableOrdering[T](o)
  }
  </code></pre>
  
  <p>That I can use like:</p>
  
  <pre><code>val ordering = Ordering[Int].on[String](_ length) ifEqual Ordering[String]
  </code></pre>
  
  <p>I thought it looked really great, but then I realized that what I wanted to do was not really to order by the natural ordering of Strings, I just wanted ordering by size, but uniqueness by something else. Is this possible in a more elegant way?</p>