我有一个自定义类型的数字关联,如下所示:
let DiffNumerics =
{ new INumeric<Diff> with
member op.Zero = C 0.0
member op.One = C 1.0
member op.Add(a,b) = a + b
member op.Subtract(a,b) = a - b
member op.Multiply(a,b) = a * b
member ops.Negate(a) = Diff.negate a
member ops.Abs(a) = Diff.abs a
member ops.Equals(a, b) = ((=) a b)
member ops.Compare(a, b) = Diff.compare a b
member ops.Sign(a) = int (Diff.sign a).Val
member ops.ToString(x,fmt,fmtprovider) = failwith "not implemented"
member ops.Parse(s,numstyle,fmtprovider) = failwith "not implemented"
}
GlobalAssociations.RegisterNumericAssociation(DiffNumerics)
它在 f# 交互中运行良好,但在我运行时崩溃,因为 .ElementOps 未正确填充这些类型的矩阵。任何想法为什么会这样?
编辑:
在 fsi 中,代码
let A = dmatrix [[Diff.C 1.;Diff.C 2.;Diff.C 3.];[Diff.C 4.;Diff.C 5.;Diff.C 6.]]
let B = matrix [[1.;2.;3.];[4.;5.;6.]]
给出:
> A.ElementOps;;
val it : INumeric<Diff> = FSI_0003.NewAD+DiffNumerics@258
> B.ElementOps;;
val it : INumeric<float> = Microsoft.FSharp.Math.Instances+FloatNumerics@115
>
在调试器 A.ElementOps 中显示:
'(A).ElementOps' threw an exception of type 'System.NotSupportedException'
并且,对于 B 矩阵:
Microsoft.FSharp.Math.Instances+FloatNumerics@115
所以不知何故 DiffNumerics 并没有进入编译程序。