Re: Arbitrarily Many Nested Loops



Jacob JKW wrote:
This is what I have:

-------------
#!perl

for (my $i = 0; $i<=$n_ra->[0]; $i++) {
for (my $j = 0; $j<=$n_ra->[1]; $j++) {
for (my $k = 0; $k<=$n_ra->[2]; $k++) {
$prob_ra->[$i+$j+$k] += (
$f_raa->[0]->[$i] *
$f_raa->[1]->[$j] *
$f_raa->[2]->[$k] *
);
}
}
-------------
But that's obviously messy and more imprtantly I'd like to be able to
decide at run time to have how nested levels to go (probably be on the
order of 50 or 60). I assume that there's a canonical manner in which
this should be handled (using closures I'd guess) but I can't
sufficiently summarize my issue to make it Google-able.

Easy enough to do in perl:

my $index_var = 'aa';
my @var_names = map '$' . $index_var++, 0 .. $#$n_ra;

my $nested_loop = join( '',
map "\t" x $_
. 'for ( my '
. $var_names[ $_ ]
. ' = 0; '
. $var_names[ $_ ]
. ' <= $n_ra->[ '
. $_
. ' ]; '
. $var_names[ $_ ]
. "++ ) {\n", 0 .. $#$n_ra )
. "\t" x $#$n_ra
. '$prob_ra->[ '
. join( ' + ', @var_names )
. " ] +=\n"
. join( " *\n",
map "\t" x @$n_ra
. '$f_raa->[ '
. $_
. ' ]->[ '
. $var_names[ $_ ]
. ' ]', 0 .. $#$n_ra )
. "\n"
. join '', map "\t" x $_ . "}\n", reverse 0 .. $#$n_ra;

eval $nested_loop;



John
--
use Perl;
program
fulfillment
.



Relevant Pages

  • Re: Parsing text to array
    ... Which is entirely standard Perl. ... map() actually, and for grepthe above statement holds true. ... They are builtins that make new lists of given ... This is offset by the fundamental simplification that comes with working ...
    (comp.lang.perl.misc)
  • Re: Parsing text to array
    ... Which is entirely standard Perl. ... Not understanding map is nearly as bad ... as not understanding hashes: it is a fundamental part of Perl. ... map() actually, and for grepthe above statement holds true. ...
    (comp.lang.perl.misc)
  • Re: any pointers please? combine words script
    ... it is a very common perl idiom so use it. ... sf> ok...this is cute too, ... i wonder why so many perl newbies have trouble with map. ...
    (comp.lang.perl.misc)
  • Re: Style question: map versus foreach
    ... >> The only real difference between map and foreach is that map returns a ... don't create it in the first place and just use foreach. ... Which version of perl are you using? ... equivalent function exists that documents that there is no return (or ...
    (comp.lang.perl.misc)
  • Re: Is there arithmetic sequence represents?
    ... I prefer to be explicit. ... It is clear what you're shifting: an unqualified 'shift' shifts off the ... advice to use map for list ... encouraging people to learn to use Perl properly. ...
    (comp.lang.perl.misc)