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)
问:我在这里做错了什么?
您不需要对、 和进行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)