Suppose list1 = [1, 2, 3]
and list2 = ["a", "b"]
I want to combine them such that I get a tuple list like so:
list3 = [(1, "a"), (1, "b"), (2, "a"), (2, "b"), (3, "a"), (3, "b")]
Is there any way to do this concisely?
You can do it fairly easily with Scala's for ... yield
expression.
for {
x <- list1
y <- list2
} yield {
(x, y)
}
This desugars to flatMap
and map
calls, so it's equivalent to
list1.flatMap { x => list2.map { y => (x, y) } }
If you're using Scalaz, then the Cartesian product is just an application of the Applicative
instance for lists. With appropriate Scalaz imports, this will suffice
^(list1, list2) { (_, _) }
cats has similar functionality with different syntax:
import cats.syntax.all._
(list1, list2).tupled