More uses of operator "in"
Baz via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Oct 28 08:11:00 PDT 2014
On Tuesday, 28 October 2014 at 13:50:24 UTC, Nordlöw wrote:
> Has there been any proposals/plans to make operator "in" work
> for elements in ranges such as
>
> assert('x' in ['x']);
>
> I'm missing that Python feature when I work in D.
There is also something similar in Pascal, at the language level.
Very handy when working with characters or enums.
I think in D it's possible to create some library types which
allow an almost similar syntax. For example this one, briefly
written after reading your post:
----
import std.stdio;
// global variable to get rid of
https://issues.dlang.org/show_bug.cgi?id=11877
CharSet charSet;
struct CharSet
{
private string str;
public:
typeof(this) opSlice(char lo, char hi)
{
CharSet result;
foreach(c; lo .. hi)
result.str ~= c;
return result;
}
typeof(this) opSlice(char lohi)
{
CharSet result;
result.str ~= lohi;
return result;
}
bool opIn_r(char elem)
{
if (str == "")
return false;
else
return ((elem >= str[0]) & (elem <= str[$-1]));
}
string toString()
{
return str;
}
}
void main(string args[])
{
auto a2k = charSet['a' .. 'k'+1];
auto A2K = charSet['A' .. 'K'+1];
auto Z29 = charSet['0' .. '9'+1];
assert( 'a' in a2k );
assert( !('x' in a2k) );
assert( 'A' in A2K );
assert( !('X' in A2K) );
import std.conv;
assert( to!string(Z29) == "0123456789" );
assert( 'x' in charSet['x'..'x'+1] );
}
----
More information about the Digitalmars-d-learn
mailing list