我为一副纸牌定义了数据Suit
和数据Value
。我还定义了类型Card
并输入Deck
。但我不知道如何使用它们。
data Suit = Club | Diamond | Heart | Spade
data Value = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten |
Jack | Queen | King | Ace
type Card = (Suit, Value)
type Deck = [Card]
有人能举例说明如何使用这些吗?
答案 0 :(得分:4)
我要在你的类型中添加一些派生实例。
data Suit = Club | Diamond | Heart | Spade
deriving (Bounded, Enum, Eq, Ord, Show)
data Value
= Two | Three | Four | Five | Six | Seven | Eight
| Nine | Ten | Jack | Queen | King | Ace
deriving (Bounded, Enum, Eq, Ord, Show)
type Card = (Suit, Value)
type Deck = [Card]
这是一些套牌。
royalFlush :: Deck
royalFlush = [ (Spade, v) | v <- [Ten .. Ace] ]
completeDeck :: Deck
completeDeck =
[ (s, v) | v <- [minBound .. maxBound], s <- [minBound .. maxBound] ]
这是一个能够找到牌组中所有球杆的功能。
filterClubs :: Deck -> Deck
filterClubs = filter (\(s, v) -> s == Club)
在random
包的帮助下,我们可以选择一张随机卡片:
import System.Random
randomCard :: IO Card
randomCard =
let r xs = (xs !!) <$> randomRIO (0, length xs - 1)
in (,) <$> r [minBound .. maxBound] <*> r [minBound .. maxBound]
更好的是,让我们使用random-shuffle
包,现在我们可以洗牌:
import System.Random.Shuffle
shuffleDeck :: Deck -> IO Deck
shuffleDeck = shuffleM
这是一个功能,可以告诉你bridge中每个技巧对于一次不加倍的下注有多少分值。
import Numeric.Natural
points :: Suit -> Natural
points Heart = 30
points Spade = 30
points Club = 20
points Diamond = 20