Search code examples
classhaskelltypesfunctional-programming

Class problems with Haskell


This time, I have these definitions:

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

My problem is that the line

class Eq a => Eq (Cycle a) where'='"

produces the error

    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
  |

Q: What am I doing wrong here?


Solution

  • You don't need the Eq constraint on Cycle, nor on Color and Suit. You can just write the module like this:

    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