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?
Here's one of the more interesting ways to write it:
Which works as expected:
See for example this discussion thread for an explanation of how it works.
(And as debilski notes in the comments,
ListW
also pimpspowerset
ontoList
, but that's no fun.)Looks like no-one knew about it back in July, but there's a built-in method:
subsets
.Use the built-in
combinations
function:Note, I cheated and used a
Seq
, because for reasons unknown,combinations
is defined onSeqLike
. So with a set, you need to convert to/from aSeq
:Notice that if you have a set
S
and another setT
whereT = S ∪ {x}
(i.e.T
isS
with one element added) then the powerset ofT
-P(T)
- can be expressed in terms ofP(S)
andx
as follows:That is, you can define the powerset recursively (notice how this gives you the size of the powerset for free - i.e. adding 1-element doubles the size of the powerset). So, you can do this tail-recursively in scala as follows:
Then:
It actually looks much nicer doing the same with a
List
(i.e. a recursive ADT):Can be as simple as:
Recursive implementation:
Here's a simple, recursive solution using a helper function:
so the call of
will give the result