Here is a fairly common problem. We have an array of arrays. We'd like to call some function for every combination of elements from the different arrays. Conceptually we'd like to do something like this:
for my $x (1, 2) {
for my $y ('a', 'b') {
for my $z ('A', 'B') {
print "$x $y $z\n";
}
}
}
except that we don't want to have to write out a different number of loops if we have a different number of elements. In other words we want to be able to implement the above as something like:
nested_for(
sub {print "@_\n"},
[1, 2], ['a', 'b'], ['A', 'B']
);
and get the same result. (Exact syntax may vary by language.)
One solution per post, please.
Index of Solutions
(with at least +1 vote)
- APL by Christian D
- D by BCS
- Haskell
- Java by einarwh.myopenid.com
- JavaScript by Kent Fredric
- Lisp
- by levy
- a newbie attempt by Chris Jester-Young
- Nemerle by Cody Brocious
- Perl
- by bentilly.blogspot.com
- with Algorithm::Loops by runrig.myopenid.com
- Perl 6 version by Eevee
- Python
- by Alexander Kojevnikov
- with generators by Torsten Marek
- Ruby
- two solutions by Kent Fredric (including a variant with mapping)
- by bentilly.blogspot.com on behalf of Christoph Rippel
- by Kevin Conner
- permutative/generative version by Kent Fredric