[英]Functional programming in D trouble
我在D中創建有效的模板時遇到了麻煩:
pure T BSpline(int k:1, T)(in T x, in T[] t)
{
if (t[0] <= x && x < t[k])
return 1;
else
return 0;
}
pure T BSpline(int k, T)(in T x, in T[] t)
{
if (t[0] <= x && x < t[k])
{
T a = (x - t[0]) / (t[k-1] - t[0]);
T b = (t[k] - x) / (t[k] - t[1]);
return a * BSpline!(k-1,T)(x, t[0..k-1]) + b * BSpline!(k-1,T)(x, t[1..k]);
}
else
return 0;
}
然后我的單元測試:
unittest {
real a = .5;
real[] b = [0,0,1,2,3];
assert(BSpline!(1,real)(a,b[0..2]) == 0);
assert(BSpline!(2,real)(a,b[0..3]) == .5);
assert(BSpline!(3,real)(a,b[0..4]) == .625);
assert(BSpline!(4,real)(a,b[0..5]) == 0.260417);
}
失敗並顯示以下錯誤:
bspline.d(18): Error: template BSplineBasis.BSpline(int k : 1,T) does not match any function template declaration
bspline.d(18): Error: template BSplineBasis.BSpline(int k : 1,T) cannot deduce template function from argument types !(1,real)(const(real),const(real[]))
bspline.d(18): Error: template instance errors instantiating template
我不會問,但是,我不明白為什么D很難從相當明確的參數類型推導模板函數...
我究竟做錯了什么。
如果應該在代碼審閱堆棧交換中而不是在此處進行交換,請告訴我,但是我希望這對模板的工作方式造成誤解,而不是錯誤。
我現在無法測試,但是我認為這是因為in T[]
是scope const T[]
,這是scope const(T[])
,這對每個人來說都比scope const(T)[]
,同時幾乎沒有任何好處。
嘗試改變
in T x, in T[] t
至
scope T x, scope const(T)[] t
在參數列表中,查看是否可以解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.