Guest User

Untitled

a guest
Nov 19th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. -- should probably have used Data.Map for dictionary instead of list of pairs
  2. -- also, 100% of functions are IO actions!
  3.  
  4. import System.IO
  5. import System.Random
  6.  
  7. type Dict = [(String, String)]
  8.  
  9. -- calls main loop with empty dictionary
  10. main :: IO ()
  11. main = mainloop []
  12.  
  13.  
  14. mainloop :: Dict -> IO ()
  15. mainloop dict =
  16. do printGreeting
  17. selection <- getLine
  18. performActivity dict selection
  19.  
  20. -- this probably doesn't need to be its own function
  21. printGreeting :: IO ()
  22. printGreeting = putStrLn "e to enter words into dictionary\ns to start testing"
  23.  
  24. -- procedure called by the main loop to start up either
  25. -- word entry or the test itself
  26. performActivity :: Dict -> String -> IO ()
  27. performActivity dict selection
  28. | selection == "e" = dictEntry dict >>= mainloop
  29. | selection == "s" = doGame dict >> mainloop dict
  30. | otherwise = putStrLn "Invalid entry" >> mainloop dict
  31.  
  32. -- user prompt to enter things into dictionary
  33. -- to do: allow removal from dictionary
  34. -- allow read/write dictionary to/from file
  35. dictEntry :: Dict -> IO Dict
  36. dictEntry dict =
  37. do a <- getLine
  38. if (a == "EXIT") then return dict else
  39. do b <- getLine
  40. if (b == "EXIT") then return dict else
  41. let newdict = (:) (a, b) dict in (dictEntry newdict)
  42.  
  43. -- the actual test component
  44. doGame :: Dict -> IO ()
  45. doGame dict
  46. | dict == [] = putStrLn "No entries in dictionary." >> mainloop dict
  47. | otherwise =
  48. do choice <- randomIndex
  49. let pair = dict !! choice
  50. response <- doQuestion pair
  51. if response == "EXIT"
  52. then return ()
  53. else if response == snd pair
  54. then doGame dict
  55. else putStrLn (snd pair) >> doGame dict
  56. where randomIndex = randomRIO (0, (length dict) - 1)
  57.  
  58. -- prints word to translate and accepts user input
  59. doQuestion :: (String, String) -> IO String
  60. doQuestion pair =
  61. do putStrLn $ fst pair
  62. getLine
Add Comment
Please, Sign In to add comment