Scala SortedSet - sorted by one Ordering and unique by something else?
Say I have a set of Strings that I want to开发者_Go百科 be ordered by length but unique by the normal String
uniqueness. What I mean is that I that I could have more than one String of same length in the Set
, but that they should be sorted by length.
I want to express the ordering like this:
val orderByLength = Ordering[Int].on[String](_ length)
which I think looks really nice. But if I were to throw this into a SortedSet, say like this:
scala> val s = SortedSet("foo", "bar")(orderByLength)
s: scala.collection.immutable.SortedSet[java.lang.String] = TreeSet(bar)
I only get 'bar'. This is because the Ordering
represents a total ordering and so when compare
returns 0 the elements are considered identical.
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:
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)
}
That I can use like:
val ordering = Ordering[Int].on[String](_ length) ifEqual Ordering[String]
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?
What I do in such situations is this:
val orderByLength = Ordering[(Int, String)].on[String](s => s.length -> s)
In other words, use a tuple to get a tie-breaker.
On the other hand, I think it's silly of SortedSet
to consider elements the same based on their ordering. I think this has been discussed before, but I wouldn't discard the possibility of searching mailing lists archives and the scala trac for discussions/tickets on this, and maybe trying to get SortedSet
to change its behavior.
精彩评论