Suppose you have a list of items, and you are going to compute some expensive function on each of them.
Sometimes it is convenient to have
the minimum (or maximum) value of the function. Other times, it is more convenient to have
the item which minimizes (or maximizes) the function (for example, what is the hash key that corresponds to the largest hash value?). And sometimes you even want both.
The latter behavior is referred to as argmin and argmax. To do this in Perl, you can always sort based on the expensive function, and then grab the min/max, but the sort is very wasteful for long lists (even with a Schwartzian Transform). Instead, here's a simple watermarking way to do it. In list context, it also returns both values of interest (the item that minimized/maximized the function, and the min/max value itself).
- Get the largest value that an expression takes on:
use List::Util 'max';
my $largest_val = max map { expensive_func($_) } @items;
- Get the item which produces the largest value on an expression:
my $largest_item = argmax { expensive_func($_) } @items;
- Get both at once:
my ($largest_item, $largest_val) = argmax { expensive_func($_) } @item
+s;
A very simple concept, but quite useful.
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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.