It's easy enough to find the maximum value in a list in Perl 6:
> my @list = 1,4,9,7,3;
> say @list.max;
9
But if I want to find the index of the maximum entry, there doesn't seem to be an elegant way to do this.
> say (^@list).sort({ -@list[$_] })[0];
2
> say @list.pairs.sort(*.value).tail.key;
2
> say @list.first(@list.max, :k);
2
Those all work, but they're hardly elegant, let alone efficient.
Is there a better way to do this?
It'd be nice if max
had :k
, :v
and :kv
options, like for instance first
has.
Of course, there might not be a unique index (for instance, in the case of (1,4,9,7,9).max
, but then again, there might not be a unique value either:
> dd (1, 2.0, 2.0e0, 2).max;
2.0
> say <the quick brown fox>.max(*.chars);
quick
max
already retrieves the first maximum value, so it would be perfectly reasonable to return the first index with :k
(or :kv
).
Note: In Perl arrays, the size of an array is always equal to (maximum_index + 1) i.e. And you can find the maximum index of array by using $#array.
max index(es) is the index for the first max value. If array is multidimensional, max index(es) is an array whose elements are the indexes for the first maximum value in array. min value is of the same data type and structure as the elements in array. min index(es) is the index for the first min value.
You can use
@list.maxpairs
to get a list of all pairings of indices and maximal values or
@list.pairs.max(*.value).key
to get just a single index.
As far as I can see, both maxpairs
and the ability to provide a transformation to max
are still undocumented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With