www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Cool tricks with D

reply Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
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
next sibling parent Walter Bright <newshound2 digitalmars.com> writes:
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
prev sibling parent Trass3r <un known.com> writes:
 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