Rewrite some C# generic code into F#

家住魔仙堡 提交于 2019-12-05 22:41:45

问题


I'm trying to rewrite generic code like this (C#):

U Upcast<T, U>(T x) where T : U { return x; }

In F#:

let ucast<'T, 'U when 'T :> 'U> (x: 'T) = x :> 'U

But F# constraint solving works different than C# and compiler outputs a bunch of typing errors:

error FS0698: Invalid constraint: the type used for the constraint is sealed, which means the constraint could only be satisfied by at most one solution

warning FS0064: This construct causes code to be less generic than indicated by the type annotations. The type variable 'T has been constrained to be type ''U'.

error FS0663: This type parameter has been used in a way that constrains it to always be ''U'

error FS0013: The static coercion from type 'U to 'U
involves an indeterminate type based on information prior to this program point. Static coercions are not allowed on some types. Further type annotations are needed.

error FS0661: One or more of the explicit class or function type variables for this binding could not be generalized, because they were constrained to other types

Please, explain me how to correctly rewrite C# code above and why F# version I've wrote doesn't compiles.


回答1:


This isn't possible in F#. See How do I translate a `where T : U` generic type parameter constraint from C# to F#? and http://cs.hubfs.net/forums/thread/10534.aspx.




回答2:


You can't write a type-safe function for this. You could however, use the upcast operator instead of your function.




回答3:


This is compiler restriction. Right type of the constraint 'a :> 'b must be of non generic type.



来源:https://stackoverflow.com/questions/4561663/rewrite-some-c-sharp-generic-code-into-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!