Skip to content

Commit dece4aa

Browse files
committed
Report errors.
1 parent a656422 commit dece4aa

File tree

1 file changed

+23
-18
lines changed

1 file changed

+23
-18
lines changed

haskell/fallout.hs

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -32,26 +32,31 @@ startGame = do
3232

3333
game words secret
3434

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+
3549
game words secret = do
3650
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
5560

5661
won = do
5762
putStrLn "Love u"

0 commit comments

Comments
 (0)