问题
I'm trying to create a pure function that returns the multiplication of two other pure functions:
pure Func multiplyFunctions(Func,Real)(scope const Func f1, scope const Func f2)
{
return (Real a) { return f1(a) * f2(a); };
}
Unfortunately, I'm running into problems, number one, I want to declare f1 and f2 to be pure functions/delegates/classes with opCall defined... which is required because I'm calling them from a pure function.
But number two, and what seems to be the most problematic, is that I want f1 and f2 to be functions of one, "Real" variable that return one "Real" value... but I can't figure out how to template this out...
Anyone have any ideas?
回答1:
First of all, remove the scope
; it's wrong, because the scopes of the delegates are escaped.
Second, try something like:
real delegate(real) multiplier(const real delegate(real) pure f1,
const real delegate(real) pure f2) pure
{
real multiply(real val) { return f1(val) * f2(val); }
return &multiply;
}
You can also try doing this with templates, although there's not much of a reason to:
pure auto multiplier(alias F1, alias F2)(ParameterTypeTuple!F1 args)
{
return F1(args) * F2(args);
}
real square(real a) pure { return a * a; }
alias multiplier!(square, square) squareMultiplier;
//Now squareMultiplier is a multiplier of square()
Note that there are bugs in the compiler that don't allow purity to be 100% correct, so you'll just have to put up with them for now.
来源:https://stackoverflow.com/questions/6805566/pure-function-of-functions-that-returns-functions-in-d