Rewrite some C # common code in F #

I am 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 the solution to the F # restriction does not work like C #, and the compiler outputs a bunch of input errors:

error FS0698: Invalid restriction: the type used for the restriction is sealed, which means the restriction can be satisfied by no more than one Solution

warning FS0064: This construct causes the code to be less general than indicated by type annotations. The type variable 'T was limited to type' 'U'.

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

error FS0013: Static enforcement from type 'U to' U
includes an indefinite type according to the information up to this program point. Static enforcement is not allowed on some types. A further type of annotation is required.

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

Please explain to me how to correctly rewrite the C # code above and why the F # version that I wrote does not compile.

+7
source share
3 answers

You cannot write a function that is safe for this. However, you can use upcast instead of your function.

+6
source

This is a compiler limitation. The correct constraint type 'a:>' ​​b must not be a generic type.

+3
source

All Articles