我正在尝试以字符串格式输出一手牌,但是我不能从牌的等级中删除单词“ Numeric”,我宁愿不使用辅助函数来执行此操作,因为它看起来确实很乱,任何建议在没有帮助功能的情况下执行此操作。另外,当我使用display
功能时,我在前奏中使用putStr (display x)
。这是到目前为止的代码:
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"
我宁愿不使用辅助功能也要这样做,因为它看起来确实很凌乱
假设您具有类似以下类型的内容,
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)
然后编写辅助函数会很有意义
displayRank :: Rank -> String
displayRank (Numeric n) = show n
displayRank otherRank = show otherRank
displaySuit :: Suit -> String
displaySuit = show
displayCard :: Card -> String
displayCard (Card rank suit) = ...
但是您也可以将它们组合:
displayCard :: Card -> String
displayCard (Card (Numeric n) suit) = ...
displayCard (Card otherRank suit) = ...
具有正确设计的辅助函数并不麻烦。相反。
您用show (rank c)
完成的工作,
rank :: Card -> Rank
show :: Rank -> String
您可以用displayRank (rank c)
完成
rank :: Card -> Rank
displayRank :: Rank -> String
(谈到类型)。