dips dips - 1 year ago 71
Scala Question

cross product of arbitrary number of lists in scala

I have a list of lists in Scala as follows.

val inputList:List[List[Int]] = List(List(1, 2), List(3, 4, 5), List(1, 9))


I want a list of cross products of all the sub-lists.

val desiredOutput: List[List[Int]] = List(
List(1, 3, 1), List(1, 3, 9),
List(1, 4, 1), List(1, 4, 9),
List(1, 5, 1), List(1, 5, 9),
List(2, 3, 1), List(2, 3, 9),
List(2, 4, 1), List(2, 4, 9),
List(2, 5, 1), List(2, 5, 9))


The number of elements in inputList as well as the sublist are not fixed. What is the Scala way of doing this?

Answer Source

If you use scalaz, this may be a suitable case for Applicative Builder:

import scalaz._
import Scalaz._

def desiredOutput(input: List[List[Int]]) = 
  input.foldLeft(List(List.empty[Int]))((l, r) => (l |@| r)(_ :+ _))

desiredOutput(List(List(1, 2), List(3, 4, 5), List(1, 9)))

I am not very familiar with scalaz myself, and I expect it has some more powerful magic to do this.

Edit

As Travis Brown suggest, we just write

def desiredOutput(input: List[List[Int]]) = input.sequence

And I find the answers of this question very helpful for understanding what sequence does.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download