我在Scala中有一个列表列表,如下所示。
val inputList:List[List[Int]] = List(List(1, 2), List(3, 4, 5), List(1, 9))
我想要所有子列表的交叉产品列表。
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))
inputList以及子列表中的元素数量不是固定的。 Scala这样做的方式是什么?
最佳答案
如果您使用scalaz
,这可能是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)))
我自己对scalaz不太熟悉,并且我希望它具有一些更强大的功能。
编辑
正如特拉维斯·布朗(Travis Brown)所说,我们只是写
def desiredOutput(input: List[List[Int]]) = input.sequence
而且我发现this question的答案对于理解
sequence
的作用非常有帮助。