在 F# 中使用泛型创建 EnumArray 类型
我创建了一个 F# 类来表示一个数组,该数组为特定枚举的每个值分配一个元素。我使用显式构造函数创建从枚举值到数组索引的字典和 Item 属性,以便您可以编写如下表达式:
let my_array = new EnumArray<EnumType, int>
my_array.[EnumType.enum_value] <- 5
但是,我在标有 '// FS0670 的行处收到以下晦涩的编译错误' 以下。
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.
我不知所措 - 谁能解释这个错误?
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这里:
一个关键方面是 LanguagePrimitives.EnumToValue,它删除了需要静态成员约束。 (使用静态成员约束已经够糟糕的了,但是当它们失败时,编译器诊断就更糟糕了。)
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.)