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\' Sui
Since Color
can always be inferred from Suit
, there's no reason to model it explicitly; you'll want to make illegal states unrepresentable.
You can still get a nice programming experience out of your model, and have a nice way of modelling colour, using an Active Pattern:
type Suit =
| Diamonds
| Hearts
| Clubs
| Spades
let (|Red|Black|) suit =
match suit with
| Diamonds | Hearts -> Red
| Clubs | Spades -> Black
This would enable you to pattern match on Suit
, like this inane example:
let printColor card =
match card.Suit with
| Red -> "Red"
| Black -> "Black"
Usage example from FSI:
> printColor { Suit = Spades; Face = Ace };;
val it : string = "Black"
> printColor { Suit = Diamonds; Face = King };;
val it : string = "Red"
You can add a recording method:
type Card =
{suit: Suit;face: Face}
member this.Color =
match this.suit with
| Diamonds | Hearts -> Red
| Clubs | Spades -> Black
Example:
let v = {suit = Diamonds;face = Two}
printfn "%A" v.Color
let v1 = {suit = Clubs;face = Two}
printfn "%A" v1.Color
Red Black Для продолжения нажмите любую клавишу . . .