F# F中的结构等式#
我有一个记录类型,其中包括一个函数:F# F中的结构等式#,f#,structural-equality,F#,Structural Equality,我有一个记录类型,其中包括一个函数: {foo : int; bar : int -> int} 我希望这种类型具有结构相等性。有没有什么方法可以让我在平等性测试中忽略条?或者有其他方法解决这个问题吗?请参阅Don关于这个主题的帖子,特别是自定义平等和比较部分 他给出的示例与您建议的记录结构几乎相同: /// A type abbreviation indicating we’re using integers for unique stamps on objects type stam
{foo : int; bar : int -> int}
我希望这种类型具有结构相等性。有没有什么方法可以让我在平等性测试中忽略条
?或者有其他方法解决这个问题吗?请参阅Don关于这个主题的帖子,特别是自定义平等和比较部分
他给出的示例与您建议的记录结构几乎相同:
/// A type abbreviation indicating we’re using integers for unique stamps on objects
type stamp = int
/// A type containing a function that can’t be compared for equality
[<CustomEquality; CustomComparison>]
type MyThing =
{ Stamp: stamp;
Behaviour: (int -> int) }
override x.Equals(yobj) =
match yobj with
| :? MyThing as y -> (x.Stamp = y.Stamp)
| _ -> false
override x.GetHashCode() = hash x.Stamp
interface System.IComparable with
member x.CompareTo yobj =
match yobj with
| :? MyThing as y -> compare x.Stamp y.Stamp
| _ -> invalidArg "yobj" "cannot compare values of different types"
///一个类型缩写,表示我们在对象上使用整数作为唯一标记
类型戳记=int
///一种类型,它包含一个无法比较相等性的函数
[]
类型神话=
{邮票:邮票;
行为:(int->int)}
覆盖x.Equals(yobj)=
将yobj与
| :? 虚构为y->(x.Stamp=y.Stamp)
|_u->false
重写x.GetHashCode()=哈希x.Stamp
接口系统.i可与
成员x.与yobj相比=
将yobj与
| :? 虚构为y->比较x.戳记y.戳记
|->invalidArg“yobj”无法比较不同类型的值
要更具体地回答您的原始问题,您可以创建一个自定义类型,其实例之间的比较始终为真:
[<CustomEquality; NoComparison>]
type StructurallyNull<'T> =
{ v: 'T }
override x.Equals(yobj) =
match yobj with
| :? StructurallyNull<'T> -> true
| _ -> false
override x.GetHashCode() = 0
[]
结构完整型
type MyType = {
foo: int;
bar: StructurallyNull<int -> int>
}