sub iter_choose_n { my $n = pop; # Base cases get assigned to an array, which the iterator shifts through my @base_case = ([]); return sub{ shift @base_case } if $n == 0 or $n > @_; @base_case = (\@_); return sub { shift @base_case } if $n == @_; # otherwise.. my ($first, @rest) = @_; my @sub_iter = ( sub { my $recurse = iter_choose_n(@rest, $n-1); my $set; sub { ($set = $recurse->()) ? [$first, @$set] : () } }, sub { iter_choose_n(@rest, $n) } ); # Below here is boilerplate: if you've done the above steps right, just plug # this in, and it works. It returns the first iterator from the list that # returns anything. # Grab and unwrap an iterator from the list my $iter = (shift @sub_iter)->(); return sub { my $rval; $iter = (shift @sub_iter)->() until ($rval = $iter->() or @sub_iter == 0); return $rval; } }