How to restrict one type parameter to another

Is there a way to limit one type parameter that should be obtained from another?

type Foo<'T, 'U when 'U :> 'T> = member x.Bar() : 'T = upcast Unchecked.defaultof<'U> 

This code causes the following errors:

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

Error 2 This type parameter was used so that it was always "T"

Error 3 Static enforcement from type "T to" T0 includes an undefined type based on information up to this point in the program. Static constraints are not allowed for some types. Additional type annotations are required.

Warning 4 This construction causes the code to be less general than indicated by type annotations. A variable of type 'U was limited to type' 'T'.

+17
f #
04 Oct '10 at 17:08
source share
1 answer

No :( This is one of the most unsuccessful F # restrictions at the moment (in my opinion). See the Resolution of Subtype Constraints section of the specification, which states that

New form type restrictions:> 'b are resolved again as type =' b.

This is really a shame, because otherwise we could do without the general variance of F #:

 let cvt<'a,'b when 'a :> 'b> (s:seq<'a>) : seq<'b> = // doesn't compile s |> box |> unbox 
+19
04 Oct '10 at 17:16
source share



All Articles