歧视联盟结构/习惯平等

时间:2012-06-12 20:17:10

标签: f# discriminated-union

我有以下歧视联盟:

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 *)

这里有什么更好的方法?

1 个答案:

答案 0 :(得分:8)

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

修改

可以做这样的事情。

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