Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any methods included in Scala to convert tuples to lists?

Tags:

list

tuples

scala

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.

like image 204
pr1001 Avatar asked Dec 17 '09 01:12

pr1001


People also ask

Which method can be used to convert a tuple to a list?

To convert a tuple to list in Python, use the list() method. The list() is a built-in Python method that takes a tuple as an argument and returns the list. The list() takes sequence types and converts them to lists.

Can you turn tuples into lists?

We can use the list() function to convert tuple to list in Python. After writing the above code, Ones you will print ” my_tuple ” then the output will appear as a “ [10, 20, 30, 40, 50] ”. Here, the list() function will convert the tuple to the list.

What is the difference between list and tuple in Scala?

Lists are mutable(values can be changed) whereas tuples are immutable(values cannot be changed).


2 Answers

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).

like image 79
Mitch Blevins Avatar answered Oct 09 '22 12:10

Mitch Blevins


Using Shapeless -

@ import syntax.std.tuple._
import syntax.std.tuple._
@ (1,2,3).toList
res21: List[Int] = List(1, 2, 3)
@ (1,2,3,4,3,3,3,3,3,3,3).toList
res22: List[Int] = List(1, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3)

Note that type information is not lost using Shapeless's toList.

like image 37
Michael T Avatar answered Oct 09 '22 12:10

Michael T