I’ve occasionally found myself wanting a very simple Ordering[A] for a class which does not have an ordering yet. Usually the projection of a tuple or a field of a class. The following class seems to do this generically
case object Ord {
case class DerivedOrdering[A,B](fn : B=>A)(implicit o : Ordering[A]) extends Ordering[B] {
def compare(a:B, b:B) = o.compare(fn(a), fn(b))
}
}
I haven’t seen it in the scala library. Is it there somewhere?
Usage
Ord.DerivedOrdering[Int, (Int, List[Int])]( _._1)
Gives an ordering on (Int, List[Int]) ordering by the integer.
There is something you can do which is a method in the standard library
for example you can do the following:
Reuben