Enum Type Constraint returns error "The signature and implementation are not compatible..."

Viewed 219

I've been trying to follow the guide from MSDN - Constraints (F#) on creating a type within a module which has a generic type constraint of an enum, as follows:

type Mapper<'TEnum when 'TEnum : enum<uint32>>() = 
    let dict = new Dictionary<'TEnum, string>()

    member this.Add (key: 'TEnum) (value: string) = 
        dict.Add(key, value)

However, I'm getting the error:

The signature and implementation are not compatible because the declaration of the type parameter 'TEnum' requires a constraint of the form 'TEnum : equality

Is there a way to fix this code example so that I'm able to constrain a type to an enum?

1 Answers

This comes from the instantiation of Dictionary<,>. F# has a special case for this type: it adds an equality constraint to its TKey generic parameter¹, because, well, dictionary keys have to be comparable, otherwise the dictionary can't function.

You can fix this by adding the constraint to your 'TEnum parameter:

  type Mapper<'TEnum when 'TEnum: enum<uint32> and 'TEnum : equality>() =  

¹even though the original type definition doesn't have this constraint, because the type is defined in C#

Related