3
votes

If I have a method that has the following signature:

def max[T <% Ordered[T]](list:List[T]): T={ 
 //return max. element of List (for example)
}

and I want to give a list of pairs like this to it:

val fu:List[Pair[String, Double]] = List(Pair("a", 3.1),Pair("b", 1.7),Pair("c", 3.1),Pair("d", 5.4))

How do I define the ordering on the second element of the list, so I am able to work with it in the function?

I tried to use

implicit def wrapper(p: Pair[String, Double])=new runtime.RichDouble(p._2)

to implicitly convert the Double of the Pair to a RichDouble which extends the ordered trait, but that is not working.

2

2 Answers

6
votes

given:

scala> def max[T <% Ordered[T]](xs: List[T]) = xs.max
max: [T](xs: List[T])(implicit evidence$1: T => Ordered[T])T

scala> case class Pair(x: String, y: Double)
defined class Pair

You need to define ordering object for Pair:

scala> implicit val order = scala.math.Ordering.by[Pair, Double](_.y)
order: scala.math.Ordering[Pair] = scala.math.Ordering$$anon$7@3b2e9a90

Then you will find your max function working for Pairs

scala> max(List(Pair("foo", 1), Pair("bar", 2), Pair("baz", 2.2)))
res5: Pair = Pair(baz,2.2)
0
votes

why don't you use maxBy?

scala> val xs = ('c',3) :: ('a',1) :: ('b',2) :: Nil

scala> val x = xs maxBy(_._2)

//x == ('c',3)