Haskell 的类问题

cod*_*dde 2 haskell types functional-programming class

这次,我有这些定义:

data Color = Red | Green | Blue
  deriving (Show, Eq)

data Suit = Club | Spade | Diamond | Heart
  deriving (Show, Eq)

class Eq a => Eq (Cycle a) where
  step :: a -> a
  stepMany :: Integer -> a -> a
  stepMany 0 x = x
  stepMany steps x = stepMany (steps - 1) (step x)
    
instance Eq Color => Cycle Color where
  step color
    | color == Red = Green
    | color == Green = Blue
    | color == Blue = Red

instance Eq Suit => Cycle Suit where
  step suit 
    | suit == Club = Spade
    | suit == Spade = Diamond
    | suit == Diamond = Heart
    | suit == Heart = Club
Run Code Online (Sandbox Code Playgroud)

我的问题是该行

class Eq a => Eq (Cycle a) where'='"
Run Code Online (Sandbox Code Playgroud)

产生错误

    Unexpected type `Cycle a'
    In the class declaration for `Eq'
    A class declaration should have form
      class Eq a where ...
  |
7 | class Eq a => Eq (Cycle a) where
  |
Run Code Online (Sandbox Code Playgroud)

问:我在这里做错了什么?

Mar*_*ann 5

您不需要对、 和进行Eq约束。您可以像这样编写模块:CycleColorSuit

data Color = Red | Green | Blue
  deriving (Show, Eq)

data Suit = Club | Spade | Diamond | Heart
  deriving (Show, Eq)

class 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
Run Code Online (Sandbox Code Playgroud)

  • @nm 我复制了操作代码并进行了使其工作所需的最小更改。OP 是 IIRC,一位 Haskell 初学者(这没什么问题 - 我们都曾经是初学者),所以我发现首先处理最直接的问题在教学上是合适的。一心一意... (3认同)