![]() |
|
laziness, impatience, and hubris | |
PerlMonks |
argmin & argmaxby blokhead (Monsignor) |
on May 03, 2005 at 21:26 UTC ( #453733=snippet: print w/replies, xml ) | Need Help?? |
sub argmax(&@) { my $index = undef; my $max = undef; my $block = shift; for (@_) { my $val = $block->($_); if ( not defined $max or $val > $max ) { $max = $val; $index = $_; } } return wantarray ? ($index, $max) : $index; } sub argmin(&@) { my $index = undef; my $min = undef; my $block = shift; for (@_) { my $val = $block->($_); if ( not defined $min or $val < $min ) { $min = $val; $index = $_; } } return wantarray ? ($index, $min) : $index; }These could also be implemented with List::Util::reduce, but just doing it by hand makes it easier to let the block to run with $_ aliased to the relevant value -- instead of fussing with $a and $b in L::U::reduce.
|
|