F#: Member constraints to help create seemingly dynamic types
Asked Answered
P

1

3

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?

Peltate answered 11/11, 2011 at 14:41 Comment(0)
T
5

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
Twospot answered 11/11, 2011 at 15:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.