Some time ago I was asked the “strange” question how would I implement map with grep.
Today I tried to do it, and here is what came out. Did I squeeze everything from Perl, or there are other more clever hacks?
#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;
sub my_map(&@) {
grep { $_= $_[0]->($_) } @_[1..$#_];
}
my @arr = (1,2,3,4);
#list context
say (my_map sub {$_+1}, @arr);
#scalar context
say "".my_map {$_+1} @arr;
say "the array from outside: @arr";
say "builtin map:", (map {$_+1} @arr);
Are you sure they didn’t ask how to implement
grepwithmap? That’s actually useful sometimes.can be written as
(With one difference:
grepreturns lvalues, andmapdoesn’t.)Knowing this, one can compact
to
(I prefer the “uncompressed” version, but the “compressed” version is probably a little faster.)
As for implementing
mapusinggrep, well, you can take advantage ofgrep‘s looping and aliasing properties.can be written as