Using generics in F# to create an EnumArray type

Posted by Matthew on Stack Overflow See other posts from Stack Overflow or by Matthew
Published on 2010-05-13T04:47:18Z Indexed on 2010/05/13 4:54 UTC
Read the original article Hit count: 280

Filed under:
|
|
|

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

© Stack Overflow or respective owner

Related posts about F#

Related posts about generics