I found a function for creating a cartesian product from a list of lists in Scala. However, it isn’t tail recursive and won’t work well with large lists. Unfortunately I won’t know at design time how many lists I will need to combine, so I believe a recursive function is necessary. I’m struggling to make it tail recursive so it can be optimized by the compiler:
def product[T](listOfLists: List[List[T]]): List[List[T]] = listOfLists match {
case Nil => List(List())
case xs :: xss => for (y <- xs; ys <- product(xss)) yield y :: ys
}
This approach is similar to your original method except that instead of starting and the front and recursively descending until you get to the end and appending back up, I’ve introduced an accumulator to that I can just march through the list backwards, accumulating as I go.
Then: