'in' for arrays?
Chad J
gamerChad at _spamIsBad_gmail.com
Wed Dec 6 08:58:36 PST 2006
Lionello Lunesu wrote:
> Bill Baxter wrote:
>
>> I keep wanting to say
>> if (val in somearray) {
>> }
>
>
> Wait! That's just it!
>
> It's "KEY in CONTAINER" and the KEY of a regular array is the index, not
> the value. So dare I suggest the following instead?
>
> if (index in somearray) {
> }
>
> This "in" would be:
> (cast(size_t)index < somearray.length?&somearray[index]:null)
>
> Totally analogous to the associative array. And it also solves the
> "Length comparison" issue.
>
> L.
hmmm, seems unintuitive to me. I tend to think of the "in" operator
acting on a set and a potential member of the set. I also tend to think
of an array as a set of somethings. Now when I make an int[] and say
something like if( 14 in somethings ) I'd expect it to look through the
set of somethings and see if the number 14 is in there. I wouldn't
expect it to look through the set of integers that are less than
somethings.length to see if 14 is in that.
Now I'm wondering, why is it a good idea to have "in" mean what it does
for aa's? It seems to hold back a lot of other stuff, and not provide
much. It would be nice to be able to write foreach(value in array)
instead of using the strange semicolon syntax - and this is very common.
I doubt the current usage of "in" is anywhere near as common as that,
or even as common as something like if(ipAddy in ipAddresses). Thus it
would be more appropriate to, in those few cases of aa "in" usage,
instead write aa.hasKey(key) instead of (key in aa). Changing that
would also allow you to write (value in aa).
Notice that associative arrays have a .keys property. Perhaps then, we
could simply define the current usage of "in" - (key in aa) - to be
shorthand for (key in aa.keys). With that "in" has a more intuitive
meaning, IMO.
More information about the Digitalmars-d
mailing list