对于未知数量的列表,不同长度的列表,以及可能不同的类型,你可以使用这个:
def xproduct (xx: List [List[_]]) : List [List[_]] =
xx match {
case aa :: bb :: Nil =>
aa.map (a => bb.map (b => List (a, b))).flatten
case aa :: bb :: cc =>
xproduct (bb :: cc).map (li => aa.map (a => a :: li)).flatten
case _ => xx
}
你会这样称呼它
xproduct List (List ("a ", "b ", "c "), List ("x", "y"))
但也可以使用不同类型的列表来调用它:
scala> xproduct (List (List ("Beatles", "Stones"), List (8, 9, 10), List ('$', '€')))
res146: List[List[_]] = List(List(Beatles, 8, $), List(Stones, 8, $), List(Beatles, 8, €), List(Stones, 8, €), List(Beatles, 9, $), List(Stones, 9, $), List(Beatles, 9, €), List(Stones, 9, €), List(Beatles, 10, $), List(Stones, 10, $), List(Beatles, 10, €), List(Stones, 10, €))
如果不能使用列表,则必须将数组转换为列表,并将结果转换回数组。
更新:
在走向惰性集合的过程中,我做了一个从索引(从 0 到组合大小 - 1)到该位置结果的函数映射,很容易用模和除法计算,只需要一点注意力:
def combicount (xx: List [List[_]]): Int = (1 /: xx) (_ * _.length)
def combination (xx: List [List[_]], i: Int): List[_] = xx match {
case Nil => Nil
case x :: xs => x(i % x.length) :: combination (xs, i / x.length)
}
def xproduct (xx: List [List[_]]): List [List[_]] =
(0 until combicount (xx)).toList.map (i => combination (xx, i))
用 long 代替,甚至 BigInt 都没问题。
更新2,迭代器:
class Cartesian (val ll: List[List[_]]) extends Iterator [List[_]] {
def combicount (): Int = (1 /: ll) (_ * _.length)
val last = combicount - 1
var iter = 0
override def hasNext (): Boolean = iter < last
override def next (): List[_] = {
val res = combination (ll, iter)
iter += 1
res
}
def combination (xx: List [List[_]], i: Int): List[_] = xx match {
case Nil => Nil
case x :: xs => x (i % x.length) :: combination (xs, i / x.length)
}
}