Best way to check for an element in an array?

Taylor Hillegeist via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Apr 21 21:22:11 PDT 2014


On Tuesday, 22 April 2014 at 03:57:33 UTC, Timothee Cour via 
Digitalmars-d-learn wrote:
> you can use stuff.canFind(2)
>
> but sometimes it'd be more convenient to have the other way 
> around (UFCS
> chains etc);
>
> how about:
>
> bool isIn(T,T2...)(T needle, T2 haystack)
> if(__traits(compiles,T.init==T2[0].init)){
>   foreach(e;haystack){
>     if(needle==e) return true;
>   }
>   return false;
> }
> unittest{
> assert(1.isIn(3,1,2) && !4.isIn(3,1,2));
> }
>
I like it! I didn't know you could use templates like that! 
Question though? why doesn't canFind() work on statically 
allocated arrays?

import std.stdio;
import std.algorithm;

bool contains(T)( T[] haystack,T needle){
		 foreach(T e;haystack){
		   if(needle==e) return true;
		 }
	 return false;
}
unittest{
	assert([3,1,2].contains(1) && ![3,1,2].contains(4));
}

void main(string[] args)
{
     int[3] stuff=[0,1,2];
	if (stuff.contains(2))
     {
         writeln("Hello World!");
     }
	
	if (stuff.canFind(2)){ // No compile with stuff -> static
	    writeln("This Also WOrks");
	}
}


> On Mon, Apr 21, 2014 at 8:25 PM, Taylor Hillegeist via 
> Digitalmars-d-learn <
> digitalmars-d-learn at puremagic.com> wrote:
>
>> So I find myself Doing this kind of thing very frequently. I 
>> have a Array
>> of Somethings and i want to see if "something specific" is 
>> inside the
>> array. I wrote a template for it. but is this the best way to 
>> do this kind
>> of thing. I feel like it doesn't help with readability. Is 
>> there a better
>> way? Maybe i missed something in the std library.
>>
>> import std.stdio;
>>
>> template FNDR(T){
>>     bool isIn(T Element, T[] Array){
>>         bool rtn=false;
>>         foreach(T ArrayElement; Array){
>>             if(Element==ArrayElement){
>>                 rtn=true;
>>             }
>>         }
>>     return rtn;
>>     }
>> }
>>
>> void main(string[] args)
>> {
>>     int[3] stuff=[0,1,2];
>>     if (FNDR!int.isIn(2,stuff))
>>     {
>>         writeln("Hello World!");
>>     }
>> }
>>
>>
>> Is there a way maybe to make it look like this?
>>
>> import std.stdio;
>>
>> template FNDR(T){
>>     bool contains(T[] Array,T Element){
>>         bool rtn=false;
>>         foreach(T ArrayElement; Array){
>>             if(Element==ArrayElement){
>>                 rtn=true;
>>             }
>>         }
>>     return rtn;
>>     }
>> }
>>
>> void main(string[] args)
>> {
>>     int[3] stuff=[0,1,2];
>>     if (stuff.contains(2)) // Much clean! 
>> stuff.FNDR!int.contains(2)
>> doesn't work
>>     {
>>         writeln("Hello World!");
>>     }
>> }
>>
>> I'm interested in what you guys think? what is the cleanest 
>> way to do this?



More information about the Digitalmars-d-learn mailing list