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}}== |
||
⚫ | |||
{{incorrect|D|Compare and contrast the resultant program with the corresponding entry in First-class functions.}} |
|||
⚫ | |||
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 |
auto yi = 0.25; |
||
auto |
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; }; |
||
}; |
}; |
||
⚫ | |||
auto forward = [x, y, z]; |
|||
auto reverse = [xi, yi, zi]; |
|||
⚫ | |||
auto b = reverse[i]; |
auto b = reverse[i]; |
||
writefln("%f * %f * 0.5 = %f", a, b, multiplier(a, b)(0.5)); |
|||
} |
} |
||
⚫ | |||
} |
|||
⚫ | |||
Output: |
Output: |
||
<pre>2.000000 * 0.500000 * 0.5 = 0.500000 |
|||
4.000000 * 0.250000 * 0.5 = 0.500000 |
|||
⚫ | |||
Alternative implementation (same output): |
|||
⚫ | |||
(2 * 0.5)(0.5) = 0.5 |
|||
(4 * 0.25)(0.5) = 0.5 |
|||
⚫ | |||
⚫ | |||
void main() { |
void main() { |
||
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 zi = 1.0 / (x + y); |
|||
auto multiplier = (double a, double b) { |
|||
return (double m){ return a * b * m; }; |
|||
⚫ | |||
(real x){ return x ^^ (1 / 3.0); }]; |
|||
auto forward = [x, y, z]; |
|||
auto reverse = [xi, yi, zi]; |
|||
return (real x){ return a(b(x)); }; |
|||
⚫ | |||
⚫ | |||
writeln(compose(a, reverse[i])(0.5)); |
|||
} |
|||
} |
|||
⚫ | |||
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 |
|||
⚫ | |||
=={{header|E}}== |
=={{header|E}}== |