rectifiedIndexOf()
Basile B.
b2.temp at gmx.com
Fri May 5 02:43:15 UTC 2023
On Friday, 5 May 2023 at 00:19:01 UTC, Salih Dincer wrote:
> It has a traditional very beautiful function: indexOf() but it
> has an important problem: returns -1 when it can't find 'c'...
>
> ```d
> void main()
> {
> enum chr = 'c';
> auto arr = "dlang".dup;
> if(auto res = arr.indexOf(chr))
> {
> assert(arr[res] == chr);
> // core.exception.ArrayIndexError
> }
> }
> ```
>
> When you try to solve the problem with boolean logic, res is
> now a bool.
> [...]
> So now that we've broken the traditional index approach, you
> need to consider this (res - 1) in your code.
>
> SDB at 79
As often in D you can use a struct to help:
```d
auto toBool(ptrdiff_t t)
{
struct ToBool
{
ptrdiff_t value;
alias value this;
bool opCast(T : bool)()
{
return value != -1;
}
}
return ToBool(t);
}
void main()
{
enum chr = 'l';
auto arr = "dlang".dup;
if (auto res = arr.indexOf(chr).toBool())
{
assert(res == 1);
}
}
```
`opCast` is used for the `if` condition and the original value
for reading back in the array, via `alias this`.
More information about the Digitalmars-d
mailing list