I have a generic class in F # with one type of parameter and would like to create a static class containing factory methods. When I write my classes, the F # compiler generates an error related to "a type variable that implements its scope". My question is why there is an error and how to fix it.
I created a minimal size fragment demonstrating the problem:
type Foo<'a>(element : 'a) = member this.Copy () = Bar.Create(element) and Bar = static member Create(element : 'a) = new Foo<'a>(element)
There is mutual recursion in types, because I would like the type Foo<'a>
be able to call factory methods in a static class. The above snippet does not compile, and an error occurs: "Type inference forced a variable of type a to leave the scope. Consider adding an explicit declaration of the type parameter or changing the code to a more general one." The error is registered as being in the Create
method of the Bar
class. Unfortunately, I really do not understand the problem and how to fix it. Any ideas?
Here's an extra observation. Fragment
type Foo<'a>(element : 'a) = member this.Element = element and Bar = static member Create(element : 'a) = new Foo<'a>(element)
does a compilation. Thus, the problem is apparently related to type inference based on the Copy()
method of class Foo<'a>
. Also fragment
type Foo<'a>(element : 'a) = member this.Copy () = Bar.Create(element) and Bar = static member Create<'a>(element) = new Foo<'a>(element)
- this is a more C # -like version of the code (where the static method is explicitly generalized), which also does not compile with the error "This code is not general enough. A variable of type a cannot be generalized because it leaves the scope."
source share