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"
?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With