You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写Tree类型Eq实例报错No instance for (Eq a),求解决方案

Fixing Your Eq Instance for the 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:27:47