Discriminated union structural/custom equality

点点圈 提交于 2019-12-12 10:01:01

问题


I have the following 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)

It had structural equality until I added the card -> bool to Spy. This question is helpful for how to do custom equality for records. However, I'm not sure how best to implement it in this situation. I would prefer to not have to enumerate each case in ActCard:

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

What is a better approach here?


回答1:


There isn't a better approach. If you're not going to use the default structural equality you'll have to spell out equality semantics.

EDIT

You could do something like this.

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


来源:https://stackoverflow.com/questions/11004179/discriminated-union-structural-custom-equality

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!