Test for element in array
Kirk McDonald
kirklin.mcdonald at gmail.com
Thu Jul 13 11:52:13 PDT 2006
BCS wrote:
> 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
>
>
Hmmm. "Lambda properties." Fun.
--
Kirk McDonald
Pyd: Wrapping Python with D
http://dsource.org/projects/pyd/wiki
More information about the Digitalmars-d-learn
mailing list