1

I am trying to write a function to compare tuples of similar type.

def compareTuples(tuple1: (String, String, Int), tuple2: (String, String, Int)): (String, String, Int) = {
   // if tuple1.Int < tuple2.Int return tuple1 else tuple2.
}

How do I access the third element or the int in each tuple?

Thanks

4

2 回答 2

5

To access a value in a tuple t, you can use t._1, t._2, etc.

For you that would then result in

def compareTuples(tuple1: (String, String, Int), tuple2: (String, String, Int)): (String, String, Int) = {
   if (tuple1._3 < tuple2._3) tuple1 else tuple2
}
于 2013-04-19T22:17:45.887 回答
1

To make this use case more generic, you can add a maxBy method to Tuple (of any size, but here we'll use Tuple3):

implicit class Tuple3Comparable[T1, T2, T3](t: (T1, T2, T3)) {
    type R = (T1, T2, T3)
    def maxBy[B](other: R)(f: R => B)(implicit ord: Ordering[B]): R = if(ord.lt(f(t), f(other))) other else t
}

Then you can make comparisons such as:

("z", "b", 3).maxBy(("c", "d", 10)) (_._3 ) // selects the second one, ("c", "d", 10)
("z", "b", 3).maxBy(("c", "d", 10)) (_._1 ) // selects the first one, ("z", "b", 3)
于 2013-04-30T14:38:21.917 回答