F#: Member constraints to help create seemingly dynamic types

泄露秘密 提交于 2019-12-07 14:26:36

问题


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:


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


来源:https://stackoverflow.com/questions/8095512/f-member-constraints-to-help-create-seemingly-dynamic-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!