First-class functions: Difference between revisions

m
→‎{{header|D}}: correction
(→‎{{header|Ursala}}: Marked incorrect. Cube/cube root seem to be built-in or library functions rather than "user-created".)
m (→‎{{header|D}}: correction)
Line 261:
 
=={{header|D}}==
{{incorrect|D|No user-created function such as cube is used.}}
'''D 2.0 version''' of compose function (template).
<lang D>import std.stdio;
Line 285 ⟶ 284:
Example:
 
<lang D>voidprivate main()import std.math ;
import std.stdio ;
{
auto sinwrp = delegate (real x){ return sin(x);};
auto coswrp = delegate (real x){ return cos(x);};
auto sincos_n = delegate (real x) { return sin(cos(x)); };
auto sincos_r = compose(sinwrp, coswrp);
auto funcTbl = cast(real delegate(real) [])[sinwrp, coswrp, sincos_n, sincos_r];
 
T delegate(S) compose(T, U, S)(T delegate(U) f, U delegate(S) g) {
for (int i = 1; i <= 10; i++) {
return (S s) { real arg =return f(i*2.0*PIg(s)); / 10.0};
}
foreach (f; funcTbl)
 
writef ("%10f ", f(arg));
void main() {
writefln("");
// warper need as not all built-in real functions
}
// have same signature , eg pure/nothrow
auto sinwrp sin = delegate (real x) { return std.math.sin(x) ; } ;
auto sincos_nasin = delegate (real x) { return sin(cosstd.math.asin(x)) ; } ;
auto coswrp cos = delegate (real x) { return std.math.cos(x) ; } ;
auto acos = delegate (real x) { return std.math.acos(x) ; } ;
auto cube = delegate (real x) { return x*x*x ; } ;
auto cbrt = delegate (real x) { return std.math.cbrt(x) ; } ;
// built-in : sin/cos/asin/acos/cbrt user:cube
auto fun = [sin, cos, cube] ;
auto inv = [asin, acos, cbrt] ;
foreach(i, f ; fun)
writefln("%6.3f", compose(f, inv[i])(0.5)) ;
}</lang>
 
Anonymous user