简体   繁体   中英

How do I write this member constraint in F#?

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?

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)

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