Haskell自定义Cycle类型类报错求助:类声明语法问题排查
问题分析与修正
你的核心错误出在类型类的声明语法上:
你写的class Eq a => Eq (Cycle a) where完全不符合Haskell的类定义规则。这里你想定义一个名为Cycle的新类型类,但错误地把类名写成了Eq(这是Haskell自带的标准类),还错误地将Cycle a作为Eq类的参数,导致编译器认为你在非法重定义Eq类,且参数格式错误。
正确的类定义写法
应该把类名写成Cycle,类型参数为a,同时保留Eq a作为约束(因为你的step方法需要用==比较值):
class Eq a => Cycle a where step :: a -> a stepMany :: Integer -> a -> a stepMany 0 x = x stepMany steps x = stepMany (steps - 1) (step x)
修正后的完整代码
data Color = Red | Green | Blue deriving (Show, Eq) data Suit = Club | Spade | Diamond | Heart deriving (Show, Eq) class Eq a => Cycle a where step :: a -> a stepMany :: Integer -> a -> a stepMany 0 x = x stepMany steps x = stepMany (steps - 1) (step x) instance Cycle Color where step color | color == Red = Green | color == Green = Blue | color == Blue = Red instance Cycle Suit where step suit | suit == Club = Spade | suit == Spade = Diamond | suit == Diamond = Heart | suit == Heart = Club
(注:实例声明里的Eq Color =>可以省略,因为Color已经通过deriving (Eq)满足了Cycle类的约束要求,不过保留也不会报错)
内容的提问来源于stack exchange,提问作者coderodde
相关产品推荐
相关产品推荐

