列出具有边界的haskell数据类型
问题描述:
我具有以下表示卡的类型定义:
I have the following type definitions to represent cards:
data Suit = Hearts | Spades | Diamonds | Clubs
data Rank = Numeric Integer | Jack | Queen | King | Ace
data Card = Card Rank Suit
data Deck = None | Cons Card Deck
数字整数代表2到10的等级.
Numeric Integer represents ranks from 2 to 10.
现在,我想编写一个函数来获取完整提示:
Now I want to write a function to get the full deck:
fullDeck :: Deck
我如何以最优雅的方式生成完整的牌组?我了解其中一些定义很丑陋,但我没有选择这个自由的机会.
How could I generate the full deck in the most elegant way? I understand that some of these definitions are ugly but I have no freedom to choose this.
谢谢
答
类似
-- Not sure why you're reinventing a list but
fromList :: [Card] -> Deck
fromList = foldr Cons None
fullDeck = fromList [Card r s | s <- [Hearts, Spades, Diamonds, Clubs]
, r <- map Numeric [2..9]++[Jack, Queen, King, Ace]]
看起来不错吗?我们只是使用列表推导生成所有可能性的列表,而不是将其砸成Deck
.
Look nice? we're just using list comprehensions to generate a list of all possibilities than smashing it into a Deck
.