Beg*_*udy 1 f# operator-overloading
我这样做了:
let (-) (m:float[]) (n:float[])= [| for i = 0 to Array.length m - 1 do yield m.[i]-n.[i] |]
Run Code Online (Sandbox Code Playgroud)
但是,为什么这是错的?!
let y=1.0-0.0
Run Code Online (Sandbox Code Playgroud)
那之前还可以!
Error 1 This expression was expected to have type float [] but here has type float E:\MyDocuments\Visual Studio 2010\Projects\curve intersection\newton\Module1.fs 28 7 newton
Error 2 This expression was expected to have type float [] but here has type float E:\MyDocuments\Visual Studio 2010\Projects\curve intersection\newton\Module1.fs 28 11 newton
Run Code Online (Sandbox Code Playgroud)
我认为(m:float [])(n:float [])设置参数类型,为什么1.0-0.0,浮点浮点数,不去使用( - )浮点浮点数 - >浮点数???
您完全重新定义了-运算符.
如果你想扩充你自己的一个类型-,你可以这样做(内置运算符定义将选择一个类型的成员).但我认为没有任何方法可以在内置/现有类型上定义现有的运算符,这些运算符不会完全影响内置运算符定义.
您可以使用本地let绑定临时阴影-来处理浮点数组,也可以改为定义新的运算符.例子:
// locally shadow
let f() =
let (-) (a:float[]) (b:float[]) = ...
// use (-) on arrays for a moment
// use (-) as normal
Run Code Online (Sandbox Code Playgroud)
和
// new operator
let (-@) (a:float[]) (b:float[]) = ...
[|1.0|] -@ [|2.0|] // my new op
1.0 - 2.0 // minus as normal
Run Code Online (Sandbox Code Playgroud)