Created
September 20, 2010 20:59
-
-
Save petermarks/588640 to your computer and use it in GitHub Desktop.
Number guesser iterations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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