Reputation: 6840
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
).
Upvotes: 12
Views: 928
Reputation: 169683
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.
Upvotes: 15