Type restriction order in F #

This works in F # 4.0:

type Something<'a, 'b when 'b :> seq<'b>>() = 

It does not mean:

 type Something<'b when 'b :> seq<'b>, 'a>() = 

Unexpected character ',' in type name. The expected '>' or other token.

What is the reason that type restriction order matters?

+3
source share
3 answers

Since this is in the specification - the relevant part - this (from the beginning of section 5):

 typar-defns:= < typar-defn, ..., typar-defn typar-constraints_opt> 

restrictions must come at the end.

In this, typar-constraints should always begin with when and can no longer appear.

+9
source

Type restrictions and type arguments are two different things. In your example, 'a and 'b are two type arguments, and when 'b :> seq<'b> is a constraint (only).

Now, as you wrote your first example, it looks like the definitions of type arguments have something to do with type restrictions, but this is only in appearance. Pay attention to this (working) code:

 type Something<'b, 'a when 'b :> seq<'b>>() = member this.A (a : 'a, b : 'b) = () 

First you define all type arguments. Only after this does type constraints appear, and the constraint still applies to 'b , not 'a - as long as it looks a bit confusing, the constraint expression is not 'a when 'b :> seq<'b> , it's just when 'b :> seq<'b> .

This is actually almost the same as in C #, another .NET language:

 public class Something<TA, TB> where TA: someConstraint where TB: someOtherConstraint 

Constraints are more visually separated from C #, so people are not inclined to make the mistake you made in F #.

+4
source

Along with the answers above, ordering allows constraints to depend on several types. eg.

 type Something<'a, 'b when 'b :> seq<'a>>() = 

Note: seq<'a> not seq<'b>

+1
source

All Articles