Ambiguous occurrence of '=='

I am just learning Haskell and still trying to figure out how things work.

So, I am creating a list class that can contain a mixture of Int and Char .

 data Algebra = Empty | Nmbr Int Algebra | Smbl Char Algebra 

Then I try to make it an instance of Eq

 instance Eq Algebra where Empty == Empty = True (Nmbr x xl) == (Nmbr y yl) = (x == y) && (xl==yl) (Smbl x xl) == (Smbl y yl) = (x == y) && (xl==yl) _ == _ = False 

and I get Ambiguous occurrence == compilation error. It cannot determine the difference between Main.== and Prelude.== . If I manually replaced everything == with Main.== or Prelude.== , then it compiles fine.

I don’t understand why the compiler has so many difficulties. x and y clearly defined as Int or Char in each case. I compared what I do with numerous sample tutorials (e.g. http://www.haskell.org/tutorial/classes.html ), and I cannot determine why the compiler is such a jerk in this situation: P

+6
source share
1 answer

You need to separate the body from your instance definition:

 instance Eq Algebra where Empty == Empty = True (Nmbr x xl) == (Nmbr y yl) = (x == y) && (xl==yl) (Smbl x xl) == (Smbl y yl) = (x == y) && (xl==yl) _ == _ = False 

Otherwise, the compiler sees this as two things:

  • An instance Eq Algebra with an empty body, creating default definitions a == b = not (a /= b) and vice versa.

  • Defining a new infix operator named == .

Then, using == in your code, an ambiguity arises between == of Eq (defined in Prelude ) and == in your code ( Main ).

And yes, deriving Eq gives you just such structural equality.

+9
source

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


All Articles