First-class functions/Use numbers analogously: Difference between revisions

(rewrite with an attempted understanding of the new problem statement)
Line 110:
 
=={{header|D}}==
<lang d>import std.stdio,: std.mathwritefln;
{{incorrect|D|Compare and contrast the resultant program with the corresponding entry in First-class functions.}}
 
<lang d>import std.stdio, std.algorithm;
void main() {
auto x = 2.0;
auto xi = 0.5;
auto y = 4.0;
auto forwardyi = [x, y, x + y ]0.25;
auto reversez = map!"1x /+ a"(forward)y;
auto zi = 1.0 / (x + y);
 
auto multiplier = (double a, double b) {
return (double m){ return a * b * m; };
};
 
foreach(iauto forward = [x, a; forward)y, { z];
auto reverse = [xi, yi, zi];
 
foreach (i, a; forward) {
auto b = reverse[i];
writelnwritefln("(",%f a* ,"%f * ", b, ")(0.5) = %f", a, b, multiplier(a, b)(0.5));
}
}</lang>
}
</lang>
 
Output:
<pre>2.000000 * 0.500000 * 0.5 = 0.500000
4.000000 * 0.250000 * 0.5 = 0.500000
(6.000000 * 0.166667)( * 0.5) = 0.5500000</pre>
Alternative implementation (same output):
<lang d>import std.stdio, std.algorithmrange;
 
(2 * 0.5)(0.5) = 0.5
(4 * 0.25)(0.5) = 0.5
(6 * 0.166667)(0.5) = 0.5
 
<lang d>import std.stdio, std.math;
void main() {
auto forwardx = [(real x){ return sin(x)2.0; },
auto xi = 0.5;
(real x){ return cos(x); },
auto y = 4.0;
(real x){ return x * x * x; }];
auto yi = 0.25;
auto z = x + y;
auto zi = 1.0 / (x + y);
 
auto reversemultiplier = [(realdouble x){a, returndouble asin(xb); },{
return (double m){ return a * b * (real x){ return acos(x)m; },;
};
(real x){ return x ^^ (1 / 3.0); }];
 
auto composeforward = (real[x, delegate(real) ay, real delegate(real) b) {z];
auto reverse = [xi, yi, zi];
return (real x){ return a(b(x)); };
};
 
foreach(i, a; forward) {
writeln(compose(a, reverse[i])(0.5));
}
}
</lang>
 
Output:
 
foreach (f; zip(forward, reverse))
0.5
writefln("%f * %f * 0.5 = %f", f.at!0, f.at!1,
0.5
multiplier(f.at!0, f.at!1)(.5));
0.5
}</lang>
 
=={{header|E}}==
Anonymous user