What is the difference between the generic signifi

2019-06-22 14:39发布

问题:

I understand the tick to signify a generic parameter, as in:

Seq.append : seq<'T> -> seq<'T> -> seq<'T>

but what does the caret signify, as in:

Seq.average : seq<^T> -> ^T

回答1:

The detailed signature is:

Seq.average : seq<^T> -> ^T (requires ^T with static member (+) and ^T with static member DivideByInt and ^T with static member Zero)

Unlike Seq.append, Seq.average needs some more constraints on type of elements. Particularly:

                                _ DivideByInt (s1 + s2 + ... + sn) n where n <> 0
Seq.average {s1; s2;...; sn} = /
                               \_ ^T.Zero where n = 0

As you can see, both (+), DivideByInt and Zero are required in order that Seq.average<^T> makes sense.

Useful information about generics could be found hereMSDN.



回答2:

The caret indicates that the type parameter must be statically resolved, usually because there are particular constraints on the type that must be satisfied and which can't be expressed in normal .NET metadata. For instance, you can't call Seq.average "test" even though "test" is a seq<char>, because chars don't support the necessary arithmetic operations.

These statically resolved type variables only arise from inline defintions, and when such a function is used, its body is inlined so that the compiler can insert the correct type-specific instructions.



回答3:

Although, as others have pointed out, by convention ^T is used with inline and 'T is not, the two are interchangeable (sometimes?).

So, technically, the answer to your question is "there isn't a difference."

kvb pointed out: there is a difference. But it's not as clear-cut as the other answers indicate. In some cases, the two are interchangeable, e.g.,

let inline add (x:^T) (y:^T) = x + y
let inline add (x:'T) (y:'T) = x + y

or

let f (x:^T) = !x
let f (x:'T) = !x

The convention is clear, while the implementation is not.