Override just a few cases of data in Eq instance implementation

  • A+

I have a data type

data MyType = Any | A | B | C ... 

and the semantics of "Any" is that it should be equivalent to all other cases. I thought that the most elegant way is to implement my own Eq instance, starting with

instance Eq MyType where     Any == _ = True     _ == Any = True 

But now I don't see a way of avoiding repetitive and silly code like

    A == A = True     B == B = True     ... 

I though of "abusing" the show function and just do x == y = (show x) == (show y) but is there a cleaner way?

You could perhaps do something like this:

data Wildcard a = Any | Card a  data NewType = A | B | C | ... deriving Eq  type OldType = Wildcard NewType  instance (Eq a) => Eq (Wildcard a) where   Any    == _      = True   _      == Any    = True   Card l == Card r = l == r 

This way, the compiler auto-derives Eq OldType for you, and we have Eq NewType with the expected semantics. (And we can apply Any over any type we fancy...)


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: