Francesco Borg
Francesco Borg

Reputation: 57

scala call tuple element with variable

I'm new to scala and I'm trying to figure out how tuple works. I'm trying to call the xth element of a tuplle where x is a variable but it seems not to work, how should I do?

for (x <- 1 to 2; j <- 0 to (N-1)) yield((j, index._x), (x-1,index._x))

In particular the index._x seem to not work

Upvotes: 0

Views: 91

Answers (1)

Dima
Dima

Reputation: 40500

It is possible to do this using the Product trait, though, as mentioned in the comment, this is not really a good idea or the intended way tuples are supposed to be used:

    val indexed = index.productIterator.toIndexedSeq
    for { 
      x <- 1 to 2
      j <- 0 until N
    } yield ((j, indexed(x-1)), (x-1, indexed(x-1))  

or better yet (get rid of indexed access, it's yuky):

   index.productIterator.take(2).toSeq.zipWithIndex
     .flatMap { case (value, index) => 
         (0 until N).map { j => ((j, value), (index, value)) }
     }

I'll say it again though: there is about 99% chance there is a better way to do what you are actually trying to do. Tuples are meant for grouping data, not iterating over it (use collections for that).

Upvotes: 1

Related Questions