views:

199

answers:

1

I have a Tuple2 of List[List[String]] and I'd like to be able to convert the tuple to a list so that I can then use List.transpose(). Is there any way to do this? Also, I know it's a Pair, though I'm always a fan of generic solutions.

+7  A: 

Works with any tuple (scala 2.8):

myTuple.productIterator.toList

Scala 2.7:

(0 to (myTuple.productArity-1)).map(myTuple.productElement(_)).toList

Not sure how to maintain type info for a general Product or Tuple, but for Tuple2:

def tuple2ToList[T](t: (T,T)): List[T] = List(t._1, t._2)

You could, of course, define similar type-safe conversions for all the Tuples (up to 22).

Mitch Blevins
Looks good, though you need `myTuple.productArity - 1` and `productElement()` returns an `Any`. Is there any way to maintain the inner type information.
pr1001
Corrected indexing off-by-one and added type maintaining comment in answer.
Mitch Blevins
Thanks, looks good.
pr1001
productElements is deprecated, use myTuple.productIterator.toList instead
tommy chheng
Answer edited to reflect latest version per Tommy Chheng's comment.
Mitch Blevins