There is no analogous routine in the Standard Library, but you can get close:
scala> List(List(1,2,3),List(5,6,7),List(14,13,12)).transpose
res3: List[List[Int]] = List(List(1, 5, 14), List(2, 6, 13), List(3, 7, 12))
scala> List(List(1,2,3),List(5,6,7),List(14,13,12)).transpose.map(_.sum)
res4: List[Int] = List(20, 21, 22)
Note: transpose
requires all sub-collections have the same size.
Followup to your comment.
I'm not sure you understand what zipped
is. It transforms 2 sub-collections, inside a tuple (Tuple2
), into a single collection of tuples, each of which can then be given to a function that takes 2 parameters of the given types. This is also available for 3 sub-collections, inside a Tuple3
, becoming a collection of triples, but that's the limit.
Also, I don't know why you think "zipped
is one function call as opposed to two". If you follow the link Richard Scriven suggested in his comment, and compare the two solutions offered, you'll see that they have the same number of steps/statements.
As I see it, the advantages/disadvantages breakdown as follows:
- If you're dealing with collections of different types, say
Seq[Int]
and Seq[Char]
, then you'll want to get them zipped
before applying the "combiner" function to them: f(i1,c1)
then f(i2,c2)
then f(i3,c3)
etc.
- Neither approach handles sub-collections of different sizes well.
transpose
will throw an exception while zipped
simply ignores all elements beyond the max-index of the smallest sub-collection.
- If your "combiner" function takes more than three arguments then you can't use
zipped
.
- If your "combiner" takes a collection as input, then
transpose
is probably the better/easier option.