开发者

F# dynamic lookup operator (?) overloading

Can't define (?) operator overload on type:

type Foo =
     val s : string
     new(s) = { s = s }
     static member (?) (foo : Foo, name : string) = foo.s + name

let foo = Foo("hello, ")
let hw  = foo? world

// error FS0043: The member or object constructor 'op_Dynamic'
// takes 2 argument(s) but is here given 1. The required signature
// is 'static member Foo.( ? ) : foo:Foo * name:string -> string'.

All works fine if I use standalone let-binding for operator definition:

let (?) (foo : Foo) (name : string) = foo.s + name

let hw  = foo? world

But I need to specify op_Dynamic operator directly for type Foo. What's wrong with the first code snippet?

开发者_如何学JAVA

Using F# 1.9.7.4 @ Visual Studio 2010 Beta2


Perhaps there is an easier way (I'll look), but this will do in a pinch:

type Foo =     
    val s : string     
    new(s) = { s = s }     
    static member (?)(foo : Foo, name : string) = 
        foo.s + name

let inline (?) (o:^T) (prop:string) : ^U =
    (^T : (static member (?) : ^T * string -> ^U)(o,prop))

let foo = Foo("hello, ")
let hw  = foo ? world 
printfn "%s" hw
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜