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

no edit summary
m (copy edit - wiki link to wikipedia)
No edit summary
Line 107:
(#<FUNCTION ACOS> ∘ #<FUNCTION COS>)(0.5) = 0.5
(#<FUNCTION CUBE-ROOT> ∘ #<FUNCTION CUBE>)(0.5) = 0.5
 
=={{header|D}}==
 
<lang d>import std.stdio, std.algorithm;
void main() {
auto x = 2.0;
auto y = 4.0;
auto forward = [x, y, x + y ];
auto reverse = map!"1 / a"(forward);
auto multiplier = (double a, double b) {
return (double m){ return a * b * m; };
};
foreach(i, a; forward) {
auto b = reverse[i];
writeln("(", a ," * ", b, ")(0.5) = ", multiplier(a, b)(0.5));
}
}
</lang>
 
Output:
 
(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 forward = [(real x){ return sin(x); },
(real x){ return cos(x); },
(real x){ return x * x * x; }];
 
auto reverse = [(real x){ return asin(x); },
(real x){ return acos(x); },
(real x){ return x ^^ (1 / 3.0); }];
 
auto compose = (real delegate(real) a, real delegate(real) b) {
return (real x){ return a(b(x)); };
};
 
foreach(i, a; forward) {
writeln(compose(a, reverse[i])(0.5));
}
}
</lang>
 
Output:
 
0.5
0.5
0.5
 
=={{header|E}}==
Anonymous user