Skip to content

Instantly share code, notes, and snippets.

@petermarks
Created September 20, 2010 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petermarks/588640 to your computer and use it in GitHub Desktop.
Save petermarks/588640 to your computer and use it in GitHub Desktop.
Number guesser iterations
module Main where
import Data.Char
import Data.List
data Guess
= Guess Int Guess Guess
| GiveUp
| Done
main = do
getLine
guess (guesses 1 100)
guess :: Guess -> IO ()
guess (Guess n lower higher) = do
print n
response <- getLine
guess $ nextGuess response lower higher
guess _ = return ()
nextGuess :: String -> Guess -> Guess -> Guess
nextGuess response lower higher
| "high" `isInfixOf` r = lower
| "low" `isInfixOf` r = higher
| otherwise = Done
where
r = map toLower response
guesses :: Int -> Int -> Guess
guesses lo hi | lo > hi = GiveUp
| otherwise = Guess mid (guesses lo (mid - 1)) (guesses (mid + 1) hi)
where
mid = (lo + hi) `div` 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment