I’ve created an F# class to represent an array that allocates one element for each value of a specific enum. I’m using an explicit constructor that creates a dictionary from enum values to array indices, and an Item property so that you can write expressions like:
let my_array = new EnumArray<EnumType, int>
my_array.[EnumType.enum_value] <- 5
However, I’m getting the following obscure compilation error at the line marked with ‘// FS0670’ below.
error FS0670: This code is not sufficiently generic.
The type variable ^e when ^e : enum<int> and ^e : equality
and ^e : (static member op_Explicit : ^e -> int)
could not be generalized because it would escape its scope.
I’m at a loss – can anyone explain this error?
type EnumArray< 'e, 'v when 'e : enum<int> //'
and 'e : equality
and 'e : (static member op_Explicit : 'e -> int) > =
val enum_to_int : Dictionary<'e, int> //'
val a : 'v array //'
new() as this =
{
enum_to_int = new Dictionary<'e, int>() //'
a = Array.zeroCreate (Enum.GetValues(typeof<'e>).Length) //'
}
then
for (e : obj) in Enum.GetValues(typeof<'e>) do //'
this.enum_to_int.Add(e :?> 'e, int(e :?> 'e))
member this.Item
with get (idx : 'e) : 'v = this.a.[this.enum_to_int.[idx]] // FS0670
and set (idx : 'e) (c : 'v) = this.a.[this.enum_to_int.[idx]] <- c
Here you go:
A key aspect is LanguagePrimitives.EnumToValue, which removes the need for the static member constraints. (Use of static member constraints is bad enough, but when things fail with them, the compiler diagnostics are even worse.)