pure function of functions that returns functions in D

浪子不回头ぞ 提交于 2019-12-24 01:23:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!