'in' for arrays?
Bill Baxter
dnewsgroup at billbaxter.com
Thu Dec 7 16:39:08 PST 2006
Stewart Gordon wrote:
> Bill Baxter wrote:
>> I keep wanting to say
>> if (val in somearray) {
>> }
>>
>> but 'in' doesn't work for arrays... Is there any reason why not?
> <snip>
>
> You appear to be wanting it to find a given _value_ in an array. Several
> people have requested this. The problem is that it would create a
> confusing inconsistency with associative arrays, in which it is defined
> to find a given _key_.
Confusing to whom? That's the way it works in Python, and it never
seemed the least bit odd or confusing to me, nor dare I say to the vast
majority of Python users.
If you want to check for a value in an AA all you would need is
"v in aa.values". There's no need for a special 'check values' function.
> Logically, if in does anything on linear arrays, then it should check
> whether the given index is within the array's bounds. This isn't just
> purism - it's also a generic programming concern.
Depends on how you think of an array. Technically, yes, that's logical
if you think of an array as a function that maps natural numbers to
values (which is the functional purist's view). But in terms of usage,
for the most part arrays tend to be more like generic containers for
(ordered) values, stored adjacent to each other in memory because that's
the most efficient for certain applications.
The fact that I access an element by an index is just a side effect of
that. In fact sometimes I don't use indices, I use pointers instead.
Should 'x in array' check if the pointer value x is array's memory range?
Arrays, linked lists, sets -- for a lot of purposes they are basically
interchangeable. They're all just containers that hold values. Which
one you choose just depends on what operations on those values need to
be fast for your application, and what sort of ordering matters to you.
In my experience it's much more common to start with an array then
realize at some point that insertion matters to me more than random
access, so I switch to a linked list. In that case should 'x in
container' change from querying if the index is in the container to
querying if the value is in the container (which is the only logical
thing for 'in' to do on a linked list)? Seems 'generic programming
concerns' in that case would be better served by having 'in' check values.
For practical purposes, arrays, lists, and sets are much more similar to
each other than arrays and associative arrays. So if there is any
'generic programming concern' it should default to making the
lists/array/set types be generically interchangeable, not arrays and
associative arrays.
And that's all I'm gonna say about it. There's reasonable arguments
both ways and neither argument amounts to a hill of beans if Walter
isn't interested.
--bb
More information about the Digitalmars-d
mailing list