On Wednesday, 21 November 2012 at 18:15:51 UTC, Walter Bright wrote:
On 11/21/2012 10:02 AM, John Colvin wrote:
My vision of how things could work:
c = a[] opBinary b[];
should be legal. It should create a new array that is then reference assigned to c.

This is not done because it puts excessive pressure on the garbage collector. Array ops do not allocate memory by design.

But if they wanted it anyways, could implement it as a struct... Here's a rough build... Should be fairly obvious what's happening.

struct AllocatingVectorArray(T) {
  T[] data;
  alias data this;
  alias AllocatingVectorArray AVA;

  //forces slice operations for vector format only
  static struct AVASlice {
    T[] data;
    alias data this;

    this(T[] rhs) {
      data = rhs;
    }

    AVA opBinary(string op)(const AVASlice rhs) {
assert(rhs.length == data.length, "Lengths don't match, cannot use vector operations");

      AVA var; var.data = data.dup;
      mixin("var[] " ~ op ~ "= rhs[];");

      return var;
    }
  }

  this(T[] rhs) {
    data = rhs;
  }

  ref AVA opAssign(T[] rhs) {
    data = rhs;
    return this;
  }

  AVASlice opSlice() {
    return AVASlice(this);
  }
}

unittest {
  alias AllocatingVectorArray!int AVAint;
  AVAint a = [1,2,3,4];
  AVAint b = [5,6,7,8];

  AVAint c;

//  c = a + b; //not allowed, 'not implemented error'
//  assert(c == [6,8,10,12]);

  c = a[] + b[]; //known vector syntax
  assert(c == [6,8,10,12]);

  c[] = a[] + b[]; //more obvious what's happening
  assert(c == [6,8,10,12]);
}

Reply via email to