我想比较两个元组

时间:2013-04-19 22:07:08

标签: scala pattern-matching tuples

我正在尝试编写一个函数来比较相似类型的元组。

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

如何访问每个元组中的第三个元素或int?

由于

2 个答案:

答案 0 :(得分:5)

要访问元组t中的值,您可以使用t._1t._2等。

对你而言会导致

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

答案 1 :(得分:1)

为了使这个用例更通用,您可以将maxBy方法添加到Tuple(任意大小,但我们将使用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
}

然后你可以进行比较,例如:

("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)