Finding position of a value in an array

Steven Schveighoffer 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 
(https://github.com/dlang/phobos/commit/224c570c1b191f4d3701160265961149e174cc71)

2. In 
https://github.com/dlang/phobos/commit/a4c244f2a8037fb35b3d8c758aa3c60edfc45fbd, 
it was changed to "indexOf", improving on the API.

3. In 
https://github.com/dlang/phobos/commit/d90a1a94e0cbb8fbe1e96299c254dd8ec24c9a83 
it was switched to be generic based on the character type.

4. In 
https://github.com/dlang/phobos/commit/3ea2debb8c4a6a707447c684e94f651924efaa96 
a range version is added to std.algorithm, which uses only range 
functions, but has a special version for narrow strings which does what 
std.string.indexOf does.

5. In 
https://github.com/dlang/phobos/commit/c2f018066ab649bd7fd3cd6a07aa151a5cea9549 
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 ;)

-Steve


More information about the Digitalmars-d-learn mailing list