F#中的结构平等

Nic*_*ner 10 f# structural-equality

我有一个包含功能的记录类型:

{foo : int; bar : int -> int}
Run Code Online (Sandbox Code Playgroud)

我希望这种类型具有结构上的平等性.有什么方法可以说明bar在相等测试中应该忽略它吗?或者还有其他方法吗?

Ste*_*sen 18

请参阅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"
Run Code Online (Sandbox Code Playgroud)


Fre*_*any 9

要更具体地回答您的原始问题,您可以创建一个自定义类型,其实例之间的比较始终为真:

[<CustomEquality; NoComparison>]
type StructurallyNull<'T> =
    { v: 'T } 

    override x.Equals(yobj) =
        match yobj with
        | :? StructurallyNull<'T> as y -> true
        | _ -> false

    override x.GetHashCode() = 0

type MyType = { 
    foo: int; 
    bar: StructurallyNull<int -> int> 
}
Run Code Online (Sandbox Code Playgroud)