请注意,如果您有一个集合S 和另一个集合T,其中T = S ∪ {x}(即T 是S 并添加了一个元素),那么T - P(T) 的幂集 - 可以用P(S)和x表示如下:
P(T) = P(S) ∪ { p ∪ {x} | p ∈ P(S) }
也就是说,您可以递归地定义幂集(注意这是如何免费为您提供幂集的大小 - 即添加 1 个元素会使幂集的大小翻倍)。因此,您可以在 scala 中以递归方式执行此操作,如下所示:
scala> 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])) //Powerset of ∅ is {∅}
| }
power: [A](t: Set[A])Set[Set[A]]
然后:
scala> power(Set(1, 2, 3))
res2: Set[Set[Int]] = Set(Set(1, 2, 3), Set(2, 3), Set(), Set(3), Set(2), Set(1), Set(1, 3), Set(1, 2))
用List(即递归ADT)做同样的事情实际上看起来好多了:
scala> def power[A](s: List[A]): List[List[A]] = {
| @annotation.tailrec
| def pwr(s: List[A], acc: List[List[A]]): List[List[A]] = s match {
| case Nil => acc
| case a :: as => pwr(as, acc ::: (acc map (a :: _)))
| }
| pwr(s, Nil :: Nil)
| }
power: [A](s: List[A])List[List[A]]