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

    You find

    print a(\&do_something)->(1 .. 5);

    preferable to:

    print map do_something( $_ ) , 1 .. 5;

    ? or better still

    sub do_something { map{ $_ * 2 } @_ } print do_something 10; 20 print do_something 1..5; 2 4 6 8 10

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco.
    Rule 1 has a caveat! -- Who broke the cabal?
      Well... no. Actually, I had multiple goals when I wrote the snippet.

      When I was on my scooter going back home, I simply thought about simply using map to do the job. Clean and straightforward, as in your first suggestion.

      Then, I was wondering about a scenario in which I would re-use already written functions without touching them. This obviously kicks the last proposal out, which modifies do_something, even if I've to admit that it's quite an elegant approach.

      By the time I came home, I was obsessed by minimising typing (I like these variations on the theme...), so I ended up with that solution. Moreover, I get a pretty obfuscated code with my solution - don't you agree? :) The better I was able to do is to lower typing overhead down to 8 chars.

      -- Don't fool yourself.