F#建模扑克牌 [英] F# modeling playing cards

查看:92
本文介绍了F#建模扑克牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在F#中表示标准扑克牌.我的目标是实现游戏的 Microsoft Solitaire (Windows附带的游戏)的克隆.卡的衣服,脸和颜色很重要.此练习主要是为了学习一些F#.

I am trying to represent standard playing cards in F#. My goal is to implement a clone of Microsoft Solitaire (the one that comes with Windows) , a game in which Cards' Suit, Face, and Color are important. This exercise is mostly intended as a way to learn some F#.

我曾考虑使用歧视性联合:

I have considered using discriminated unions:

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;
}

但是,可以从套装中推断出卡片的颜色-所有钻石和心形都是红色,而所有球杆和黑桃都是黑色.不能仅从颜色"确定西装.也许这样的事情是合适的:

However, a Card's Color can be inferred from its Suit—all Diamonds and Hearts are Red, and all Clubs and Spades are Black. Suit cannot be determined from Color alone. Perhaps something like this is appropriate:

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;
}

但这似乎不正确,因为这允许不正确的组合,例如黑色的心和红色的黑桃.

But this doesn't seem right, since this allows incorrect combinations, e.g. Black Hearts and Red Spades.

我的问题是:

  1. 考虑颜色取决于西服,最常见的处理西服和颜色的方法是什么?
  2. 是否应该明确表示颜色"的概念?从理论上讲,可以用与钻石或红心(红色)和棍棒或黑桃(黑色)的图案匹配替换所有出现的颜色.

推荐答案

由于始终可以从Suit推断出Color,因此没有必要对其进行显式建模;您将要使非法国家不可代表.

Since Color can always be inferred from Suit, there's no reason to model it explicitly; you'll want to make illegal states unrepresentable.

使用这将使您能够在Suit上进行模式匹配,例如以下示例:

This would enable you to pattern match on Suit, like this inane example:

let printColor card =
    match card.Suit with
    | Red -> "Red"
    | Black -> "Black"

FSI的用法示例:

> printColor { Suit = Spades; Face = Ace };;
val it : string = "Black"
> printColor { Suit = Diamonds; Face = King };;
val it : string = "Red"

这篇关于F#建模扑克牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆