函数返回类型中的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