extend "in" to all array types

Adam D. Ruppe destructionator at gmail.com
Wed Jan 15 07:38:18 PST 2014


On Wednesday, 15 January 2014 at 15:30:35 UTC, pplantinga wrote:
> Is there any chance we could extend this to every kind of array?

Probably not, since there's a significant speed difference 
between in associative array and in regular array. For a regular 
array, it means potentially looping over every item in the array. 
As a general rule, D likes to make long loops obvious in some 
way, like a different function name.

There are functions which do the same thing. Notably, 
std.algorithm.canFind

import std.algorithm;
if(array.canFind(x)) { /* do something */ }


You could also define your own function In if you wanted to keep 
the order that way:

bool In(T)(T lookFor, T[] lookIn) {
     import std.algorithm;
     return lookIn.canFind(lookFor);
}

if(x.In(array)) { /* do something */ }

It is capitalized so it doesn't clash with the keyword, and still 
uses the dot - it is a function called with dot syntax instead of 
an operator -  but it works.


More information about the Digitalmars-d mailing list