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)
?
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.
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.
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.
In Scala 2.9, you can do list minBy { _._2 }
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With