Created
February 2, 2015 15:26
-
-
Save sortega/94b00dadbbf3b2f05ad4 to your computer and use it in GitHub Desktop.
Naïe pick/guess implementation
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
import System.Environment | |
import System.Exit | |
import System.Random | |
import System.IO | |
data Feedback = Smaller | Bigger | Done deriving (Show, Eq) | |
type Guess = Int | |
type Range = (Int, Int) | |
range = (1, 100) | |
main :: IO () | |
main = do | |
args <- getArgs | |
hSetBuffering stdout LineBuffering | |
case args of | |
["pick"] -> pick | |
["guess"] -> guess | |
_ -> usage | |
usage :: IO () | |
usage = do | |
putStrLn "usage: ( pick | guess )" | |
exitWith (ExitFailure 1) | |
pick :: IO () | |
pick = randomRIO range >>= putStrLn . show | |
guess :: IO () | |
guess = interact $ formatGuesses . guess' range . parseFeedback | |
parseFeedback :: String -> [Feedback] | |
parseFeedback = map parse . lines | |
where parse l = case l of | |
"+" -> Bigger | |
"-" -> Smaller | |
_ -> Done | |
formatGuesses :: [Guess] -> String | |
formatGuesses = unlines . map show | |
guess' :: Range -> [Feedback] -> [Guess] | |
guess' (lower, upper) feedback = pivot : nextGuesses | |
where pivot = (upper + lower) `div` 2 | |
nextGuesses = case feedback of | |
(Bigger : nextFeedback) -> guess' (succ pivot, upper) nextFeedback | |
(Smaller : nextFeedback) -> guess' (lower, pred pivot) nextFeedback | |
_ -> [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment