Code shared from run.dlang.io. Run with ‘-main -unittest -dip1000’

Home   »   Code shared from run.dlang.io. Run with ‘-main -unittest -dip1000’

V!T v(T)(T[] values...) { return V!T(values); }
struct V(T)
{
    private T[] values;
    alias values this;
    
    this(T[] values...) { this.values = values; }
    
    typeof(mixin("T.init ", op, " typeof(S.init[0]).init"))[] opBinary(string op, S)(return scope S rhs) return
        in (rhs.length == values.length)
    {
        auto result = new typeof(return)(values.length);
        foreach (i, ref x; result)
        {
            x = mixin("values[i] ", op, " rhs[i]");
        }
        return result;   
    }
    
    typeof(mixin("typeof(S.init[0]).init ", op, " T.init"))[] opBinaryRight(string op, S)(return scope S lhs) return
        if (!is(S : V!X, X))
        in (lhs.length == values.length)
    {
        auto result = new typeof(return)(values.length);
        foreach (i, ref x; result)
        {
            x = mixin("lhs[i] ", op, " values[i]");
        }
        return result;   
    }
}

@safe unittest
{
    auto a = [1,2,3].v + [4,5,6];
    static assert(is(typeof(a) == int[]));
    assert(a == [5,7,9]);
    
    enum as = ["a": 1, "b": 3];
    enum bs = ["a": 3, "c": 2];
    auto ps = ["a", "b"].v in [ as, bs ];
	static assert(is(typeof(ps) == int*[]));
    assert(ps.length == 2);
    assert(ps[0] !is null && *ps[0] == 1);
    assert(ps[1] is null);
    
    auto b = ['a', 'B', '3'] ~ ["bc", "CDE", "4567"].v;
    static assert(is(typeof(b) == string[]));
    assert(b == ["abc", "BCDE", "34567" ]);
}

Leave a Reply

Your email address will not be published.