gpt4 book ai didi

haskell - 从枚举到枚举实例?

转载 作者:行者123 更新时间:2023-12-04 14:57:07 26 4
gpt4 key购买 nike

data Suit = Spade | Heart | Club | Diamond deriving (Eq, Ord, Enum, Show)

data Pip = Ace | Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King deriving (Eq, Ord, Enum, Show)

data Card = Card
{suit :: Suit
,pip :: Pip
} deriving (Eq,Ord, Show)

type Deck = [Card]

data EOBoard = EOBoard
{foundations :: [Deck]
,columns :: [Deck]
,reserve :: [Deck]
} deriving (Eq, Ord, Show)

instance Enum Card where

这是一个纸牌数据结构
如何制作 Card可枚举的,带有 Enum实例来自 Card{suit = Spade, pip = Ace} , Card{suit = Spade, pip = Two} .. Card{suit = Heart, pip = Ace} .. Card{suit = Club, pip = Ace} .. Card{suit = Diamond, pip = Ace} ..Card{suit = Diamond, pip = King} .

最佳答案

这是我的做法(基本上是@epsilonhalbe 的想法):

data Suit
= Spade | Heart | Club | Diamond
deriving (Eq, Ord, Enum, Show, Bounded)

data Pip
= Ace | Two | Three | Four | Five | Six | Seven | Eight | Nine
| Ten | Jack | Queen | King
deriving (Eq, Ord, Enum, Show, Bounded)

data Card = Card
{ suit :: Suit
, pip :: Pip
} deriving (Eq,Ord, Show, Bounded)

instance Enum Card where
toEnum i =
let (d,m) = i `divMod` (fromEnum (maxBound :: Pip) + 1)
in Card (toEnum d) (toEnum m)
fromEnum (Card s p) = fromEnum s * (fromEnum (maxBound :: Pip) + 1) + fromEnum p

这给了你:
λ> take 5 $ [minBound .. maxBound] :: [Card]
[Card {suit = Spade, pip = Ace},Card {suit = Spade, pip = Two},Card {suit = Spade, pip = Three},Card {suit = Spade, pip = Four},Card {suit = Spade, pip = Five}]

PS:现在你应该得到所有 - 抱歉我搞砸了 maxBound忘记一个额外的

关于haskell - 从枚举到枚举实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33785138/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com