Skip to content

Instantly share code, notes, and snippets.

@axhixh
Created July 19, 2019 13:29
Show Gist options
  • Select an option

  • Save axhixh/21bf1fd1c48d0dcccfcac9c293fa86f6 to your computer and use it in GitHub Desktop.

Select an option

Save axhixh/21bf1fd1c48d0dcccfcac9c293fa86f6 to your computer and use it in GitHub Desktop.
Coin Flip Game from Functional Programming Simplified book
module Game
open System
type GameState =
{ numFlips : int
numCorrectGuesses : int }
// using this instead of strings like the book
type FlipResult =
| Head
| Tail
let showPrompt() =
printf "\n(h)eads, (t)ails, or (q)quit: "
let getUserInput() =
let input = Console.ReadLine().Trim().ToUpper()
match input with
| "H" -> Some Head
| "T" -> Some Tail
| _ -> None
let printableFlipResult flip =
match flip with
| Head -> "Heads"
| Tail -> "Tails"
let printGameStateOnly gameState =
printfn "#Flips: %i, #Correct: %i" gameState.numFlips
gameState.numCorrectGuesses
let printGameState printableResult gameState =
printf "Flip was %s. " printableResult
printGameStateOnly gameState
let printGameOver () =
printfn "\n==== GAME OVER ===="
let tossCoin (r : Random) =
match r.Next(2) with
| 0 -> Head
| 1 -> Tail
| _ -> failwith "unexpected random value"
let rec mainLoop state random =
showPrompt ()
match getUserInput () with
| None ->
printGameOver ()
printGameStateOnly state
| Some guess ->
let tossResult = tossCoin random
let correctGuesses =
match guess, tossResult with
// can also do | x, y when x = y ->
| Head, Head | Tail, Tail -> state.numCorrectGuesses + 1
| _ -> state.numCorrectGuesses
let newState =
{ numFlips = state.numFlips + 1
numCorrectGuesses = correctGuesses }
printGameState (printableFlipResult tossResult) newState
mainLoop newState random
[<EntryPoint>]
let main argv =
let state =
{ numFlips = 0
numCorrectGuesses = 0 }
mainLoop state (Random())
0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment