简体   繁体   中英

F#: Member constraints to help create seemingly dynamic types

I've been looking into a way to add some duck typing to an F# method.

SomeMethod(model:'a) =
   let someField = model.Test("")

Where the parameter coming in has the Test method on it. I've seen notation like this:

member inline public x.Testing< ^a when ^a : (member public Test : String-> String)>(model:^a) =   
  let something = model.Test("")
  ignore

Which looks like to me that generic constraints can be used to enfore at a method level rather than class/interface level. Problem is I can't get it to compile due to type issues. This leads me to believe that there isn't a way to specify constraints at the method level. Is that coorect?

The syntax for this is a bit clunky, but here it is.

type Foo() =
  member inline public x.Testing(model) =   
    let something = (^a : (member Test : string -> string) (model, ""))
    ignore

You're probably better off using an interface:

type IModel
  abstract Test : string -> string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM