views:

82

answers:

1

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
+3  A: 

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"

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.)

Brian