How to make this recursive method tail recursive in Scala?

functional-programming, scala, tail-recursion

Solution

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.

import annotation.tailrec

def product[T](listOfLists: List[List[T]]): List[List[T]] = {
  @tailrec def innerProduct[T](listOfLists: List[List[T]], accum: List[List[T]]): List[List[T]] =
    listOfLists match {
      case Nil => accum
      case xs :: xss => innerProduct(xss, for (y <- xs; a <- accum) yield y :: a)
    }

  innerProduct(listOfLists.reverse, List(Nil))
}

Then:

scala> product(List(List(1,2),List(3,4)))
res0: List[List[Int]] = List(List(1, 3), List(1, 4), List(2, 3), List(2, 4))

Problem

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 } ```

Original source