Understanding F # inline and statically resolved parameter types: an example of F #

F # built-in functions with statically permitted typical parameters seem similar to C ++ templates. However, unlike C ++, you need to specify restrictions - how does it work?

For example, I am trying to implement a boost function, but this will not work:

let inline myUpcast< ^a, ^b  when ^a :> ^b  > (x: ^a) :  ^b =  x

Error message: error FS0698: Invalid constraint: the type used for the constraint is sealed, which means that the constraint can be satisfied with only one solution.

I'm actually trying to write a function that will generate sequences when the base types can be selected (to avoid the lack of covariance), but the following also doesn't work:

let inline upcastseq (xs: seq< ^a >) : seq< ^b > when ^a :> ^b = xs :?> seq< ^b >

which triggers the following warning: warning FS0064: this construction causes the code to be less general than indicated by type annotations. A variable of type 'a was limited to type' ^ b '. As you would expect, in fact, using a function does not work as you might expect.

So, I'm looking for a function that will lead to a type-checking error if it is used to convert sequences in a covariantly invalid order (hence, limiting the general parameters) - is this possible?

More generally, what are the limitations of statically permitted type parameters compared to C ++ templates?

+3
source share
1 answer

, . :

// doesn't work
let myUpcast<'a, 'b when 'a :> 'b) (x: 'a) : 'b = unbox (box x)

F # ; .

. .

+3

Source: https://habr.com/ru/post/1775427/


All Articles