How to instantiate a map with multiple functions
Jay Norwood via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Dec 26 19:22:50 PST 2015
I'm playing around with something also trying to apply multiple
functions.
In my case, a sample is some related group of measurements taken
simultaneously, and I'm calculating a group of metrics from the
measured data of each sample.
This produces the correct results for the input data, and it
seems pretty clear what functions are being applied.
I would probably want to associate names with the tuple metric
results, and I've seen that somewhere in the docs in parameter
tuples. I suppose I'll try those in place of the current tuple
...
import std.stdio;
import std.algorithm;
import std.conv;
import std.range;
import std.typecons;
struct S { ulong a; ulong b; ulong c; ulong d; double e; ulong f;}
ulong f1(ref S s) { with(s){return a+b;}}
double f2(ref S s) { with(s){return (c+d)/e;}}
double f3(ref S s) { with(s){return (c+f)/e;}}
int main()
{
S[10] samples;
// initialize some values
foreach ( int i, ref s; samples){
int j=i+1;
with (s){
a=j; b=j*2; c=j*3; d=j*4; e=j*10; f=j*5;
}
}
// apply several functions on each sample
samples.each!((int i, ref
a)=>tuple(i,f1(a),f2(a),f3(a)).writeln());
return 0;
}
========== output is
Tuple!(int, ulong, double, double)(0, 3, 0.7, 0.8)
Tuple!(int, ulong, double, double)(1, 6, 0.7, 0.8)
Tuple!(int, ulong, double, double)(2, 9, 0.7, 0.8)
Tuple!(int, ulong, double, double)(3, 12, 0.7, 0.8)
Tuple!(int, ulong, double, double)(4, 15, 0.7, 0.8)
Tuple!(int, ulong, double, double)(5, 18, 0.7, 0.8)
Tuple!(int, ulong, double, double)(6, 21, 0.7, 0.8)
Tuple!(int, ulong, double, double)(7, 24, 0.7, 0.8)
Tuple!(int, ulong, double, double)(8, 27, 0.7, 0.8)
Tuple!(int, ulong, double, double)(9, 30, 0.7, 0.8)
More information about the Digitalmars-d-learn
mailing list