469,903 Members | 1,698 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,903 developers. It's quick & easy.

powerset operation


I would like to know how to implement a powerset operation in perl.
My friend found the code:

sub subsets {
map {
my $n = $_;
[@_[grep {$n & 1 << $_} 0..$#_]]
} (1..2**($#_ + 1));

online, and that makes sense - but I would like to understand how to
build a lists of lists etc through the `normal' way of building the

Normal being akin to the haskell code:
powerset :: [a] -> [[a]]
powerset [] = [[]]
powerset (x:xs) = concat $ [[l, x:l] | l <- powerset xs]

my closest perl approximation is:

sub subsets {
my @list;
@list = @_;

return (()) if ($#list < 0);

my @subs;
@subs = subsets(@subs[1..$#subs]);

my @with;
@with = @subs;
foreach (@with) {
push(@{$_}, $list[0]);
push(@subs, [ $_ ]);

return @subs;
but this doesn't seem to work. (I'm relatively new to perl, but am a
somewhat well-versed unix and ruby user, if where I'm coming from
matters in explanations...)
Jul 19 '05 #1
0 1473

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

reply views Thread by Tim Rowe | last post: by
1 post views Thread by Gunnar G | last post: by
4 posts views Thread by Hardy Wang | last post: by
reply views Thread by relaxedrob | last post: by
2 posts views Thread by Robinson | last post: by
reply views Thread by Default User | last post: by
1 post views Thread by Waqarahmed | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.