Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to inverse sort in scala?

Tags:

scala

What is the best way to do an inverse sort in scala? I imagine the following is somewhat slow.

list.sortBy(_.size).reverse 

Is there a conveinient way of using sortBy but getting a reverse sort? I would rather not need to use sortWith.

like image 284
schmmd Avatar asked Oct 18 '11 05:10

schmmd


People also ask

How do you sort in reverse order?

Sort in Descending order The sort() method accepts a reverse parameter as an optional argument. Setting reverse = True sorts the list in the descending order. Alternatively for sorted() , you can use the following code.

How do I sort a list in Scala?

Use the sortWith() Function to Sort List in Scala. We used the sortWith() function to take a lambda expression as an argument and return the sorted result. We can use this function to sort the list in ascending and descending order.


2 Answers

There may be the obvious way of changing the sign, if you sort by some numeric value

list.sortBy(- _.size) 

More generally, sorting may be done by method sorted with an implicit Ordering, which you may make explicit, and Ordering has a reverse (not the list reverse below) You can do

list.sorted(theOrdering.reverse) 

If the ordering you want to reverse is the implicit ordering, you can get it by implicitly[Ordering[A]] (A the type you're ordering on) or better Ordering[A]. That would be

list.sorted(Ordering[TheType].reverse) 

sortBy is like using Ordering.by, so you can do

list.sorted(Ordering.by(_.size).reverse) 

Maybe not the shortest to write (compared to minus) but intent is clear

Update

The last line does not work. To accept the _ in Ordering.by(_.size), the compiler needs to know on which type we are ordering, so that it may type the _. It may seems that would be the type of the element of the list, but this is not so, as the signature of sorted is def sorted[B >: A](ordering: Ordering[B]). The ordering may be on A, but also on any ancestor of A (you might use byHashCode : Ordering[Any] = Ordering.by(_.hashCode)). And indeed, the fact that list is covariant forces this signature. One can do

list.sorted(Ordering.by((_: TheType).size).reverse) 

but this is much less pleasant.

like image 122
Didier Dupont Avatar answered Oct 05 '22 18:10

Didier Dupont


list.sortBy(_.size)(Ordering[Int].reverse) 
like image 30
incrop Avatar answered Oct 05 '22 18:10

incrop