在定义Haskell后如何使用Haskell中的数据类型?

时间:2017-10-17 05:26:42

标签: haskell types

我为一副纸牌定义了数据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]

有人能举例说明如何使用这些吗?

1 个答案:

答案 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