F# modeling playing cards

后端 未结 2 588
粉色の甜心
粉色の甜心 2020-12-11 18:24

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

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-11 18:38

    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"
    

提交回复
热议问题