F#: Member constraints to help create seemingly dy

2019-05-10 15:43发布

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?

1条回答
不美不萌又怎样
2楼-- · 2019-05-10 16:22

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
查看更多
登录 后发表回答