powerset operation

M

matt

Hi,

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
powerset.

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...)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top