(Re) -definition (==) for the class Eq

In the following example:

data ColourName 
  = White
  | Grey
  | Gray
  | Black
  | Blue
  -- ...
  -- hundreds more of colours
  -- ...
  | LastColor
  deriving (Read, Show, Eq)

I would like to redefine (==)so that Greythey are Grayevaluated as equals.

Obviously, one way would be to not include Eqin deriving, but then I would need to define

(==) :: ColourName
(==) White White = True
(==) Gray Gray = True
(==) Grey Grey = True
(==) Gray Grey = True
(==) Grey Gray = True
(==) Black Black = True
-- frickin' log of other colors, hundreds of lines of typing
(==) LastColor LastColor = True
(==) a b = False

which I do not plan to do anything.

I also can not do

instance Eq ColourName where
    (==) :: ColourName -> ColourName -> Bool
    (==) Gray Grey = True
    (==) Grey Gray = True
    (==) a b = (a == b)

because it leads to infinite recursion, mostly undetermined.

Is there a way out?

(No, I don’t want to use data Colour = Colour Stringor similar. I want acceptable colors to be presented as an enumeration, such as automatic checking, but allowing spelling to be allowed for end users of the module!)

+4
source share
5 answers

Enum:

data ColourName = Gray | Grey | ...
  deriving (Read, Show, Enum)

instance Eq ColourName where
  Gray == Grey = True
  Grey == Gray = True
  a == b = fromEnum a == fromEnum b

: PatternSynonyms GHC 7.8+. , .

pattern Gray = Grey
+12

. . -

f Gray = g
f x    = h

Eq.

, , f Grey h, g, f x == f y x == y. , , f Gray, f Grey, .

, , ,

#define Gray Grey

CPP.

+9

Grey Gray . , , , , . , Eq.

:

sameColour :: Color -> Color -> Bool
sameColour Grey Gray = True
sameColour Gray Grey = True
sameColor  a    b    = a == b

, ""

+7

Piezoid , , Show :

data ColourName = Gray | Grey | ...
    deriving (Show, Read)

instance Eq ColourName where
    Gray == Grey = True
    Grey == Gray = True
    a == b = show a == show b

Enum, , .

+6

newtype :

newtype ColourNameEquatingGrayAndGrey = CNEGAG ColourName
instance Eq ColourNameEquatingGrayAndGrey where
    CNEGAG Gray == CNEGAG Grey = True
    CNEGAG Grey == CNEGAG Gray = True
    CNEGAG a    == CNEGAG b    = a == b

( ...)

deriving Eq, , , , nub ( nubBy sameColour ( @cdk) - ). Show, , .

, , , , , 100 , !

+4

Source: https://habr.com/ru/post/1546153/


All Articles