sub combinations returns Array (@list is rw) { return () unless @list.elems; gather { for 1 .. 2**@list.elems-1-> $num { take [ @list[ (0 .. sqrt($num)).grep:{ $num +& (2**$_) } ] ]; } } } my @list = (1..4); combinations(@list).perl.say;