I want to have a binary operator cross (cross-product/cartesian product) that operates with traversables in Scala:
val x = Seq(1, 2)
val y = Lis
Here is the implementation of recursive cross product of arbitrary number of lists:
def crossJoin[T](list: Traversable[Traversable[T]]): Traversable[Traversable[T]] =
list match {
case xs :: Nil => xs map (Traversable(_))
case x :: xs => for {
i <- x
j <- crossJoin(xs)
} yield Traversable(i) ++ j
}
crossJoin(
List(
List(3, "b"),
List(1, 8),
List(0, "f", 4.3)
)
)
res0: Traversable[Traversable[Any]] = List(List(3, 1, 0), List(3, 1, f), List(3, 1, 4.3), List(3, 8, 0), List(3, 8, f), List(3, 8, 4.3), List(b, 1, 0), List(b, 1, f), List(b, 1, 4.3), List(b, 8, 0), List(b, 8, f), List(b, 8, 4.3))