harika kotipalli
harika kotipalli

Reputation: 1

How to access second element in a Sequence in scala

val k = Seq((0,1),(1,2),(2,3),(3,4))
k: Seq[(Int, Int)] = List((0,1), (1,2), (2,3), (3,4))

If I have above statement and I need to do addition for even places and subtraction for odd places how can I access them? to be clear

Upvotes: 0

Views: 326

Answers (1)

zero323
zero323

Reputation: 330063

Do you mean something like this?

val transformed = k.grouped(2).flatMap{
  case Seq((i, x), (j, y)) => Seq((i, x + y), (j, x - y))
}

transformed.toList
// List[(Int, Int)] = List((0,3), (1,-1), (2,7), (3,-1))

Upvotes: 3

Related Questions