【问题标题】:Discriminated union structural/custom equality有区别的工会结构/习惯平等
【发布时间】:2012-06-14 02:30:15
【问题描述】:

我有以下受歧视的工会:

type ActCard = Cellar of card list 
                | Chapel of (card option * card option* card option* card option) 
                | Smithy | Spy of (card -> bool * card -> bool)

在我将card -> bool 添加到Spy 之前,它具有结构平等性。 This question 有助于如何对记录进行自定义相等。但是,我不确定在这种情况下如何最好地实施它。我宁愿不必在ActCard 中列举每个案例:

override x.Equals(yobj) =
    match x, yobj with
    |  Spy _, Spy _ -> true
    |  Cellar cards, Cellar cards2 -> cards = cards2
    (* ... etc *)

这里有什么更好的方法?

【问题讨论】:

    标签: f# discriminated-union


    【解决方案1】:

    没有更好的方法。如果您不打算使用默认的结构相等,则必须说明相等语义。

    编辑

    可以做这样的事情。

    [<CustomEquality; CustomComparison>]
    type SpyFunc = 
      | SpyFunc of (card -> bool * card -> bool) 
      override x.Equals(y) = (match y with :? SpyFunc -> true | _ -> false)
      override x.GetHashCode() = 0
      interface System.IComparable with
        member x.CompareTo(y) = (match y with :? SpyFunc -> 0 | _ -> failwith "wrong type")
    
    type ActCard = 
      | Cellar of card list 
      | Chapel of (card option * card option * card option * card option) 
      | Smithy 
      | Spy of SpyFunc
    

    【讨论】:

    • 如果我想让 ActCard 支持比较怎么办? SpyFunc是否需要提供对比?
    • 是的。您需要使用CustomComparison 属性并实现System.IComparable。我更新了我的答案来演示。
    • 太好了,谢谢。当类型是 and 绑定的一部分时,如何将这些属性应用于类型?
    • 属性放在and之后。例如,type A() = class end and [&lt;CustomEquality; CustomComparison&gt;] B() = class end
    猜你喜欢
    • 2015-11-05
    • 2017-11-24
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多