Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala, how to use Ordering[T] with List.min or List.max and keep code readable

Tags:

scala

In Scala 2.8, I had a need to call List.min and provide my own compare function to get the value based on the second element of a Tuple2. I had to write this kind of code:

val list = ("a", 5) :: ("b", 3) :: ("c", 2) :: Nil  list.min( new Ordering[Tuple2[String,Int]] {    def compare(x:Tuple2[String,Int],y:Tuple2[String,Int]): Int = x._2 compare y._2  } ) 

Is there a way to make this more readable or to create an Ordering out of an anonymous function like you can do with list.sortBy(_._2)?

like image 675
huynhjl Avatar asked Feb 03 '10 08:02

huynhjl


People also ask

Is list in Scala ordered?

In Scala we do not sort Lists in-place. They are immutable. But we use lambda expressions, and the Ordering type, to create sorted copies of these lists.

How do you find the largest number in an array in Scala?

The max() method is utilized to find the largest element of all the elements in the stated list. Return Type: It returns the largest of all the elements in the stated list.

Which of the following is a member of list in Scala?

Scala List Methods. head: This method returns the first element of the scala list. tail: This method returns all the elements except the first. isEmpty: This method checks if the list is empty in which case it returns True else False.


2 Answers

In Scala 2.9, you can do list minBy { _._2 }.

like image 153
missingfaktor Avatar answered Oct 11 '22 08:10

missingfaktor


C'mon guys, you made the poor questioner find "on" himself. Pretty shabby performance. You could shave a little further writing it like this:

list min Ordering[Int].on[(_,Int)](_._2) 

Which is still far too noisy but that's where we are at the moment.

like image 41
psp Avatar answered Oct 11 '22 08:10

psp