如何在Haskell中从构造函数转换为字符串



我正试图以字符串格式输出一手牌,但我无法从牌的等级中删除"数字"一词,我更喜欢在没有辅助功能的情况下这样做,因为这看起来真的很混乱,任何建议都可以在没有辅助函数的情况下进行。此外,当我使用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

(说到类型(。

相关内容

  • 没有找到相关文章

最新更新