I am trying to output a hand of cards in string format, but I can't drop the word "Numeric" from the rank of the card, I would prefer to do this without a helper function because it seems really messy, any recommendations to do this without a helper function. Also, when I'm using the display
function, I'm using putStr (display x)
in the Prelude. Here's the code so far for it:
displayCard :: Card -> String
displayCard c = show (rank c) ++ " of " ++ show (suit c) ++ "\n"
display :: Hand -> String
display Empty = "\n"
display (Add c h) = displayCard c
++ display h
displayRank :: Rank -> String
displayRank (Numeric 2) = "2"
displayRank (Numeric 3) = "3"
displayRank (Numeric 4) = "4"
displayRank (Numeric 5) = "5"
displayRank (Numeric 6) = "6"
displayRank (Numeric 7) = "7"
displayRank (Numeric 8) = "8"
displayRank (Numeric 9) = "9"
displayRank (Numeric 10) = "10"
displayRank Jack = "Jack"
displayRank Queen = "Queen"
displayRank King = "King"
displayRank Ace = "Ace"
I would prefer to do this without a helper function because it seems really messy
Assuming you have something like the following types,
data Card = Card { cardRank :: Rank, cardSuit :: Suit }
deriving (Eq, Show)
data Rank = Numeric Int | Jack | Queen | King | Ace
deriving (Eq, Show)
data Suit = Diamonds | Clubs | Hearts | Spades
deriving (Eq, Show)
then it would make sense to write helper functions
displayRank :: Rank -> String
displayRank (Numeric n) = show n
displayRank otherRank = show otherRank
displaySuit :: Suit -> String
displaySuit = show
displayCard :: Card -> String
displayCard (Card rank suit) = ...
but you could also combine them:
displayCard :: Card -> String
displayCard (Card (Numeric n) suit) = ...
displayCard (Card otherRank suit) = ...
Having properly designed helper functions is not messy. On the contrary.
What you accomplish with show (rank c)
,
rank :: Card -> Rank
show :: Rank -> String
you can accomplish with displayRank (rank c)
rank :: Card -> Rank
displayRank :: Rank -> String
(speaking of types).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.