order - Scala SortedSet - sorted by one Ordering and unique by something else? -


say have set of strings want ordered length unique normal string uniqueness. mean i have more 1 string of same length in set, should sorted length.

i want express ordering this:

val orderbylength = ordering[int].on[string](_ length) 

which think looks nice. if throw sortedset, this:

scala> val s = sortedset("foo", "bar")(orderbylength) s: scala.collection.immutable.sortedset[java.lang.string] = treeset(bar) 

i 'bar'. because ordering represents total ordering , when compare returns 0 elements considered identical.

therefore i'm thinking need make chained ordering , compare strings if lengths equal. used "pimp library"-pattern 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 can use like:

val ordering = ordering[int].on[string](_ length) ifequal ordering[string] 

i thought looked great, realized wanted not order natural ordering of strings, wanted ordering size, uniqueness else. possible in more elegant way?

what in such situations this:

val orderbylength = ordering[(int, string)].on[string](s => s.length -> s) 

in other words, use tuple tie-breaker.

on other hand, think it's silly of sortedset consider elements same based on ordering. think has been discussed before, wouldn't discard possibility of searching mailing lists archives , scala trac discussions/tickets on this, , maybe trying sortedset change behavior.


Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -