Function Composition
atzensepp
webwicht at web.de
Wed Jan 24 21:12:20 UTC 2024
Some progress: compose function needs to know type but templates
help to create for different types.
```d
import std.stdio;
import std.container.array;
// Function composition:
int f(int x) { return x*2;} ;
int g(int x) { return x+2;} ;
double ff(double x) { return x*x;} ;
double gg(double x) { return 2+x;} ;
template Delegate(T)
{
T delegate(T) compose( T function(T)second, T function(T )first)
{
return ((T i) => second(first(i)));
}
}
void main()
{
alias c = Delegate!(int);
writeln( c.compose(&f,&g)(2));
writeln( c.compose(&g,&f)(2));
alias d = Delegate!(double);
writeln( d.compose(&ff,&gg)(2));
writeln( d.compose(&gg,&ff)(2));
}
```
Compose function gets 2 pointers to functions and yield a
delegate.
The created delegate can be invoked. However it cannot be passed
to the composition function. This:
```d
int delegate (int) fg = c.compose(&f,&g);
int delegate (int) fgf = c.compose(fg,&f);
writeln( fgf(2));
```
leads to:
```
lambda2.d:41:37: error: function lambda2.Delegate!int.compose
(int function(int) second, int function(int) first) is not
callable using argument types (int delegate(int), int
function(int x))
int delegate (int) fgf = c.compose(fg,&f);
```
what a bummer!
More information about the Digitalmars-d-learn
mailing list