Back to my MATLAB days at the University, I remember striving to write functions that behaved well with either scalars and arrays (typically applying the same "scalar" operation on every element in the array). This was generally repaid by the fact that I used lots of arrays.
Writing such functions in Perl, I always ask myself if I should stick to the same convention. As a matter of fact, yesterday I realised that I should not - it can take me only 8 characters of typing overhead to get the array version of any "simple one-scalar" function if I really need it (and I usually don't need these days :).
I understand this is some very basic example of a trivial application of map, but I wonder if there's any trick to do even less typing.
# Build an array-ized version of a sub sub a { my $s = shift; sub{map {&$s($_)} @_}; } # A simple function workin only on one scalar parameter sub do_something {$_[0] * 2} # Use 'em print do_something 10; print "\n", join (', ', a(\&do_something)->(1 .. 5)), "\n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Array-ize a function
by BrowserUk (Patriarch) on Mar 18, 2005 at 15:04 UTC | |
by polettix (Vicar) on Mar 18, 2005 at 15:55 UTC |