score:30
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.
score:3
You could always define your own implicit conversion:
implicit def funToOrdering[T,R <% Ordered[R]](f: T => R) = new Ordering[T] {
def compare(x: T, y: T) = f(x) compare f(y)
}
val list = ("a", 5) :: ("b", 3) :: ("c", 2) :: Nil
list.min { t: (String,Int) => t._2 } // (c, 2)
EDIT: Per @Dario's comments.
Might be more readable if the conversion wasn't implicit, but using an "on" function:
def on[T,R <% Ordered[R]](f: T => R) = new Ordering[T] {
def compare(x: T, y: T) = f(x) compare f(y)
}
val list = ("a", 5) :: ("b", 3) :: ("c", 2) :: Nil
list.min( on { t: (String,Int) => t._2 } ) // (c, 2)
score:5
list.min(Ordering.fromLessThan[(String, Int)](_._2 < _._2))
Which is still too verbose, of course. I'd probably declare it as a val
or object
.
score:8
The function Ordering#on
witnesses the fact that Ordering
is a contra-variant functor. Others include Comparator
, Function1
, Comparable
and scalaz.Equal
.
Scalaz provides a unified view on these types, so for any of them you can adapt the input with value contramap f
, or with symbolic denotation, value ∙ f
scala> import scalaz._
import scalaz._
scala> import Scalaz._
import Scalaz._
scala> val ordering = implicitly[scala.Ordering[Int]] ∙ {x: (_, Int) => x._2}
ordering: scala.math.Ordering[Tuple2[_, Int]] = scala.math.Ordering$$anon$2@34df289d
scala> List(("1", 1), ("2", 2)) min ordering
res2: (java.lang.String, Int) = (1,1)
Here's the conversion from the Ordering[Int]
to Ordering[(_, Int)]
in more detail:
scala> scalaz.Scalaz.maContravariantImplicit[Ordering, Int](Ordering.Int).contramap { x: (_, Int) => x._2 }
res8: scala.math.Ordering[Tuple2[_, Int]] = scala.math.Ordering$$anon$2@4fa666bf
score:10
One thing you can do is use the more concise standard tuple type syntax instead of using Tuple2
:
val min = list.min(new Ordering[(String, Int)] {
def compare(x: (String, Int), y: (String, Int)): Int = x._2 compare y._2
})
Or use reduceLeft
to have a more concise solution altogether:
val min = list.reduceLeft((a, b) => (if (a._2 < b._2) a else b))
Or you could sort the list by your criterion and get the first
element (or last
for the max):
val min = list.sort( (a, b) => a._2 < b._2 ).first
Which can be further shortened using the placeholder syntax:
val min = list.sort( _._2 < _._2 ).first
Which, as you wrote yourself, can be shortened to:
val min = list.sortBy( _._2 ).first
But as you suggested sortBy
yourself, I'm not sure if you are looking for something different here.
score:40
In Scala 2.9, you can do list minBy { _._2 }
.
Source: stackoverflow.com
Related Query
- In Scala, how to use Ordering[T] with List.min or List.max and keep code readable
- How do I use scala and scalatest to see if a list contains an object with a field matching a specific value
- How to use scala list and java list in the same file in scala code base?
- How to use IntelliJ with Play Framework and Scala
- How can I use a combination of Scala, Groovy, and Java code with Gradle?
- How to use play-plugins-mailer with Play 2.3 and Scala 2.11?
- How do I create horizontal or vertical struts and glue for use with scala BoxPanel?
- Value and column operations in scala spark, how to use a value left of an operator with spark column?
- How to convert a List to RDD with scala and spark
- How to parse a string with filter criteria in scala and use it to filter objects
- How do I abstract over effects and use ContextShift with Scala Cats?
- How to find an element in a list based on a condition and return some data associated with that element in Scala
- scala TreeMap - how to get indexOf and element to use with slice or view method
- How to use scala and html code inside single block
- How can I use the Scala REPL to test java code - java and scala REPL giving different outputs
- How to use getOrElse with Map and compare value in scala
- how should I optimise the scala code and make it more readable
- How to define case class with a list of tuples and access the tuples in scala
- How can I use scala sources from a different location in a sbt project and also make it work with IntelliJ IDEA?
- How to use the Akka sample cluster kubernetes with Scala and minikube?
- scala how to use pattern matching with inheriance and templated class
- how to avaoid circular dependency exception in spark scala and make code run with cyclic dependency
- How to generate a list with xml element as key and xml as value in scala
- scala spark sql with intellij, how to link jdbc jar file and run the scala code
- How to use cdn url with play framework and scala for image display?
- How to find max and min with single aggregate function in spark RDD?
- is there a way to write coalesce query to remove null from a file and use in scala code with a filter after extracting from a file?
- What's the standard way to work with dates and times in Scala? Should I use Java types or there are native Scala alternatives?
- Debugging Scala code with simple-build-tool (sbt) and IntelliJ
- How to use third party libraries with Scala REPL?
More Query from same tag
- How do I change universal zip file name using sbt-native-packager
- Error while installing PlayFramework
- scala flatMap or filter which one is cheaper
- Akka mapTo versus asInstanceOf
- Get case class and JSON object from a hierarchical JSON map with lift-json
- Parsing a JSArray object into a list of objects in Scala Play
- How to get the class of Option[_] on a None with Reflection
- SBT local Maven repository dependency
- transactions and conditional update in Jooq with scala
- Scala: not a legal formal parameter
- scala not on path after installing typesafe-stack on Ubuntu
- Use function parameter as annotation argument in Scala 2.11.x: annotation argument needs to be a constant
- replace string variable in Scala for solution
- scala unapply that returns boolean
- scala @switch annotation, does it make any difference to generated byte code?
- overriding equals method in AnyRef class not working
- Implementation of ALS in Spark
- Let build.sbt define dependency on another local library
- Json4s: Trouble while trying to convert Json attribute to java.sql.Date
- Use singletons in akka scala actor
- How to make stateful API's pure
- why can not overload no argument method ,for implicit class
- How to use Pattern Matching where clause in Flink?
- Convert a List into an Option if it is populated
- post and pre increment not working as expected for REPL variable in scala
- How pyspark integrates with java?
- Type variance error in Scala when doing a foldLeft over Traversable views
- Spark Dataset : Example : Unable to generate an encoder issue
- Scala type erasure issue with path dependent/nested types
- Get most recently inserted primary key slick