18

For a type

type Cow() =
    class
        member this.Walk () = Console.WriteLine("The cow walks.")
    end

I can write a method which enforces a member constrain for method Walk like

let inline walk_the_creature creature =  
    (^a : (member Walk : unit -> unit) creature)
// and then do
walk_the_creature (Cow())

In this case the type is inferred. I am unable to explicitly write a constraint on the creature parameter like this

// Does not compile
// Lookup on object of indeterminate type based on information prior to this 
// program point. A type annotation may be needed...
let inline walk_the_creature_2 (creature:^a when ^a:(member Walk : unit -> unit)) =
    creature.Walk()

What am I doing wrong?

SharePoint Newbie
  • 5,974
  • 12
  • 62
  • 103

1 Answers1

27

It's not explicitly writing the constraints that is the issue, it's that the syntax is not so nice that you can place a member constraint on a parameter and then invoke the member in the usual way. The body of walk_the_creature and walk_the_creature2 would be the same here:

let inline walk_the_creature_2 (creature:^a when ^a:(member Walk : unit -> unit)) =
    (^a : (member Walk : unit -> unit) creature)
Stephen Swensen
  • 22,107
  • 9
  • 81
  • 136
  • 1
    Could you explain why the body is required to be written in this manner. Isn't all the type information already present in the second method? – SharePoint Newbie Jan 14 '11 at 20:01
  • 11
    The member constraint system is quite complex and separate from the nominal type system, so you don't get nominal member invocation syntax for free. In fact, `(^a : (member Walk : unit -> unit) creature)` doesn't invoke anything, it is a template for generating an (inlined) type specific implementation of the function at compile time. I suppose the unified syntax desired could be implemented, but the F# team never anticipated member constraints becoming so popular, intending them only for core libraries, and hence the syntax is a total wreck in this version (crossing fingers). – Stephen Swensen Jan 14 '11 at 20:45