我知道 F# 有 MAP,但我想使用 .NET 字典。这个字典有作为字符串的键和作为 F# 值 + 字典的值,即:
type ExprC =
| StrC of string
| BoolC of bool
| IntC of int32
| DecC of decimal
| ArrayC of int * array<ExprC>
| RelC of RelationC
and RelationC = Dictionary<string, ExprC>
现在,我要解决的问题是如何为 RelationC 类型提供结构平等。如果需要封装实际存储,如何创建一个替代 Dictionary 的容器,将其用于可变操作并具有结构相等性?
使用当前答案,此代码不起作用(诅咒实现不完整,但是,这甚至无法编译):
[<CustomEquality; CustomComparison>]
type MyDict() =
inherit Dictionary<string, ExprC>()
override this.Equals x =
match x with
| :? MyDict as y -> (this = y)
| _ -> false
override this.GetHashCode () =
hash this
interface System.IComparable with
member x.CompareTo yobj =
match yobj with
| :? MyDict as y -> compare x y
| _ -> invalidArg "MyDict" "cannot compare values of different types"
and [<StructuralEquality;StructuralComparison>] ExprC =
| IntC of int
| StrC of string
| MapC of MyDict
这是错误:
错误 FS0377:此类型使用了“NoEquality”、“ReferenceEquality”、“StructuralEquality”、“NoComparison”和“StructuralComparison”属性的无效组合 (FS0377)