Finding position of a value in an array
schveiguy at gmail.com
Tue Dec 31 21:00:26 UTC 2019
On 12/31/19 2:52 PM, H. S. Teoh wrote:
> On Tue, Dec 31, 2019 at 09:41:49AM -0500, Steven Schveighoffer via Digitalmars-d-learn wrote:
>> On 12/30/19 6:15 PM, JN wrote:
>>> On Sunday, 29 December 2019 at 08:31:13 UTC, mipri wrote:
>>>> int i = a.countUntil!(v => v == 55);
>>>> assert(i == 2);
>>> I also had to ask because I couldn't find it. In other languages
>>> it's named "index()", "indexOf()" or "find()". D is the only
>>> language I know which uses the "countUntil" scheme. And even so it's
>>> not obvious from the name if it's the index of the element or number
>>> of preceding elements.
>> indexOf used to be in std.algorithm I believe. It was nixed for having
>> too simple an implementation I believe.
> No, it still exists as std.string.indexOf.
> IIRC, the story goes like this: countUntil was the original way of doing
> this, but, no thanks to autodecoding, it returns the wrong value for
> strings. So indexOf was introduced to fix the problem for strings, but
> since it was string-specific it was added to std.string instead.
So I looked way way back in history. This predates our usage of github
PRs, so all I have is commit messages for a lot of these. I was wrong on
the reasoning for it being deprecated, see below.
1. phobos std.string module contained a "find" function, which looked
for a dchar in a string. Earlier (probably in Phobos 1, which I never
used) I think it was just for char, but was switched to dhcar in 2007
it was changed to "indexOf", improving on the API.
it was switched to be generic based on the character type.
a range version is added to std.algorithm, which uses only range
functions, but has a special version for narrow strings which does what
indexOf is renamed to countUntil to disambiguate the two functions (with
almost identical results, but different implementations). Note that at
this time, countUntil on a string did NOT use autodecoding (it had a
special case to make it return the same thing as indexOf).
At some point since then, countUntil was altered to remove the special
case for narrow strings, and returned what one might expect.
> Either way, it's yet another reason to kill autodecoding with fire (and
> extreme prejudice).
Well, I must agree with your conclusion, even if the evidence doesn't
corroborate your story ;)
More information about the Digitalmars-d-learn