Every now and then I need to create a n-dimensional array from some given formula, where n almost always is 1 or 2.
I've been searching for a module providing such functionality without success.
It would be a surprise if there really wasn't such a thing.
But so I rolled my own and came to this:
# arg_1 to arg_n specify size in dimension k,
# last arg is a reference to a sub
# - expecting n arguments x1 ... xn
# - returning the desired value at $na->[x1]...[xn]
sub narray {
my $size = shift;
my $val = pop;
my $na;
for my $i (0 .. $size - 1) {
$na->[$i] = @_ ? narray(@_, sub {&$val($i, @_)}) : &$val($i);
}
$na;
}
which can be used in various ways and is not limited in dimension:
$ar = narray(3, sub {$_[0]});
# [0, 1, 2]
$mr = narray(3, 3, sub {$_[0] == $_[1] || 0});
# [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
just to get an idea.
Does anybody know of a module providing something similar?
Otherwise: Is this of use for someone else or would it even fit into something existing?
UPDATE 1: This would be more perlish if the sub ref argument came first and the sub itself was prototyped:
sub narray (&@);
$ar = narray {$_[0]} 3;
UPDATE 2: Incorporating LanX's suggestion of using map into UPDATE 1 results in:
sub narray (&@);
sub narray (&@) {
my $val = shift;
my $size = shift;
[map {my $i = $_; @_ ? narray {&$val($i, @_)} @_ : &$val($i)} (0 .
+. $size - 1)];
}
my $na = narray {"<@_>"} 3, 2
# [['<0 0>', '<0 1>'], ['<1 0>', '<1 1>'], ['<2 0>', '<2 1>']]
Greetings,
-jo
$gryYup$d0ylprbpriprrYpkJl2xyl~rzg??P~5lp2hyl0p$