Home > Software engineering >  Define EQ Instance
Define EQ Instance

Time:12-16

I am trying to create an Eq Instance, but I have some issues creating it.

I have the following data definitions:

data Link = G | S | P deriving (Eq, Show)
data Chain = Empty | Join Link Chain

And Now I want to convert Chain into an Eq Instance (True when it is the same).

Here is my current instance:

instance Eq Chain where
(Join a b) == (Join c d) = (a == c) && (b == d)
Empty      == Empty      = True
_          == _          = False

it marks (a == c) && (b == d)as mistake (Ambiguous occurrence ‘==’)

I am unsure why this is, and would appreciate it if someone could help me.

Thank you in advance!

CodePudding user response:

You failed to indent the method definitions.

instance Eq Chain where
↓↓
  Join a b == Join c d = a==c && b==d
  Empty    == Empty    = True
  _        == _        = False
↑↑

...Or alternatively, but highly dis-recommended, put them in braces

instance Eq Chain where {
Join a b == Join c d = a==c && b==d;
Empty    == Empty    = True;
_        == _        = False
}

Without the indentation or braces, what your code does is declare an empty Eq instance, and a separate, completely new operator that happens to be also called ==. I.e., you actually wrote this:

module Ch where

instance Eq Chain where
  -- missing definitions of `Prelude.==` here

(Ch.==) :: Chain -> Chain -> Bool
Join a b Ch.== Join c d = a==c && b==d
Empty    Ch.== Empty    = True
_        Ch.== _        = False

The compiler error tells you that the a==c and b==d definitions are now ambiguous: is this referring to Prelude.== or to Ch.==?

  • Related