First-class functions: Difference between revisions

Updated both D entries
(Updated both D entries)
Line 578:
=={{header|D}}==
===Using Standard Compose===
<lang d>void main() {
We need wrappers because the standard functions have different signatures (eg pure/nothrow).
<lang d> import std.stdio, std.math, std.typetuple, std.functional;
 
alias dir = TypeTuple!(sin, cos, cube)x dir=> x ^^ 3);
enum sin = (in real x) => std.math.sin(x),
alias inv = TypeTuple!(asin, acos, cbrt) inv;
asin = (in real x) => std.math.asin(x),
// foreach (if, fg; staticZip!(dir), {inv))
cos = (in real x) => std.math.cos(x),
foreach (immutable i, f; dir)
acos = (in real x) => std.math.acos(x),
cube = (in real x) => x ^^ 3,
cbrt = (in real x) => std.math.cbrt(x);
 
void main() {
alias TypeTuple!(sin, cos, cube) dir;
alias TypeTuple!(asin, acos, cbrt) inv;
foreach (i, f; dir) {
writefln("%6.3f", compose!(f, inv[i])(0.5));
}
}</lang>
{{out}}
Line 599 ⟶ 591:
0.500
0.500</pre>
===Defining Compose===
Same output:
<lang d>T delegate(S) compose(T, U, S)(in T function(in U) f,
in U function(in S) g) {
return s => f(g(s));
}
 
===Defining Compose===
void main() {
WeHere we need wrappers because the standard functions have different signatures (eg pure/nothrow). Same output.
<lang d>void main() {
import std.stdio, std.math, std.range;
 
immutablestatic sinT delegate(S) = compose(inT, realU, xS)(in =>T sinfunction(xin U) f,
asin = (in real x) => asin in U function(xin S), g) {
return cos s => f(in real xg(s) => cos(x),;
}
acos = (in real x) => acos(x),
 
cube = (in real x) => x ^^ 3,
immutable sin cbrt = (in real x) pure nothrow => cbrt(x);.sin,
asin = (in real x) pure nothrow => std.mathx.asin(x),
cos = (in real x) pure nothrow => std.mathx.cos(x),
acos = (in real x) pure nothrow => std.mathx.acos(x),
cube = (in real x) pure nothrow => x ^^ 3,
cbrt = (in real x) /*pure*/ nothrow => std.mathx.cbrt(x);
 
foreach (f, g; zip([sin, cos, cube], .zip([asin, acos, cbrt]))
writefln("%6.3f", compose(f, g)(0.5));
}</lang>