Skip to content

Instantly share code, notes, and snippets.

@gusty
Forked from isaacabraham/io-monad.fsx
Last active May 28, 2019 07:20
Show Gist options
  • Save gusty/3a9d654de320225e4a17d92049646160 to your computer and use it in GitHub Desktop.
Save gusty/3a9d654de320225e4a17d92049646160 to your computer and use it in GitHub Desktop.
F# port of the first half of John De Goes "FP to the max" (https://www.youtube.com/watch?v=sxudIMiOo68)
#load @".paket\load\net452\FSharpPlus.fsx"
open FSharpPlus
open System
[<AutoOpen>]
module SideEffects =
let private r = Random()
let printLn text = async { printfn "%s" text }
let readLn() = async { return Console.ReadLine() }
let random upper = async { return r.Next(0, upper) }
let rec checkContinue name = monad {
do! printLn ("Do you want to continue, " + name + "?")
let! answer = readLn() |> map String.toLower
return!
match answer with
| "y" -> result true
| "n" -> result false
| _ -> checkContinue name }
let rec gameLoop name = monad {
let! secret = random 5 |> map ((+) 1)
do! printLn ("Dear " + name + ", please guess a number from 1 to 5:")
let! input = readLn()
do!
match tryParse input with
| None -> printLn "You did not enter a number!"
| Some x when x = secret -> printLn ("You guessed right, " + name + "!")
| Some _ -> printLn (sprintf "You guessed wrong, %s! The number was: %d" name secret)
let! shouldContinue = checkContinue name
return!
if shouldContinue then gameLoop name
else result () }
let main = monad {
do! printLn "What is your name?"
let! name = readLn()
do! printLn ("Hello, " + name + " welcome to the game!")
do! gameLoop name
return() }
Async.RunSynchronously main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment