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:
which can be used in various ways and is not limited in dimension:# 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; }
just to get an idea.$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]]
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
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: n-dim array generator
by LanX (Saint) on Jun 17, 2020 at 13:01 UTC | |
by LanX (Saint) on Jun 17, 2020 at 13:26 UTC | |
by jo37 (Deacon) on Jun 17, 2020 at 15:03 UTC | |
by LanX (Saint) on Jun 17, 2020 at 15:16 UTC | |
by etj (Deacon) on Apr 21, 2022 at 08:27 UTC | |
by LanX (Saint) on Jun 17, 2020 at 14:57 UTC |
Back to
Meditations