【发布时间】:2025-12-11 21:50:02
【问题描述】:
我有一个数据类型,声明为:
data Card = Card Suit Value deriving (Show, Eq)
与:
data Suit = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace deriving (Show, Eq, Enum, Ord)
data Value = Spade | Diamond | Club | Heart deriving (Show, Eq, Enum)
我使类型 Card 成为类型类 Eq 的一部分,如下所示:
instance Eq Card where
(Card s1 v1) == (Card s2 v2) = (s1 == s2) && (v1 == v2)
即使我的解决方案与我们从 uni-class 获得的解决方案完全相同,但我总是从 ghci 收到以下错误:
<interactive>:9:1: error:
Couldn't match type ‘Card’ with ‘Suit’
Expected type: Suit -> Suit -> Bool
Actual type: Card -> Card -> Bool
<interactive>:9:49: error:
• Couldn't match expected type ‘Suit’ with actual type ‘Value’
• In the first argument of ‘(==)’, namely ‘v1’
In the second argument of ‘(&&)’, namely ‘(v1 == v2)’
In the expression: (s1 == s2) && (v1 == v2)
<interactive>:9:55: error:
• Couldn't match expected type ‘Suit’ with actual type ‘Value’
• In the second argument of ‘(==)’, namely ‘v2’
In the second argument of ‘(&&)’, namely ‘(v1 == v2)’
In the expression: (s1 == s2) && (v1 == v2)
【问题讨论】:
-
您的
Card已经是Eq到deriving (Show, Eq)的一个实例,因此您不能再次执行此操作。 -
我一开始是这样的,但它给了我同样的错误。
-
但是我无法复制这种行为。您是否自己定义了
Eq类型类(所以class Eq)?在这种情况下,(==)当然不再是原始Eq类型类中定义的那个。 -
请不要。现在有两个
Eq类型类,原来的一个,可能还有Suit和Value作为成员和新的一个。此类已通过Prelude定义和导入。 -
解决方案是什么?我知道重新启动终端似乎已经为您修复了它,但这是实际修复还是您的代码也发生了变化?