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$
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.