【问题标题】:I am trying to compare two Tuples我正在尝试比较两个元组
【发布时间】:2013-04-13 09:53:58
【问题描述】:

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

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

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

谢谢

【问题讨论】:

标签: scala pattern-matching tuples


【解决方案1】:

要访问元组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
}

【讨论】:

    【解决方案2】:

    为了使这个用例更通用,您可以将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)
    

    【讨论】:

      猜你喜欢
      • 2023-01-17
      • 1970-01-01
      • 1970-01-01
      • 2017-04-14
      • 2017-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-19
      相关资源
      最近更新 更多