I\'ve been working on modeling a popular card game (Love Letter) using F# to learn more about functional programming.
module Game =
open Cards
open Players
An F# list is immutable, so if deck.IsEmpty
starts out false
, it'll stay false
forever. There's really no reason to make things so complicated, though.
Assume that you have a sorted deck. Let's use only three cards as an example, but assume that it's a full deck:
let deck =
[
{ Suit = Hearts; Face = Queen }
{ Suit = Diamonds; Face = King }
{ Suit = Spades; Face = Ace }
]
You can easily scramble the deck using a random number generator:
let r = Random ()
let scrambledDeck = deck |> List.sortBy (fun _ -> r.Next ())
The first time you create scrambledDeck
, it may look like this in FSI:
> let scrambledDeck = deck |> List.sortBy (fun _ -> r.Next ());;
val scrambledDeck : Card list =
[{Suit = Spades;
Face = Ace;}; {Suit = Hearts;
Face = Queen;}; {Suit = Diamonds;
Face = King;}]
But if you do it again, it might look like this:
> let scrambledDeck = deck |> List.sortBy (fun _ -> r.Next ());;
val scrambledDeck : Card list =
[{Suit = Spades;
Face = Ace;}; {Suit = Diamonds;
Face = King;}; {Suit = Hearts;
Face = Queen;}]
Now you have a scrambled deck, and you can simply start pulling cards off it, for example in order to print them:
scrambledDeck |> List.iter (printfn "%O")