Advertisement
konalisp

test.fs

Oct 13th, 2015
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 2.20 KB | None | 0 0
  1. //Testing out the functional way to keep state.
  2. namespace Test3
  3.  
  4. open System
  5.  
  6. type GameState = {
  7.     Name : string;
  8.     Light : bool;
  9.     ShouldQuit : bool;
  10.     }
  11.  
  12. module Game =
  13.    
  14.     let private initialState = {
  15.         Name = "noNameInput";
  16.         Light = false;
  17.         ShouldQuit = false;
  18.     }
  19.    
  20.     type Quit = GameState -> GameState
  21.     let private quit:Quit = fun gs ->
  22.         printfn "\nGoodbye, %s. Have a nice day." gs.Name
  23.         { gs with ShouldQuit = true }
  24.    
  25.     type LightSwitch = GameState -> string -> GameState
  26.     let private lightSwitch:LightSwitch = fun gs input ->
  27.         match input with
  28.         | "ON" ->
  29.             match gs.Light with
  30.             | true -> printfn "The light is already ON."; gs
  31.             | false -> { gs with Light = true }
  32.         | "OFF" ->
  33.             match gs.Light with
  34.             | false -> printfn "The light is already OFF."; gs
  35.             | true -> { gs with Light = false }
  36.         | _ -> gs
  37.    
  38.     type InitGame = unit -> GameState
  39.     let initGame:InitGame = fun () ->
  40.         printf "Enter your name: "
  41.         let nameinit = Console.ReadLine().ToUpper()
  42.         let name = if nameinit.Length > 0 then nameinit else "[SUBJECT NAME HERE]"
  43.         printfn "Hello %s, welcome to Test 3." name
  44.         { initialState with Name = name }
  45.    
  46.     type RunGame = GameState -> GameState
  47.     let runGame:RunGame = fun gs ->
  48.         printfn "Enter a state for the light (ON/OFF/QUIT):"
  49.         printf "> "
  50.         let input = Console.ReadLine().ToUpper()
  51.         match input with
  52.         | "ON" | "OFF" -> lightSwitch gs input
  53.         | "Q" | "QUIT" | "BYE" -> quit gs
  54.         | _ -> printfn "Sorry %s, that is invalid.\n" gs.Name; gs
  55.    
  56.     type GameStatus = GameState -> unit
  57.     let gameStatus:GameStatus = fun gs ->
  58.         printf "\nLight State: "
  59.         match gs.Light with
  60.         | false -> printfn "OFF"
  61.         | true -> printfn "ON"
  62.    
  63.  
  64. module Main =
  65.     [<EntryPoint>]
  66.     let main args =
  67.         let gs = Game.initGame ()
  68.         let rec loop gss =
  69.             if gss.ShouldQuit = true then exit 0
  70.             Game.gameStatus gss
  71.             Game.runGame gss |> loop
  72.         loop gs
  73.         0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement