Question

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?

Using F# 1.9.7.4 @ Visual Studio 2010 Beta2

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top