gpt4 book ai didi

haskell - 没有因使用 ‘==’ 而产生 (Eq a) 的实例

转载 作者:行者123 更新时间:2023-12-02 17:08:41 27 4
gpt4 key购买 nike

我正在尝试为此数据类型编写一个 Eq 实例:

data Tree a b = Leaf b | Node a (Tree a b) (Tree a b)
deriving (Show)

我编写了我认为可行的简单代码:

instance 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

但随后我收到错误:

• No instance for (Eq a) arising from a use of ‘==’
Possible fix: add (Eq a) to the context of the instance declaration
• In the first argument of ‘(&&)’, namely ‘(val1 == val2)’
In the expression: (val1 == val2) && (l1 == l2) && (r1 == r2)
In an equation for ‘==’:
(Node val1 l1 r1) == (Node val2 l2 r2)
= (val1 == val2) && (l1 == l2) && (r1 == r2)

我尝试添加 Eq a => ... 但随后类型 b 出现相同的错误。我似乎也无法添加 Eq b

任何帮助将不胜感激,10x!

最佳答案

正如您所写,您必须设置类型约束Eq aEq b。您只需将约束放在括号中并用逗号分隔即可。

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

关于haskell - 没有因使用 ‘==’ 而产生 (Eq a) 的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50303877/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com