Comment #0 by peter.alexander.au — 2015-01-05T20:25:55Z
I've often needed this function (and added it really early on to my utilities library)
auto argMin(alias f, alias pred = "a < b", InputRange)(InputRange arg)
{
assert(!arg.empty);
return arg.minPos!((a, b) => binaryFun!pred(f(a), f(b))).front;
}
Ideally the implementation would cache the evaluation of f(x) so that it is only evaluated once per element.
http://en.wikipedia.org/wiki/Arg_max
Comment #1 by bearophile_hugs — 2015-01-05T21:12:11Z
See Issue 4705 where I suggested to add to max/min an optional "key" argument unary function.
So to find the min or max with a key of a sequence you use a reduce:
someRange.reduce!(max!abs)
It evaluates the key function only once for item. It's similar to the max/min Python functions. And it's probably among my top additions to Phobos, beside a pairwise (Issue 6788 ).
Comment #2 by peter.alexander.au — 2015-01-05T21:34:06Z
(In reply to bearophile_hugs from comment #1)
> See Issue 4705 where I suggested to add to max/min an optional "key"
> argument unary function.
>
> So to find the min or max with a key of a sequence you use a reduce:
>
> someRange.reduce!(max!abs)
>
> It evaluates the key function only once for item.
In the reduce, the max!abs would be called n - 1 times, and each call to max!abs(a, b) would involve two calls to abs, so 2(n - 1) calls total, not n (unless I've misunderstood somewhere).
Comment #3 by bearophile_hugs — 2015-01-05T21:59:39Z
(In reply to Peter Alexander from comment #2)
> In the reduce, the max!abs would be called n - 1 times, and each call to
> max!abs(a, b) would involve two calls to abs, so 2(n - 1) calls total, not n
> (unless I've misunderstood somewhere).
Thank you for your answer (that should go also in Issue 4705 ). If you are right, then:
- I want both functions for "min with key" and "max with key" (putting only one of them in Phobos sucks);
- I prefer an unary function instead of a binary function. When you get used to unary functions they are much more handy.
So I guess you can call call them keyMax and keyMin.
Comment #4 by bearophile_hugs — 2015-01-05T22:00:58Z
So its usage looks like:
someRange.keyMin!abs
someRange.keyMax!abs
Comment #5 by bearophile_hugs — 2015-01-06T14:13:26Z
Min and maxElement are part of Phobos since 2.071 - the crowd goes wild :)
They support a custom mapping function and evaluation of the mapping is only done once.