Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
844 views
in Technique[技术] by (71.8m points)

generics - F# explicit member constraints: The type variable ^T could not be generalized because it would escape its scope

I'm attempting to use explicit member constraints in F#. The documentation says "F# supports the complete set of constraints that is supported by the common language runtime", but if I actually compile a class with such an explicit constraint, such as the following, I get quite the exotic error.

type MyType<'T when ^T: (static member ( + ) : ^T * ^T -> ^T)> =
    member this.F a b = a + b

reports

error FS0670: This code is not sufficiently generic. The type variable ^T when ^T : (static member ( + ) : ^T * ^T -> ^T) could not be generalized because it would escape its scope.

And reports it at the site of defining member this.F. What does this mean? What is the relevant scope?

There are a number of approaches supported by the language for doing this sort of work. A nice exploration can be found here on StackOverflow, but I've not seen a clear explanation of why this particular generic constraint is not allowed to 'escape'.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Member constrains need statically resolved type parameters. But statically resolved type parameters are not allowed on types (as in your example), only for inline functions and inline methods.

The underlying problem is probably that types as a whole cannot be inline.

See also: http://msdn.microsoft.com/en-us/library/dd548046.aspx

If you use an inline member like this:

type MyType() =
    member inline this.F a b = a + b

the types of a and b will automatically be correctly constrained.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...