Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Testing out the functional way to keep state.
- namespace Test3
- open System
- type GameState = {
- Name : string;
- Light : bool;
- ShouldQuit : bool;
- }
- module Game =
- let private initialState = {
- Name = "noNameInput";
- Light = false;
- ShouldQuit = false;
- }
- type Quit = GameState -> GameState
- let private quit:Quit = fun gs ->
- printfn "\nGoodbye, %s. Have a nice day." gs.Name
- { gs with ShouldQuit = true }
- type LightSwitch = GameState -> string -> GameState
- let private lightSwitch:LightSwitch = fun gs input ->
- match input with
- | "ON" ->
- match gs.Light with
- | true -> printfn "The light is already ON."; gs
- | false -> { gs with Light = true }
- | "OFF" ->
- match gs.Light with
- | false -> printfn "The light is already OFF."; gs
- | true -> { gs with Light = false }
- | _ -> gs
- type InitGame = unit -> GameState
- let initGame:InitGame = fun () ->
- printf "Enter your name: "
- let nameinit = Console.ReadLine().ToUpper()
- let name = if nameinit.Length > 0 then nameinit else "[SUBJECT NAME HERE]"
- printfn "Hello %s, welcome to Test 3." name
- { initialState with Name = name }
- type RunGame = GameState -> GameState
- let runGame:RunGame = fun gs ->
- printfn "Enter a state for the light (ON/OFF/QUIT):"
- printf "> "
- let input = Console.ReadLine().ToUpper()
- match input with
- | "ON" | "OFF" -> lightSwitch gs input
- | "Q" | "QUIT" | "BYE" -> quit gs
- | _ -> printfn "Sorry %s, that is invalid.\n" gs.Name; gs
- type GameStatus = GameState -> unit
- let gameStatus:GameStatus = fun gs ->
- printf "\nLight State: "
- match gs.Light with
- | false -> printfn "OFF"
- | true -> printfn "ON"
- module Main =
- [<EntryPoint>]
- let main args =
- let gs = Game.initGame ()
- let rec loop gss =
- if gss.ShouldQuit = true then exit 0
- Game.gameStatus gss
- Game.runGame gss |> loop
- loop gs
- 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement