F # dynamic search operator (?) Overload

It is impossible to determine (?) Operator overloading by 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'.

Everything works fine if I use stand-alone let-binding to define a statement:

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

let hw  = foo? world

But I need to specify the operator op_Dynamicdirectly for the type Foo. What happened to the first piece of code?

Using F# 1.9.7.4@Visual Studio 2010 Beta2

+3
source share
1 answer

There may be an easier way (I will look), but this will be done as a last resort:

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
+4
source

Source: https://habr.com/ru/post/1721018/


All Articles