Test for element in array

Chris Nicholson-Sauls ibisbasenji at gmail.com
Fri Jul 14 01:52:45 PDT 2006


Paolo Invernizzi wrote:
> BCS wrote:
> 
>> 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. The above wont always work for a non-aa. Also which a in b is 
>> found? The first? An array of all? The last?
> 
> 
> I would be satisfied also if it just returns a boolean value, like a 
> simple inclusion test...
> 
> But for now, I will use the BCS solutions! Thanks!
> 
> ---
> Paolo
> 

That's most likely the best solution for the moment.  Although, you could generalize it by 
  taking advantage of IFTI and defining this somewhere:

# bool contains (T : T[]) (T[] haystack, T needle) {
#   foreach (x; haystack) {
#     static if (is(T : Object)) {
#       if (x is needle)
#         return true;
#     }
#     else {
#       if (x == needle)
#         return true;
#     }
#   }
#   return false;
# }

Then your test would just be:

# if (foo.contains(bar)) {
#   // do stuff
# }

I think it reads pretty well, even if it isn't quite as "clean" as (bar in foo) in 
comparison.  Which, incidentally, also does read well.

-- Chris Nicholson-Sauls



More information about the Digitalmars-d-learn mailing list