Calculating/Averaging over a struct value

Jesse Phillips Jessekphillips+D at gmail.com
Wed Mar 21 13:13:36 PDT 2012


On Wednesday, 21 March 2012 at 17:02:05 UTC, Brian Brady wrote:

> As per the commented section, I want to be able to dynamically 
> figure out,
> which member of the struct to average across, for all the 
> structs in the array.

Timon has given you an good example to get D to generate some 
code for you. I would also point out that combining your if block 
or even Timon's solution with a template:

double average(string param)(Data[] x)
{
  static if (!isNumeric!(typeof(mixin("Data."~param))))
    return -1;
  else
  {
   //auto average = reduce!("a."~param~" + b."~param)(x)/x.length;
   typeof(return) average = 0;
   foreach(v; x) {
	  mixin("average += v."~param~";");
   }
   return average/x.length;
  }
}

Note, I commented out reduce as it uses the array type instead of 
the calculation type. I think I'll file than as a bug. Also the 
reduce version would not give you a double back even if it did 
work, need a cast in there.

Now calculating the parameter is just

auto ans = average!"d1"(x);


More information about the Digitalmars-d-learn mailing list