编写Tree类型Eq实例报错No instance for (Eq a),求解决方案
Tree a b Type Let's break down what's going wrong and fix your instance step by step.
First, here's the corrected Eq instance that resolves both errors:
instance (Eq a, Eq b) => Eq (Tree a b) where (Leaf x) == (Leaf y) = x == y (Node val1 l1 r1) == (Node val2 l2 r2) = val1 == val2 && l1 == l2 && r1 == r2 _ == _ = False
Why Your Original Code Failed
Your first error popped up because when comparing val1 == val2 in the Node case, the compiler had no guarantee that type a supports equality checks (i.e., has an Eq instance). Adding Eq a => fixed that part, but then you hit a similar issue with type b: the Leaf case compares x == y, which requires b to also have an Eq instance.
How to Add Multiple Type Constraints
To require both a and b to implement Eq, you list both constraints inside parentheses separated by a comma before the => arrow in the instance declaration. This tells the compiler: "this Eq instance for Tree a b only exists if a is an Eq type and b is an Eq type".
A Simpler Alternative
If you don't need custom equality logic (your manual implementation matches the default behavior anyway), you can let Haskell auto-generate the Eq instance for you by adding it to the deriving clause:
data Tree a b = Leaf b | Node a (Tree a b) (Tree a b) deriving (Eq, Show)
This handles all equality checks exactly like your manual code, with less boilerplate to write and maintain.
内容的提问来源于stack exchange,提问作者Ofir D

