我有一些像
这样的专栏age | company | country | gender |
----------------------------------
1 | 1 | 1 | 1 |
-----------------------------------
我想创建像
这样的对答案 0 :(得分:3)
使用Set
收集方法生成powerset的惯用方法subsets
,
implicit class groupCols[A](val cols: List[A]) extends AnyVal {
def grouping() = cols.toSet.subsets.filter { _.size > 1 }.toList
}
然后
List("age","company","country","gender").grouping
递送
List( Set(age, company),
Set(age, country),
Set(age, gender),
Set(company, country),
Set(company, gender),
Set(country, gender),
Set(age, company, country),
Set(age, company, gender),
Set(age, country, gender),
Set(company, country, gender),
Set(age, company, country, gender))
请注意,powerset包含空集和原始集中每个元素的集合,这里我们将它们过滤掉。
答案 1 :(得分:2)
我怀疑你能用元组(and this topic confirms it)实现这一点。
但是你要找的是Power Set
。
考虑这段代码:
object PowerSetTest extends Application {
val ls = List(1, 2, 3, 4)
println(power(ls.toSet).filter(_.size > 1))
def power[A](t: Set[A]): Set[Set[A]] = {
@annotation.tailrec
def pwr(t: Set[A], ps: Set[Set[A]]): Set[Set[A]] =
if (t.isEmpty) ps
else pwr(t.tail, ps ++ (ps map (_ + t.head)))
pwr(t, Set(Set.empty[A]))
}
}
运行它会给你:
Set(Set(1, 3), Set(1, 2), Set(2, 3), Set(1, 2, 3, 4), Set(3, 4), Set(2, 4), Set(1, 2, 4), Set(1, 4), Set(1, 2, 3), Set(2, 3, 4), Set(1, 3, 4))
您可以阅读here了解更多信息