F# modeling playing cards

后端 未结 2 581
粉色の甜心
粉色の甜心 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"
    
    0 讨论(0)
  • 2020-12-11 18:54

    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 Для продолжения нажмите любую клавишу . . .

    0 讨论(0)
提交回复
热议问题