F#动态查找运算符 (?) 的重载

3

在类型上无法定义 (?) 操作符重载:

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'.

如果我使用独立的 let-binding 来定义操作符,则一切都正常:
let (?) (foo : Foo) (name : string) = foo.s + name

let hw  = foo? world

但是我需要直接为类型Foo指定op_Dynamic运算符。第一段代码有什么问题吗?

使用F# 1.9.7.4@Visual Studio 2010 Beta2

1个回答

4
也许有更简单的方法(我会查找),但在紧急情况下可以使用这种方法:
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

2
更简单的方法?!?是的,它可以工作,但为什么我要将这个“内联(?)”解决方法放入任何具有重载(?)运算符的类中才能使用它呢?为什么我不能直接使用定义的运算符重载呢? - controlflow
1
是的,原來F#解析器中有一個錯誤,您的原始代碼應該可以運行。感謝您指出這一點!我已經提交了錯誤報告。 - Brian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接