无法在F#中扩展运算符? [英] Could not extend operators in F#?

查看:110
本文介绍了无法在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

Error 15: The type 'float' does not match the type
'Point3d' E:\Work\extension-RW\VS\extension\NXOpen.Extension.FSharp\Module1.fs 18 13 NXOpen.Extension.FSharp

我想扩展Point3d方法,一些新的运算符.但这并没有过去.

I want to extend the Point3d methods, some new operators. But it doesn't pass over.

推荐答案

实际上是可能的. 有一种方法可以使用one and only和

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:

type SumPoint3d = SumPoint3d with
    static member        (?<-) (p:Point3d, SumPoint3d, t        ) = Point3d(p.X + t  , p.Y + t  , p.Z + t  )
    static member        (?<-) (t        , SumPoint3d, p:Point3d) = Point3d(p.X + t  , p.Y + t  , p.Z + t  )
    static member        (?<-) (p:Point3d, SumPoint3d, t:Point3d) = Point3d(p.X + t.X, p.Y + t.Y, p.Z + t.Z)
    static member inline (?<-) (a        , SumPoint3d, b        ) = a + b

type ProdPoint3d = ProdPoint3d with    
    static member        (?<-) (p:Point3d, ProdPoint3d, t        ) = Point3d(p.X * t, p.Y * t, p.Z * t)
    static member        (?<-) (t        , ProdPoint3d, p:Point3d) = Point3d(p.X * t, p.Y * t, p.Z * t)
    static member inline (?<-) (a        , ProdPoint3d, b        ) = a * b

let inline ( + ) a b =  a ? (SumPoint3d ) <- b
let inline ( * ) a b =  a ? (ProdPoint3d) <- b

let a=Point3d (1.,2.,3.) 
let b=1.0

现在您可以尝试:

> let c=a * b ;;
val c : Point3d = Point3d (1.0,2.0,3.0)

>  2 * 3 ;;
val it : int = 6

这篇关于无法在F#中扩展运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆