【问题标题】:Structural Equality in F#F# 中的结构平等
【发布时间】:2012-06-09 00:47:51
【问题描述】:

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

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

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

【问题讨论】:

    标签: f# structural-equality


    【解决方案1】:

    请参阅 Don 关于此主题的 blog 帖子,特别是 自定义平等和比较部分。

    他给出的例子和你提出的记录结构几乎一模一样:

    /// 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"
    

    【讨论】:

      【解决方案2】:

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

      [<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> 
      }
      

      【讨论】:

        猜你喜欢
        • 2021-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多