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
函数返回类型中的F#多态性_F#_Polymorphism - Fatal编程技术网

函数返回类型中的F#多态性

函数返回类型中的F#多态性,f#,polymorphism,F#,Polymorphism,这里有一个简单的类型层次结构 type Parent() = class end type Child() = inherit Parent() 我想将('x->Child)类型的函数视为('x->Parent): 但最后一次分配失败,消息为类型“Parent”与类型“Child”不匹配。有什么方法可以让它工作吗?您可以使用: type Parent () = class end type Child () = inherit Parent () let f x = Child () //

这里有一个简单的类型层次结构

type Parent() = class end
type Child() = inherit Parent()
我想将
('x->Child)
类型的函数视为
('x->Parent)

但最后一次分配失败,消息为
类型“Parent”与类型“Child”不匹配
。有什么方法可以让它工作吗?

您可以使用:

type Parent () = class end
type Child () = inherit Parent ()

let f x = Child () // val f : x:'a -> Child
let g x = f x :> Parent // val g : x:'a -> Parent

这是有帮助的,但是必须包装
f
并不理想。例如,我希望能够在不进行大量讨价还价的情况下将f添加到
映射父项>
。这似乎是co/contrance,这在f#中不受支持。
type Parent () = class end
type Child () = inherit Parent ()

let f x = Child () // val f : x:'a -> Child
let g x = f x :> Parent // val g : x:'a -> Parent