Here's one way.
scala> case class Reverse[T](t: T)
defined class Reverse
scala> implicit def ReverseOrdering[T: Ordering]: Ordering[Reverse[T]]
= Ordering[T].reverse.on(_.t)
ReverseOrdering: [T](implicit evidence$1: Ordering[T])Ordering[Reverse[T]]
scala> ps.sortBy(p => (p.last, Reverse(p.first)))
res21: List[Person] = List(Person(Smith,Bob), Person(Smith,Bill))
-jason
Here's one way.
scala> case class Reverse[T](t: T)
defined class Reverse
scala> implicit def ReverseOrdering[T: Ordering]: Ordering[Reverse[T]]
= Ordering[T].reverse.on(_.t)
ReverseOrdering: [T](implicit evidence$1: Ordering[T])Ordering[Reverse[T]]
scala> ps.sortBy(p => (p.last, Reverse(p.first)))
res21: List[Person] = List(Person(Smith,Bob), Person(Smith,Bill))
scala> case class Person(last: String, first: String)
defined class Person
scala> val ps = List(Person("Smith", "Bob"), Person("Smith", "Bill"))
ps: List[Person] = List(Person(Smith,Bob), Person(Smith,Bill))
scala> ps.sortBy(p => (p.last, p.first))
res15: List[Person] = List(Person(Smith,Bill), Person(Smith,Bob))
scala> implicit val o = Ordering.by((p: Person) => (p.last, p.first))
o: scala.math.Ordering[Person] = scala.math.Ordering$$anon$6@6aa27760
scala> ps.sorted
res16: List[Person] = List(Person(Smith,Bill), Person(Smith,Bob))
scala> implicit val o = Ordering.by((p: Person) => (p.last, p.first))
Darnit. Why didn't I think of that?
Now I can throw away this code:
def multiSort[T](xs: Seq[T])(orderings: Ordering[T]*) =
xs.sorted(orderings.reduceLeft(combine))
def combine[T](o1: Ordering[T], o2: Ordering[T]) = new Ordering[T] {
def compare(x: T, y: T) =
o1.compare(x, y) match {
case 0 => o2.compare(x, y)
case n => n
}
}
multiSort(people)(Ordering.by(_.last),
Ordering.by(_.first),
--
Seth Tisue @ Northwestern University | http://tisue.net
lead developer, NetLogo: http://ccl.northwestern.edu/netlogo/
-- Jim
Not really; the test grows linearly if coded as:
items.sortWith { case(a,b) =>
if( a.k1 < b.k1 ) true
else if( a.k1 > b.k1 ) false
else if( a.k2 < b.k2 ) true
else if( a.k2 > b.k2 ) false
else a.k3 < b.k3
}
-- Jim
-- Jim