Scala method to combine each element of an iterable with each element of another?

Geo picture Geo · May 10, 2011 · Viewed 7.3k times · Source

If I have this:

val a = Array("a ","b ","c ")
val b = Array("x","y")

I would like to know if such a method exists which would let me traverse the first collection, and for each of it's elements, walk the entire second collection. For example, if we take the array a, we would have a,x,a,y,b,x,b,y,c,x,c,y. I know of zip but from what I've seen it only works on collections of the same sizes, and it associates elements from same positions.

Answer

user166390 picture user166390 · May 10, 2011

I'm not sure of a "method", but this can be expressed with just a nested/compound for:

val a = Array("a ","b ","c ")
val b = Array("x","y")
for (a_ <- a; b_ <- b) yield (a_, b_)

res0: Array[(java.lang.String, java.lang.String)] = Array((a ,x), (a ,y), (b ,x), (b ,y), (c ,x), (c ,y))

Happy coding.