1

同様のタイプのタプルを比較する関数を作成しようとしています。

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

各タプルの 3 番目の要素または int にアクセスするにはどうすればよいですか?

ありがとう

4

2 に答える 2

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
}
于 2013-04-19T22:17:45.887 に答える
1

このユースケースをより一般的にするために、 (任意のサイズですが、ここでは を使用します)にmaxByメソッドを追加できます。TupleTuple3

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)
于 2013-04-30T14:38:21.917 に答える