my @set = @ARGV ? @ARGV : 1 .. 4; my $iter = set_partitions(@set); my $total; while ( my @part = $iter->() ) { $total++; print join(" ", map { "[@$_]" } @part), $/; } print "There are $total partitions of @set\n"; sub set_partitions { my @universe = @_; my @growth; return sub { if (!@growth) { @growth = (0) x @universe; return [ @universe ]; } return if $growth[-1] == $#growth; my $i = $#growth; $growth[$i--] = 0 while $growth[$i-1] == $growth[$i] - 1; $growth[$i]++; my @return; push @{ $return[$growth[$_]] }, $universe[$_] for 0 .. $#growth; return @return; }; }