The code below causes a crash. What is the idiomatic way to merge associative arrays? If there is a simple version that allows the value at a key to be clobbered by the value of the right hand operand when there is a collision, that is a start.

import std.stdio;
void main() {
  double[string] a = [ "foo" : 22.2 ];
  double[string] b = [ "bar" : 22.2 ];
  writeln(a+b);
}


Is there a way to do something like this and have opApply be called for '+'?
If so, is it a bad idea?

import std.stdio;

double[string] opApply(string op)(const double[string][] inputs ...)
  if(op == "+") {
  double[string] result;
  foreach( map ; inputs ) {
    foreach( key, value ; map ) {
      auto pval = key in result;
      if(pval) {
        *pval += value;
      } else {
        result[key] = value;
      }
    }
  }
  return result;
}

void main() {
  double[string] a = [ "foo" : 22.2 ];
  double[string] b = [ "bar" : 22.2 ];
  double[string] c = [ "bar" : 5 ];
  auto d = a+b+c;
}

Reply via email to