Bug 8573 – A simpler Phobos function that returns the index of the mix or max item
Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2012-08-21T05:05:00Z
Last change time
2017-03-13T21:01:27Z
Keywords
bootcamp
Assigned to
nobody
Creator
bearophile_hugs
Comments
Comment #0 by bearophile_hugs — 2012-08-21T05:05:07Z
countUntil returns a signed value with the position, or -1 if not found:
import std.algorithm: countUntil;
void main() {
assert(countUntil("hello world", 'r') == 8);
}
But to find the index of the minimum item things become more complex and more bug-prone:
import std.algorithm: minPos;
import std.range: walkLength;
void main() {
immutable s = "hello world";
immutable sizediff_t mpos = s.walkLength() - minPos(s).walkLength();
assert(mpos == 5);
}
I have typed mpos "sizediff_t" to avoid troubles caused by a unsigned position value.
In Python taking the sum() of an empty list (array) returns 0, while searching for min/max in an empty list causes a ValueError exception to be thrown:
>>> a = []
>>> sum(a)
0
>>> min(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: min() arg is an empty sequence
In D here mpos is 0:
import std.algorithm: minPos;
import std.range: walkLength;
void main() {
immutable s = "";
immutable sizediff_t mpos = s.walkLength() - minPos(s).walkLength();
assert(mpos == 0);
}
So in Phobos I'd like a simple to use function that returns the sizediff_t index of the min item (and when the input is empty, it returns -1 or throws an exception).
Comment #1 by nick — 2016-11-26T11:44:47Z
Alternatively we could use std.range.enumerate with minPos. minPos could take a unary map function like minElement does:
auto index = range.enumerate.minPos!`a.value`.front.value;
Comment #2 by nick — 2016-11-26T11:46:31Z
Oops, should be .front.index at the end.
Comment #3 by github-bugzilla — 2016-12-16T15:16:53Z
Commits pushed to master at https://github.com/dlang/phoboshttps://github.com/dlang/phobos/commit/d2c7d3761b73405ee39da3fd7fe5030dee35a39e
Issue 8573 - A simpler Phobos function that returns the index of the mix or max item
Issue 8573 - A simpler Phobos function that returns the index of the mix or max item
added some review fixes
fixed an issue with a mutable variable
Applied review feedback
Renamed functions to minIndex and maxIndex + used sizediff_t for return value type
Updated function so that it works optimally even for lazy ranges and algorithms
Reverted to having only copyable elements in ranges
Added more unittests; implemented an array path; fixed documentation
Squashed commits
https://github.com/dlang/phobos/commit/f3a840144a156fce5efee82ca13152c2ac1ef1c3
Merge pull request #4921 from RazvanN7/Issue_8573
Issue 8573 - A simpler Phobos function that returns the index of the …
Comment #4 by github-bugzilla — 2017-01-07T03:03:06Z