15

我有一个包含函数的记录类型:

{foo : int; bar : int -> int}

我希望这种类型具有结构平等。有什么方法可以标记bar在平等测试中应该被忽略吗?或者还有其他方法可以解决这个问题吗?

4

2 回答 2

20

请参阅 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"
于 2012-06-09T03:03:58.437 回答
13

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

[<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> 
}
于 2014-01-06T09:31:08.750 回答