Daniel Davidson:

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;
}

In D operators need to be defined inside structs/classes.

So write a function, it could have signature as:

TV[TK] mergeAAs(TK, TV)(TV[TK] aas...) {

It seems even fit for Phobos.

Bye,
bearophile

Reply via email to