如何在Haskell中以某种方式操作类?

问题描述 投票:0回答:1

我正在尝试重新排列纸牌(或纸牌的Hand)的顺序。本质上是洗手。即,我想将fullDeck随机排列。但是,由于我还是Haskell的新手,请提供任何帮助,包括代码和类等:

data Hand = Empty | Add Card Hand
            deriving (Eq, Show)

data Card = Card Rank Suit
      deriving (Eq, Show)

data Rank = Numeric Integer | Jack | Queen | King | Ace
            deriving (Eq, Show)

data Suit = Hearts | Spades | Diamonds | Clubs
            deriving (Eq, Show)

-- Here is how the deck is being made, constructed.

fullDeck :: Hand
fullDeck = createHandFromList (suitedCardList Clubs ++
                suitedCardList Diamonds ++
                suitedCardList Hearts ++
                suitedCardList Spades) Empty

suitedCardList :: Suit -> [Card]
suitedCardList s = [Card r s | r <- [Numeric 2, Numeric 3, Numeric 4,
                                     Numeric 5, Numeric 6, Numeric 7,
                                     Numeric 8, Numeric 9, Numeric 10,
                                     Jack, Queen, King, Ace]]

createHandFromList :: [Card] -> Hand -> Hand
createHandFromList [] h     = h
createHandFromList (c:cs) h = Add c (createHandFromList cs h)

draw :: Hand -> Hand -> (Hand, Hand)
draw Empty h       = error "draw: The deck is empty."
draw (Add c h1) h2 = (h1, Add c h2)

shuffleDeck :: StdGen -> Hand -> Hand
shuffleDeck g Empty = Empty
shuffleDeck g h     = undefined

[所以,我对如何编码shuffleDeck以使其改写感到非常好奇,我认为重要的一点是,Deck或Hand可以互换使用,因为Deck是卡片的集合,就像手一样。

到目前为止,我已经尝试实现许多辅助函数,但是我不确定这是朝着正确还是错误的方向前进...

takeNthCard :: Hand -> Integer -> (Card, Hand)
takeNthCard h 0 = (nthCard, Add nthCard h) --Move nth card to hand
takeNthCard h n = n - 1 --(and move along list of cards)

非常感谢您提供任何建议!

haskell typeclass
1个回答
0
投票

Enum类型可以枚举:

© www.soinside.com 2019 - 2024. All rights reserved.