File tree Expand file tree Collapse file tree 1 file changed +23
-18
lines changed Expand file tree Collapse file tree 1 file changed +23
-18
lines changed Original file line number Diff line number Diff line change @@ -32,26 +32,31 @@ startGame = do
32
32
33
33
game words secret
34
34
35
+ readIndex :: Int -> Int -> IO (Either String Int )
36
+ readIndex lowerLimit upperLimit = do
37
+ putStr " YOUR ANSWER >> "
38
+ maybeIdx <- fmap (readMaybe) getLine :: IO (Maybe Int )
39
+ case maybeIdx of
40
+ Nothing -> return $ Left " Invalid number"
41
+ Just idx -> if isIndexWithinRange lowerLimit upperLimit idx then
42
+ return $ Right idx
43
+ else
44
+ return $ Left ( " Number should be between " ++ (show lowerLimit) ++ " and " ++ (show upperLimit) )
45
+
46
+ isIndexWithinRange :: Int -> Int -> Int -> Bool
47
+ isIndexWithinRange lowerLimit upperLimit idx = idx >= lowerLimit && idx <= upperLimit
48
+
35
49
game words secret = do
36
50
printWords words
37
- putStr " YOUR ANSWER >> "
38
-
39
- idxStr <- getLine
40
- let maybeIdx = readMaybe idxStr :: Maybe Int
41
-
42
- case maybeIdx of
43
- Nothing -> game words secret
44
- Just idx -> do
45
- if idx < 0 || idx >= (length words ) then
46
- game words secret
47
- else do
48
- let selection = words !! ((length words ) - idx - 1 )
49
-
50
- if selection == secret then
51
- won
52
- else do
53
- report secret selection
54
- game words secret
51
+ eitherIdx <- readIndex 0 ((length words ) - 1 )
52
+ case eitherIdx of
53
+ Left errorMessage -> print errorMessage >> game words secret
54
+ Right idx -> do
55
+ let selection = words !! (((length words ) - idx) - 1 )
56
+ print selection
57
+ if selection == secret then
58
+ won
59
+ else report secret selection >> game words secret
55
60
56
61
won = do
57
62
putStrLn " Love u"
You can’t perform that action at this time.
0 commit comments