Comparing Multiple Values

Bill Baxter dnewsgroup at billbaxter.com
Tue Mar 11 14:23:56 PDT 2008


downs wrote:
> Bill Baxter wrote:
>> okibi wrote:
>>> I've looked all over the site but can't seem to find if D supports any
>>> kind of like IN statement for comparisons. For example, I can do the
>>> following in SQL:
>>>
>>> select *
>>> from table
>>> where value in (1,2,3)
>>>
>>> And it will compare it to 1, 2, and 3. Is this possible to do within
>>> D's if statement? I hate to go about it as such:
>>>
>>> if (value == 1 || value == 2 || value == 3)
>>>     dosomething();
>>>
>>> Just seems like this could be written better. Can anyone give me any
>>> pointers?
>> I can point you to a bunch of discussions where certain people argued
>> tooth and nail that  "if(value in [1,2,3])" should mean
>> "if(value==0||value==1||value==2)", leading basically to a stalemate.
>> So, no.  Nothing like that is in the language.
>>
>> But you can write a little "contains" function that will do the trick.
>>
>> Or ask Downs how to make "if(x /In/ [1,2,3])" work.
>>
>> --bb
> 
> There's a better way actually.
> 
> import std.stdio;
> 
> // bottom-inclusive, top-exclusive, like slices.
> struct _Range(T) {
>   T from, to;
>   bool opIn_r(U)(U u) {
>     return u < to && u !< from;
>   }
> }
> 
> struct Range {
>   static _Range!(T) opSlice(T, U)(T from, U to) {
>     return _Range!(T)(from, to);
>   }
> }
> 
> void main() {
>   writefln(3 in Range[2..4], " -- ", 4 in Range[2..4]);
> }
> 
> Have funs!
> 
>  --downs


Downs seems to have misunderstood the request, but his suggestion can be 
adapted to do what the OP wanted, and without the high cost of 
constructing an associative array on the fly:

import std.stdio;

struct _Set(T) {
     T[] _set;
     bool opIn_r(U)(U u) {
         foreach(v; _set) {
             if (v==u) return true;
         }
         return false;
     }
}

struct Set {
     static _Set!(T) opIndex(T)(T[] x ...) {
         return _Set!(T)(x);
     }
     // or this
     static _Set!(T) opCall(T)(T[] x ...) {
         return _Set!(T)(x);
     }
}

void main() {
     // doesn't work because of template deduction bug :-(
     //writefln(3 in Set[2,7,4], " -- ", 4 in Set[2,7,4]);

     // ok
     writefln(3 in Set([2,7,4]), " -- ", 4 in Set([2,7,4]));
}


More information about the Digitalmars-d-learn mailing list