我正在尝试在F#中表示标准扑克牌。我的目标是实现 Microsoft Solitaire的克隆版(附带于Windows),这个游戏中花色、面值和颜色是重要的。此练习主要旨在学习一些F#。
我考虑使用判别联合:
type Suit =
| Diamonds
| Hearts
| Clubs
| Spades
type Color =
| Red
| Black
type Face =
Two | Three | Four | Five | Six | Seven |
Eight | Nine | Ten | Jack | Queen | King | Ace
使用记录类型来表示卡片:
type Card = {
suit: Suit;
face: Face;
color: Color;
}
然而,从花色可以推断出卡牌的颜色——所有方块和红桃都是红色的,所有梅花和黑桃都是黑色的。仅凭颜色无法确定花色。也许这样比较合适:
type Suit =
| Diamonds of Color //should always be red
| Hearts of Color //should always be red
| Clubs of Color //should always be black
| Spades of Color //should always be black
type Face =
Two | Three | Four | Five | Six | Seven |
Eight | Nine | Ten | Jack | Queen | King | Ace
type Card = {
suit: Suit;
face: Face;
}
但这似乎不正确,因为它允许不正确的组合,例如黑桃和红心。
我的问题是:
- 考虑到颜色依赖于花色,处理花色和颜色的最惯用方式是什么?
- 是否应明确表示颜色概念?理论上可以将所有颜色实例替换为钻石或红心(红色)和梅花或黑桃(黑色)的模式匹配。