Test for element in array

BCS BCS at pathlink.com
Thu Jul 13 10:24:30 PDT 2006


Dave wrote:
> BCS 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
>>
>>
>>
>> import std.stdio;
>>
>> void main()
>> {
>>     int[] a = new int[10];
>>     int j=1;
>>
>>     // populate a
>>     foreach(int i, inout int k; a) k=i;
>>
>>     if({foreach(i;a) if(i==j) return true; return false;})
>>         writef("true\n");
>>     else
>>         writef("false\n");
>> }
> 
> 
> That's a very elegant solution and it should work, but according to my 
> tests it doesn't (darn). It never returns false.
> 
> Set j = 100 once and give it a try.

Bizarre

--     if({foreach(i;a) if(i==j) return true; return false;})
++     if({foreach(i;a) if(i==j) return true; return false;}())

this fixes it.

WT...

Oh.

{return false;}.typeof == bool delegate()
{return false;}().typeof == bool





More information about the Digitalmars-d-learn mailing list