Lazare Rossillon
Lazare Rossillon

Reputation: 53

Instance Eq for data type with several sub-fields

I have a data type with several sub-fields and would like to implement the instance Eq class simultaneously.

The code is the following :

data Expression 
                = Variable  {
                            name            ::  String,
                            number          ::  Double,
                            exponentVal     ::  Double 
                            }
                |   Numeric Double
                |   CanonicalForm [Expression]
    deriving Show 

instance Eq Expression where
    someone == another = name someone == name another
    someone == another = exponentVal someone == exponentVal another

How could I modify the instance Eq class so that when I compare two variables the comparison evaluates both the name field and the exponentVal field ?

Upvotes: 3

Views: 262

Answers (2)

chepner
chepner

Reputation: 531055

For comparing two Variable values, you just need to combine the two field comparisons with &&.

instance Eq Expression where
    someone == another = name someone == name another && exponentVal someone == exponentVal another

However, this ignores the possibility that either argument might not be a Variable. You should use pattern matching.

instance Eq Expression where
    Variable n1 _ v1 == Variable n2 _ v2 = n1 == n2 && v1 == v2
    Number n1 == Number n2 = n1 == n2
    CanonicalForm es1 == CanonicalForm es2 = ...  -- appropriate definition here
    _ == _ = False

In the above, I've assumed that if the data constructors don't match, the expressions are not equal.

Upvotes: 3

Gabscap
Gabscap

Reputation: 287

Use pattern matching in your == definition

instance Eq Expression where
    Variable a b c == Variable a' b' c = a == a' && b == b' && c == c'
    -- other 2 cases
    _ == _ = False

Or just use deriving Eq as already pointed out in the comments.

Upvotes: 3

Related Questions