21

I have a Set of items of some type and want to generate its power set.

I searched the web and couldn't find any Scala code that adresses this specific task.

This is what I came up with. It allows you to restrict the cardinality of the sets produced by the length parameter.

def power[T](set: Set[T], length: Int) = {
   var res = Set[Set[T]]()
   res ++= set.map(Set(_))

   for (i <- 1 until length)
      res = res.map(x => set.map(x + _)).flatten

   res
   }

This will not include the empty set. To accomplish this you would have to change the last line of the method simply to res + Set()

Any suggestions how this can be accomplished in a more functional style?

4

8 回答 8

60

看起来在 7 月份没有人知道它,但是有一个内置的方法:subsets.

scala> Set(1,2,3).subsets foreach println
Set()
Set(1)
Set(2)
Set(3)
Set(1, 2)
Set(1, 3)
Set(2, 3)
Set(1, 2, 3)
于 2012-10-29T05:32:56.960 回答
34

请注意,如果您有一个集合S和另一个集合Twhere 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]]
于 2012-07-20T14:25:01.197 回答
20

这是编写它的更有趣的方法之一:

import scalaz._, Scalaz._

def powerSet[A](xs: List[A]) = xs filterM (_ => true :: false :: Nil)

哪个按预期工作:

scala> powerSet(List(1, 2, 3)) foreach println
List(1, 2, 3)
List(1, 2)
List(1, 3)
List(1)
List(2, 3)
List(2)
List(3)
List()

例如,请参阅此讨论线程以了解其工作原理。

(正如 debilski 在评论中指出的那样,ListW也拉皮条powersetList,但这并不好玩。)

于 2012-07-20T15:20:14.173 回答
15

使用内置combinations函数:

val xs = Seq(1,2,3)
(0 to xs.size) flatMap xs.combinations

// Vector(List(), List(1), List(2), List(3), List(1, 2), List(1, 3), List(2, 3),
// List(1, 2, 3))

请注意,我作弊并使用了 a Seq,因为未知原因,combinationsSeqLike. 因此,使用一组,您需要转换为/从 a Seq

val xs = Set(1,2,3)
(0 to xs.size).flatMap(xs.toSeq.combinations).map(_.toSet).toSet

//Set(Set(1, 2, 3), Set(2, 3), Set(), Set(3), Set(2), Set(1), Set(1, 3), 
//Set(1, 2))
于 2012-07-20T15:19:10.677 回答
3

可以很简单:

def powerSet[A](xs: Seq[A]): Seq[Seq[A]] = 
  xs.foldLeft(Seq(Seq[A]())) {(sets, set) => sets ++ sets.map(_ :+ set)}

递归实现:

def powerSet[A](xs: Seq[A]): Seq[Seq[A]] = {
  def go(xsRemaining: Seq[A], sets: Seq[Seq[A]]): Seq[Seq[A]] = xsRemaining match {
    case Nil => sets
    case y :: ys => go(ys, sets ++ sets.map(_ :+ y))
  }

  go(xs, Seq[Seq[A]](Seq[A]()))
}
于 2016-03-24T10:44:53.897 回答
2

所有其他答案似乎有点复杂,这是一个简单的函数:

    def powerSet (l:List[_]) : List[List[Any]] =
      l match {
       case Nil => List(List())
       case x::xs =>
         var a = powerSet(xs)
         a.map(n => n:::List(x)):::a
      }

所以

    powerSet(List('a','b','c'))

将产生以下结果

    res0: List[List[Any]] = List(List(c, b, a), List(b, a), List(c, a), List(a), List(c, b), List(b), List(c), List())
于 2017-08-08T17:24:37.437 回答
0

这是另一个(懒惰的)版本......因为我们正在收集计算幂集的方法,我想我会添加它:

def powerset[A](s: Seq[A]) =
  Iterator.range(0, 1 << s.length).map(i =>
    Iterator.range(0, s.length).withFilter(j =>
      (i >> j) % 2 == 1
    ).map(s)
  )
于 2014-04-27T19:21:57.203 回答
0

这是一个使用辅助函数的简单递归解决方案:

def concatElemToList[A](a: A, list: List[A]): List[Any] = (a,list) match {
    case (x, Nil)                 => List(List(x))
    case (x, ((h:List[_]) :: t))  => (x :: h) :: concatElemToList(x, t)
    case (x, (h::t))              => List(x, h) :: concatElemToList(x, t)
}

def powerSetRec[A] (a: List[A]): List[Any] = a match {
    case Nil    => List()
    case (h::t) => powerSetRec(t) ++ concatElemToList(h, powerSetRec (t))
}

所以呼唤

powerSetRec(List("a", "b", "c"))

会给出结果

List(List(c), List(b, c), List(b), List(a, c), List(a, b, c), List(a, b), List(a))
于 2016-03-24T21:59:18.047 回答