haskellcompiler-constructionderived-instances

Use parts of constructor for deriving instance in Haskell data


I need to derive Eq for a data, but for some constructors I want to ignore some fields. The data is for representing DataTypes (we are developing a compiler):

data DataType
    = Int | Float | Bool | Char | Range | Type
    | String Width
    | Record (Lexeme Identifier) (Seq Field) Width
    | Union  (Lexeme Identifier) (Seq Field) Width
    | Array   (Lexeme DataType) (Lexeme Expression) Width
    | UserDef (Lexeme Identifier)
    | Void | TypeError
    deriving (Ord)

I need to ignore the Width field from every contstructor it appears in.


Solution

  • You could write your own instance of Eq:

    instance Eq DataType where
       Int   == Int   = True
       Float == Float = True 
       Bool  == Bool  = True
       Char  == Char  = True
       Range == Range = True
       Type  == Type  = True
       (String _) == (String _) = True
       (Record l1 s1 _)  == (Record l2 s2 _)  = (l1 == l2) && (s1 == s2)
       (Union  l1 s1 _)  == (Union  l2 s2 _)  = (l1 == l2) && (s1 == s2)
       (Array   l1 e1 _) == (Array   l1 e1 _) = (l1 == l2) && (e1 == e2)
       (UserDef i1)      == (UserDef i2)      = i1 == i2
       Void      == Void      = True
       TypeError == TypeError = True
       _ == _     = False