Calculating/Averaging over a struct value
Timon Gehr
timon.gehr at gmx.ch
Wed Mar 21 10:40:48 PDT 2012
#! /usr/bin/rdmd
import std.array;
import std.csv;
import std.stdio;
import std.string;
struct Data{
string Date;
double d1;
double d2;
int i4;
}
double average(Data[] x, string para){
double result = 0.0;
theswitch:switch(strip(para)){
foreach(member;__traits(allMembers, Data)){
case member:
static if(__traits(compiles,
{result+=mixin(`x[0].`~member);})){
foreach(d; x){
result+=mixin(`d.`~member);
}
}else{
throw new Exception("don't know how to average
over "~para);
}
break theswitch;
}
default: throw new Exception("no member named "~para);
}
return result/x.length;
}
void main(){
Data[] allData;
string text= "2011-11-30,2.25,3.00,100\n2011-11-29,2.24,2.75,1000\r\n";
foreach(ob;csvReader!Data(text)){
allData ~= ob;
}
writeln(allData);
string input;
writeln("Enter the variable you would like to average over: ");
stdin.readln(input);
try writeln(average(allData,input));
catch(Exception e){writeln(e.msg);}
}
More information about the Digitalmars-d-learn
mailing list