Using generics in F # to create an EnumArray type
I created an F # class to represent an array that allocates one element for each value of a specific enum. I use an explicit constructor that creates a dictionary from enum values ββfor 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 am getting the following obscure compilation error on the line marked "// 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 am at a loss - can someone 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
+2
a source to share
1 answer
Here you go:
open System
open System.Collections.Generic
type EnumArray<'e, 'v when 'e : enum<int> and 'e : equality>() =
let dict = new Dictionary<'e, int>() //'
let values = Enum.GetValues(typeof<'e>) //'
let a = Array.zeroCreate values.Length
do
for (o : obj) in values do
let e = o :?> 'e //'
dict.Add(e, LanguagePrimitives.EnumToValue(e))
member this.Item
with get idx = a.[dict.[idx]]
and set idx c = a.[dict.[idx]] <- c
let d = new EnumArray<StringSplitOptions, string>()
d.[StringSplitOptions.None] <- "foo"
d.[StringSplitOptions.RemoveEmptyEntries] <- "bar"
The key aspect is LanguagePrimitives.EnumToValue , which removes the need for static member constraints. (Using static member constraints is bad enough, but when something fails with them, the compiler diagnostics is even worse.)
+5
a source to share