Reputation: 1
Using Trees
and defining a new "Eq
" I'm getting an "Ambiguous class occurrence 'Eq' *** Could refer to: Hugs.Prelude.Eq Main.Eq".
I'm aware that I'm trying to add a new definition for the existing Eq-Class of the prelude, but I don't want to use import prelude hiding (Eq), because my new equality is using the "==" for numerical types. The Operator is called "=+", because it is not a real equality (which I think is already 'loaded' via deriving), but only a structural one.
data Tree = Nil | Node Int Tree Tree deriving (Eq, Ord, Show)
instance Eq Tree where
Nil =+ Nil = true
(Node a tl1 tr1) =+ (Node b tl2 tr2) = (a==b) && (tl1==tl2) && (tl1==tl2)
I'd be thankful for any suggestions.
Upvotes: 0
Views: 423
Reputation: 62818
Why are you deriving Eq
if you want to write a custom one? Just drop Eq
from the deriving clause, and this should all work.
Upvotes: 0
Reputation: 120711
If you want a new class to coexist with a predefined one, you should obviously give it a properly distinguishable name, e.g.
class PseudoEq x where
(=+) :: x -> x -> Bool
instance PseudoEq Tree where
Nil =+ Nil = true
Node a tl1 tr1 =+ Node b tl2 tr2
= a==b && tl1==tl2 && tl1==tl2
Simply qualifying the instance with Main.Eq
does pretty much the same thing, but it's confusing to call your class Eq
at all if it's "not real equality".
(Though ==
also doesn't need to be a proper equality; for many types this only means "equivalent in all regards the user can observe".)
Upvotes: 3
Reputation: 105886
Just use fully qualified class names:
module Main where
data Tree = Nil | Node Int Tree Tree deriving (Prelude.Eq, Ord, Show)
class Eq a where
(=+) :: a -> a -> Bool
instance Main.Eq Tree where
Nil =+ Nil = True
(Node a tl1 tr1) =+ (Node b tl2 tr2) = (a==b) && (tl1==tl2) && (tl1==tl2)
You shouldn't create such ambiguity in first place. For example, your Eq
should be called StructEq
instead, if it's "only a structural one".
Upvotes: 2