Test for element in array

Regan Heath regan at netwin.co.nz
Thu Jul 13 17:46:23 PDT 2006


On Thu, 13 Jul 2006 16:46:46 -0700, BCS <BCS at pathlink.com> wrote:
> Andrei Khropov wrote:
>> Paolo Invernizzi wrote:
>>
>>> Hi all,
>>>
>>> Someone can suggest me the best way for testing the presence of an  
>>> element in
>>> an array?
>>>
>>> Coming from python, something like...
>>>
>>> if( x in array_of_x && y in array_of_y ){
>>>   ...
>>> }
>>>
>>> The workaround, apart from using a simple 'for' loop, is to use an
>>> associative array, and test for key...
>>>
>>> ---
>>> Paolo
>>   Despite BCS proposed a cool solution
>
> thanks
>
>> I think 'in' should be built-in for usual (non-associative) arrays too.  
>> why not?
>>
>
> the semantics are backwards, not a killer but its a little inconsistent.
>
> With aa, the type of the LHS is the type of the index
>
> if(a in b) b[a]; // valid
>
> with non-aa, the type of the LHS would be the type of the stored value.

True.. (wild idea alert) unless we make it valid to index an array with a  
value, which in turn returns the index of that value. It would perform a  
linear search from start to end (or match) therefore returning the 'first'  
match.

> The above wont always work for a non-aa. Also which a in b is found? The  
> first? An array of all? The last?

In the case of 'in' aren't you just asking "is it in there", in which case  
it could return the first, or last, doesn't really matter.

However, 'in' does return a pointer to the value .. I think returning the  
first is the least surprising, most useful thing to do. It would also be  
consistent with the index by value idea above.

So, if you want the last match you say:
   if (a in b.reverse)

and if you want the 2nd, 3rd, 4th etc
   p = (a in b);           //gets first
   p = (a in b[b[*p]..$]); //2nd
   p = (a in b[b[*p]..$]); //3rd
   p = (a in b[b[*p]..$]); //4th

funky! ;)

Regan



More information about the Digitalmars-d-learn mailing list