F # surcharge de l'opérateur de recherche dynamique (?)
-
06-07-2019 - |
Question
Impossible de définir (?) la surcharge de l'opérateur sur le 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'.
Tout fonctionne bien si j'utilise la let-binding autonome pour la définition d'opérateur:
let (?) (foo : Foo) (name : string) = foo.s + name
let hw = foo? world
Mais je dois spécifier l'opérateur op_Dynamic
directement pour le type Foo
. Quel est le problème avec le premier extrait de code?
Utilisation de F # 1.9.7.4
@ Visual Studio 2010 Beta2
La solution
Peut-être y a-t-il un moyen plus facile (je regarderai), mais cela suffira:
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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow