digitalmars.D - Cool tricks with D
- Andrej Mitrovic <andrej.mitrovich gmail.com> Jan 06 2012
- Walter Bright <newshound2 digitalmars.com> Jan 06 2012
- Trass3r <un known.com> Jan 06 2012
Someone wanted the 'in' operator to work for array literals on IRC.
This has been discussed before but ultimately rejected. Still, there
are ways to achieve similar syntax via some cool D tricks. Here's
mine:
module test;
import std.algorithm;
import std.stdio;
import std.range;
import std.conv;
string assign(size_t len)
{
string result;
foreach (i; 0 .. len)
result ~= "arr[" ~ to!string(i) ~ "] = vals[" ~ to!string(i) ~ "];";
return result;
}
auto makeArray(T...)(T vals)
{
T[0][T.length] arr = void;
mixin(assign(T.length));
return arr.dup;
}
struct OpIn(E)
{
E[] arr;
bool opIn_r(T)(T t) {
return arr.canFind(t);
}
}
struct A
{
static auto opIndex(T...)(T vals)
{
alias T[0] E;
return OpIn!E(makeArray(vals));
}
}
bool test(int val) { return val in A [4, 5]; }
enum x = test(5);
enum y = test(6);
static assert(x is true);
static assert(y is false);
void main()
{
assert(1 in A [1, 2]);
assert(2.0 in A [1.0, 2.0]);
}
Works at CTFE too! Note that I've had to use .dup to assign from stack
to heap, this is only because I get an ICE with the following code:
http://www.ideone.com/SIfLP
The ICE is: Internal error: ..\ztc\cgcs.c 354
If you've got a D trick show it!
Jan 06 2012
On 1/6/2012 8:39 AM, Andrej Mitrovic wrote:Works at CTFE too! Note that I've had to use .dup to assign from stack to heap, this is only because I get an ICE with the following code: http://www.ideone.com/SIfLP The ICE is: Internal error: ..\ztc\cgcs.c 354
Please post to bugzilla!
Jan 06 2012
The ICE is: Internal error: ..\ztc\cgcs.c 354
Please post to bugzilla!
http://d.puremagic.com/issues/show_bug.cgi?id=4414
Jan 06 2012









Walter Bright <newshound2 digitalmars.com> 