extend "in" to all array types

John Colvin john.loughran.colvin at gmail.com
Wed Jan 15 07:48:12 PST 2014


On Wednesday, 15 January 2014 at 15:30:35 UTC, pplantinga wrote:
> In python, I really like the ability to check if an element is 
> in an array:
>
> if x in array:
>   # do something
>
> D has this, but only for associative arrays. Is there any 
> chance we could extend this to every kind of array?

import std.algorithm: canFind;

if(array.canFind(x))
     //do something


alternatively, something like this:

struct InWrapper(T)
{
     T unwrapped;
     alias unwrapped this;

     auto opBinaryRight(string op, T)(T el)
         if(op == "in")
     {
         import std.algorithm : canFind;
         return unwrapped.canFind(el);
     }
}

unittest
{
     InWrapper!(int[]) arr;
     arr = [1,2,3,4];

     assert(4 in arr);
     assert(!(5 in arr));
}



More information about the Digitalmars-d mailing list