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

Content added Content deleted
(rewrite with an attempted understanding of the new problem statement)
Line 110: Line 110:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio: writefln;
{{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() {
void main() {
auto x = 2.0;
auto x = 2.0;
auto xi = 0.5;
auto y = 4.0;
auto y = 4.0;
auto forward = [x, y, x + y ];
auto yi = 0.25;
auto reverse = map!"1 / a"(forward);
auto z = x + y;
auto zi = 1.0 / (x + y);

auto multiplier = (double a, double b) {
auto multiplier = (double a, double b) {
return (double m){ return a * b * m; };
return (double m){ return a * b * m; };
};
};

foreach(i, a; forward) {
auto forward = [x, y, z];
auto reverse = [xi, yi, zi];

foreach (i, a; forward) {
auto b = reverse[i];
auto b = reverse[i];
writeln("(", a ," * ", b, ")(0.5) = ", multiplier(a, b)(0.5));
writefln("%f * %f * 0.5 = %f", a, b, multiplier(a, b)(0.5));
}
}
}</lang>
}
</lang>

Output:
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.500000</pre>
Alternative implementation (same output):
<lang d>import std.stdio, std.range;


(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() {
void main() {
auto forward = [(real x){ return sin(x); },
auto 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 reverse = [(real x){ return asin(x); },
auto multiplier = (double a, double b) {
(real x){ return acos(x); },
return (double m){ return a * b * m; };
};
(real x){ return x ^^ (1 / 3.0); }];


auto compose = (real delegate(real) a, real delegate(real) b) {
auto forward = [x, y, 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}}==
=={{header|E}}==