What is the difference between the generic signifier ' and the symbol ^ In F# method signatures

北城余情 提交于 2019-12-12 11:14:44

问题


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.



来源:https://stackoverflow.com/questions/11250347/what-is-the-difference-between-the-generic-signifier-and-the-symbol-in-f-me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!