Make42
Make42

Reputation: 13088

Reduce by inspecting tuple element

I want to find the Tuple with the largest second element:

mylist.reduce { (x, y) => {
  if (y._1 > x._1) y
  else x
}}

Where x and y are of type Tuple3[DenseVector[Int], Double, PipelineModel].

  1. I get the error that > cannot be resolved. What's up with that? Using foldLeft and providing a zero element did not help either.

  2. Can I write the code nicer? (It doesn't look so nice, I think.)

Upvotes: 1

Views: 495

Answers (1)

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

In a triplet (a, b, c) triplet._2 gives you the second element.

_1 gives first element

_2 gives second element

_3 gives third element

Tuples are not zero based.

scala> val triplet = (1, 2, 3)
triplet: (Int, Int, Int) = (1,2,3)

scala> triplet._1
res0: Int = 1

scala> triplet._2
res1: Int = 2

scala> triplet._3
res2: Int = 3

Answer 1:

In your case triplet._1 gives the first element of the triplet (tuple3) which is DenseVector[Int] element on which you cannot use >. Thats why > is not resolved.

Answer 2:

maxBy

l.maxBy(_._2)

Scala REPL

scala> val l = List((1, 2, 3), (0, 0, 1))
l: List[(Int, Int, Int)] = List((1,2,3), (0,0,1))

scala> l.maxBy(_._2)
res1: (Int, Int, Int) = (1,2,3)

Reduce

l.reduce { (x, y) =>  if (x._2 > y._2) x else y }

Scala REPL

scala> val l = List((1, 2, 3), (0, 0, 1))
l: List[(Int, Int, Int)] = List((1,2,3), (0,0,1))

scala> l.reduce { (x, y) =>  if (x._2 > y._2) x else y }
res3: (Int, Int, Int) = (1,2,3)

Upvotes: 2

Related Questions