[英]How to do Operator Overloading?
I did this : 我是这样做的:
let (-) (m:float[]) (n:float[])= [| for i = 0 to Array.length m - 1 do yield m.[i]-n.[i] |]
But, why this is wrong?! 但是,为什么这是错误的?
let y=1.0-0.0
That is ok before! 没关系!
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
I think (m:float[]) (n:float[]) is set the parameters type , why 1.0-0.0, float float, not go to use (-) float float->float??? 我认为(m:float [])(n:float [])设置了参数类型,为什么是1.0-0.0,float float,而不去使用(-)float float-> float ???
You completely redefined the -
operator. 您完全重新定义了
-
运算符。
If you want to augment one of your own types to work with -
, you can do that (the builtin operator definitions will pick up members on a type). 如果要扩充自己的类型之一以使用
-
,则可以这样做(内置的运算符定义将选择类型的成员)。 But I don't think there's any way to define existing operators on builtin/existing types that doesn't completely shadow the builtin operator definition. 但是我不认为有任何方法可以在内置/现有类型上定义现有的运算符,而不会完全掩盖内置运算符的定义。
You can either use a local let
binding to temporarily shadow -
to work on float arrays, or you can define a new operator instead. 您可以使用本地
let
绑定来临时阴影-
以在float数组上工作,也可以定义一个新的运算符。 Examples: 例子:
// locally shadow
let f() =
let (-) (a:float[]) (b:float[]) = ...
// use (-) on arrays for a moment
// use (-) as normal
and 和
// new operator
let (-@) (a:float[]) (b:float[]) = ...
[|1.0|] -@ [|2.0|] // my new op
1.0 - 2.0 // minus as normal
You added an operator overload for the type float[]
. 您为
float[]
类型添加了运算符重载。 In the sample code though you are trying to subject 2 float
values which doesn't work. 在示例代码中,尽管您尝试使用2个不起作用的
float
值。 Try the following 尝试以下
let y = [|1.0|] - [|0.0|]
The [| ... |]
[| ... |]
[| ... |]
syntax is used to create an array of values. [| ... |]
语法用于创建值数组。 In the above case it creates two float[]
each with a single float
value. 在上述情况下,它将创建两个
float[]
每个都有一个单独的float
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.