rectifiedIndexOf()

Quirin Schroll qs.il.paperinik at gmail.com
Fri May 12 17:40:34 UTC 2023


On Saturday, 6 May 2023 at 18:58:54 UTC, Salih Dincer wrote:
> On Saturday, 6 May 2023 at 16:39:13 UTC, Quirin Schroll wrote:
>> 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'...
>>
>> That is bad design. It should return an optional type or 
>> something like that, but D doesn’t have those. C++ has a lot 
>> of similar functions and I guess that was one reason why C++17 
>> introduced an *init-statment* to `if`. D could do the same.
>>
>> ```d
>> if (auto index = arr.indexOf('c'); index >= 0) …
>> ```
>
> In fact, there is worse!  The intent is to prevent leaking 
> outside the scope of if-else.  But it doesn't work in the else 
> block and we get the error undefined identifier `num`.
>
> ```d
>   if(auto num = imported!"std.random".uniform!int.max % 2)
>   {
>     assert(num > 0);
>   } else {
>     //assert(num == 0);
>   }
> ```
>
> I would like these issues to be resolved, but we spend our 
> energy on more difficult things!

I guess the reason why something that is declared in the 
condition is scoped to the “then” part and not visible in the 
“else” part is that if something evaluates to `false`, usually 
it’s not interesting. Something that evaluates to `false` is a 
`bool` that’s `false`, a number that’s `0`, or a pointer or class 
handle or whatever reference type that holds no interesting 
state. A user-defined type evaluates to `false` and has an 
interesting value is really bad design.

However, if you do C++’s `if` with initialization and condition 
separately, you can handle the “uninteresting `false`” value in 
the “then” branch and do the interesting work in the “else” 
branch. For that reason, something declared in the 
*init-statement* of an `if` should be visible in the “else” 
branch.


More information about the Digitalmars-d mailing list