Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to declare a typeclass instance for a type alias?

Tags:

haskell

I have the code:

data Value = A|Two|Three...Ten|J|Q|K deriving (Eq, Ord, Enum)
instance Show Value where
    show A = "A"
    show Two = "2"
    ....
    show K = "K"

And another data Suite with a similar Show instance for Hearts, Spades, Clubs, and Diamonds.

If I have

type Card = (Value, Suite)

Is it possible to create a show function that would transform (A, Spades) into the string "AS"?

like image 843
Markeazy Avatar asked Dec 08 '22 19:12

Markeazy


2 Answers

You should define a newtype (or data type) for Card, the write the Show instance for it.

newtype Card = Card (Value,Suite)

instance Show Card where
  show (Card (v,s)) = show v ++ show s

You could also enable TypeSynonymInstances and write the instance for Card as you wrote it.

Edit: I should probably also mention that a type synonym is not the idiomatic/Haskell-ish way to handle your situation. A Card is semantically different from a pair of Value and Suite, which could represent (for example) some initial condition in a card game, and not necessarily an actual card.

like image 159
Lazersmoke Avatar answered May 05 '23 15:05

Lazersmoke


You probably ought to define your own data type instead of using (,).

data Card = Card Value Suite

instance Show Card where
    show (Card v s) = show v ++ show s
like image 26
Chris Martin Avatar answered May 05 '23 14:05

Chris Martin