Cool tricks with D

Andrej Mitrovic andrej.mitrovich at gmail.com
Fri Jan 6 08:39:11 PST 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!


More information about the Digitalmars-d mailing list