I am trying to zip multiple sequences to form a long tuple:
val ints = List(1,2,3)
val chars = List('a', 'b', 'c')
val strings = List("Alpha", "Beta", "Gamma")
val bools = List(true, false, false)
ints zip chars zip strings zip bools
What I get:
List[(((Int, Char), String), Boolean)] =
List((((1,a),Alpha),true), (((2,b),Beta),false), (((3,c),Gamma),false))
However I would like to get a sequence of flat tuples:
List[(Int, Char, String, Boolean)] =
List((1,a,Alpha,true), (2,b,Beta,false), (3,c,Gamma,false))
I now I can do:
List(ints, chars, strings, bools).transpose
But it returns weakly typed List[List[Any]]. Also I can do (ints, chars, strings).zipped, but zipped works only on 2-tuples and 3-tuples.
Is there a way to zip (arbitrary) number of equal-length sequences easily?
Here’s one way to solve your example, but this is not for an arbitrary number of sequences.
I don’t think it is possible to do it generically for tuples of arbitrary length, at least not with this kind of solution. Tuples are strongly-typed, and the type system doesn’t allow you to specify a variable number of type parameters, as far as I know, which makes it impossible to make a generalized version of
f2andf3that takes a tuple of arbitrary length((A,B),C,D,...)(that would return a tuple(A,B,C,D,...)).If there were a way to specify a variable number of type parameters, we wouldn’t need traits
Tuple1,Tuple2, …Tuple22in Scala’s standard library.