Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Generics 如何在F#中写入此成员约束?_Generics_F# - Fatal编程技术网

Generics 如何在F#中写入此成员约束?

Generics 如何在F#中写入此成员约束?,generics,f#,Generics,F#,对于一种类型 type Cow() = class member this.Walk () = Console.WriteLine("The cow walks.") end 我可以编写一个方法,为类似Walk的方法强制成员约束 let inline walk_the_creature creature = (^a : (member Walk : unit -> unit) creature) // and then do walk_the_

对于一种类型

type Cow() =
    class
        member this.Walk () = Console.WriteLine("The cow walks.")
    end
我可以编写一个方法,为类似Walk的方法强制成员约束

let inline walk_the_creature creature =  
    (^a : (member Walk : unit -> unit) creature)
// and then do
walk_the_creature (Cow())
在这种情况下,将推断类型。我无法像这样显式地在bioture参数上写入约束

// 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()

我做错了什么?

问题不是显式地编写约束,而是语法不太好,无法在参数上放置成员约束,然后以常规方式调用该成员。
walk\u生物
walk\u生物2
的身体在这里是相同的:

let inline walk_the_creature_2 (creature:^a when ^a:(member Walk : unit -> unit)) =
    (^a : (member Walk : unit -> unit) creature)

你能解释一下为什么正文必须这样写吗。不是所有的类型信息都已经存在于第二个方法中了吗?成员约束系统非常复杂,并且与标称类型系统是分开的,因此您不能免费获得标称成员调用语法。事实上,
(^a:(成员行走:单位->单位)生物)
不会调用任何东西,它是一个模板,用于在编译时生成函数的(内联)类型特定实现。我认为可以实现所需的统一语法,但F#团队从未预料到成员约束会变得如此流行,只打算将其用于核心库,因此在这个版本中,语法是一个彻底的破坏(交叉手指)。