我对创建一个函数 Derivative 很感兴趣,它返回一个函数,该函数是在某个时刻传递给它的某个函数的导数。但是,我希望能够对此进行专门化,以便针对特定函数返回解析解。
所以,我正在寻找这样的东西:
auto Derivate(alias Function)(x)
{ return (Function(x+h) - Function(x-h))/(2h);}
auto Derivate(BSpline!(k)(x))(x)
{ return k * BSpline!(k-1)(x) + x * BSpline!(k-1)(x); }
但是,我目前以这种方式定义 BSpline:
pure Real BSpline(int k : 0, Real)(scope Real x, scope const(Real)[] t)
{
if (t[0] <= x && x < t[k+1])
return 1;
else
return 0;
}
pure Real BSpline(int k, Real)(scope Real x, scope const(Real)[] t)
{
if (t[0] <= x && x < t[k+1])
{
Real a = (x - t[0]) / (t[k] - t[0]);
Real b = (t[k+1] - x) / (t[k+1] - t[1]);
Real c = BSpline!(k-1,Real)(x, t[0..k+1]);
Real d = BSpline!(k-1,Real)(x, t[1..k+2]);
Real rv = (c?c*a:c) + (d?d*b:d);
return rv;
}
else
return 0;
}
所以 BSpline 上的类型签名将是 Real function(Real,Real),它与任何其他类型的函数都没有区别。解决这个问题的方法是创建一个定义了 opCall 的“BSpline”类吗?或者我可以做一些 typedef 来识别这个函数吗?
谢谢!
最佳答案
要专门化模板,您必须使用 :
符号:
auto foo(alias F_, X_)(X_ x) {
/* code here ... */
}
auto foo(alias F_ : BSpline, X_)(X_ x) {
/* specialized version here */
}
关于functional-programming - D中函数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6806025/