'in' for arrays?
Bill Baxter
wbaxter at gmail.com
Wed Dec 6 13:21:13 PST 2006
Chris Nicholson-Sauls wrote:
> 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.
>
>
> Now this I actually like... Can already think of places I could use it,
> such as in Bovis during symbol/id lookups. Its a nice idea. (Might
> just add it to Cashew in the meantime.)
>
> -- Chris Nicholson-Sauls
Ugh. I've created a monster.
That would make sense in Lua where there is only one data structure
(table), which can be indexed with numbers or non-numbers equally well,
but in D, it just doesn't seem right to say 2 is 'in'
["spam","eggs","spam"]. I certainly don't see any 2 in there. The
operation you want seems more like a get():
T* get(T[] arr, size_t index) {
return (index < arr.length ? &arr[index] : null)
}
if (somearray.get(10)) {
}
The dict type in Python uses something like that for safe indexing,
otherwise you use [] if throwing an exception is ok.
--bb
More information about the Digitalmars-d
mailing list