About the in expression, Why can't use with array.

IGotD- nise at nise.com
Fri Oct 25 21:06:53 UTC 2019


On Friday, 25 October 2019 at 20:44:18 UTC, Dennis wrote:
> On Friday, 25 October 2019 at 19:49:05 UTC, Ali Çehreli wrote:
>> I'm still not completely sold on the whole idea though because 
>> it's not a clear win.
>>
>> Do others see other advantages in other places like templates? 
>> For example, could templates really be written generically for 
>> arrays and associative arrays?
>
> I'm personally not concerned about generic code.
> - The semantics of `in` aren't very well defined anyways.
> - Those who write templates like that (hopefully) know what 
> they're doing, they'll figure it out  ;)
> - I can't think of situations where you actually want to write 
> code that generically works on both arrays and associative 
> arrays like that. (Though if anyone knows one, please share, 
> I'm interested.)
>
> I'm more concerned about the repeated reports of users being 
> surprised that `in` doesn't work like they expect. In Python, 
> the expression `3 in [2, 3, 4]` returns a boolean, and in D you 
> can do `bool b = 15 in iota(10, 20)` because the operator is 
> overloaded in Phobos for iota; But as far as actual language 
> support, `in` is only defined for associative arrays:
>
> https://dlang.org/spec/expression.html#InExpression
>
> It returns a pointer which can be used in an if-statement, but 
> also to read/modify the value. So should `in` on arrays do the 
> same? It would be consistent, but usage of raw pointers is 
> discouraged with the advent of scope and ref etc. Also you 
> can't implicitly convert a pointer to a boolean.
> Should it be a boolean then? That means part of the result of 
> the linear search is discarded, making `in` less flexible.
> So maybe we should leave it for now, and put a small 
> explanation in the error message.

I'm also not so fond of that "in" operator returns a pointer 
which is bad fit for arrays and possibly many other container 
algorithms as well. I think the best would be that it would 
return an optional of type T and T would be user defined. For 
associative arrays, a pointer or a reference to the element. For 
arrays the index of that element would suitable. Also overloading 
would be nice so that "in" operator could return several possible 
optional types, not sure if that would be possible though.




More information about the Digitalmars-d-learn mailing list