无法扩展 F# 中的运算符?
module FSharp=
let Point2d (x,y)= Point2d(x,y)
let Point3d (x,y,z)= Point3d(x,y,z)
type NXOpen.Point3d with
static member ( * ) (p:Point3d,t:float)= Point3d(p.X*t,p.Y*t,p.Z*t)
static member ( * ) (t:float,p:Point3d)= Point3d(p.X*t,p.Y*t,p.Z*t)
static member (+) (p:Point3d,t:float)= Point3d(p.X+t,p.Y+t,p.Z+t)
static member (+) (t:float,p:Point3d)= Point3d(p.X+t,p.Y+t,p.Z+t)
static member (+) (p:Point3d,t:Point3d)= Point3d(p.X+t.X,p.Y+t.Y,p.Z+t.Z)
let a=Point3d (1.,2.,3.)
let b=1.0
let c=a * b//error
错误 15:类型“float”与类型不匹配
'Point3d' E:\Work\extension-RW\VS\extension\NXOpen.Extension.FSharp\Module1.fs 18 13 NXOpen.Extension.FSharp
我想扩展 Point3d 方法,一些新的运算符。但它并没有过去。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果
Point3d
类型是在无法修改的单独程序集中声明的,那么(不幸的是)无法实现标准运算符的新重载,例如+
或<代码>*。您问题中的代码将运算符添加为扩展方法,但 F# 编译器在查找重载运算符时不会搜索扩展方法。如果您无法修改该库,那么您可以执行以下三件事:
为
Point3d
创建一个包装器,用于存储Point3d
的值并实现所有运营商(但这可能效率很低)
定义不与内置运算符冲突的新运算符。例如,您可以使用
+$
和$+
从左到右乘以标量。要声明这样的运算符,您可以编写:实现您自己的
Point3d
类型来完成所有工作,可能会使用一个转换函数,在需要时将其转换为Point3d
调用库。很难说哪个选项是最好的 - 第二种方法可能是最有效的,但它会让代码看起来有点难看。根据您的情况,选项 1 或 3 也可能有效。
If the
Point3d
type is declared in a separate assembly that you can't modify, then there is (unfortunately) no way to implement new overloads of the standard operators like+
or*
. The code in your question adds operators as extension methods, but the F# compiler doesn't search for extension methods when looking for overloaded operators.If you can't modify the library, then there are three things you can do:
Create a wrapper for
Point3d
that stores a value ofPoint3d
and implements all the operators(but this is likely going to be quite inefficient)
Define new operators that do not clash with the built-in ones. For example, you can use
+$
and$+
for multiplication by scalar from the left and right. To declare such operator, you would write:Implement your own
Point3d
type that does all the work, possibly with a conversion function that turns it intoPoint3d
when you need to call a library.It is hard to tell which option is the best - the second approach is probably the most efficient, but it will make code look a bit uglier. Depending on your scenario, the option 1 or 3 may work too.
确实有可能。
有一种方法可以使用唯一的和 鲜为人知的三元运算符
?<-
。因此,根据您的情况,您可以尝试以下操作:现在您可以尝试:
Indeed it is possible.
There is a way to extend binary operators using the one and only and little known ternary operator
?<-
. So in your case you can try this:Now you can try: