Skip to content

Instantly share code, notes, and snippets.

@pasberth
Last active January 2, 2016 11:59
Show Gist options
  • Select an option

  • Save pasberth/8299976 to your computer and use it in GitHub Desktop.

Select an option

Save pasberth/8299976 to your computer and use it in GitHub Desktop.
whileを使ったループ
import Data.IORef
doWhile :: Monad m => m Bool -> m a -> m a
doWhile test body = do
x <- body
testResult <- test
if testResult
then doWhile test body
else return x
while :: Monad m => m Bool -> m a -> m (Maybe a)
while test body = do
testResult <- test
if testResult
then doWhile test body >>= \x -> return (Just x)
else return Nothing
example :: IO ()
example = do
i <- newIORef 0
putStrLn $ "Can you guess the number I have?"
while ((/= 42) `fmap` readIORef i) $ do
a <- getLine
putStrLn $ "You said:" ++ a
writeIORef i $ read a
putStrLn "That's right!"
return ()
example2 :: IO ()
example2 = do
flag <- newIORef True
putStrLn $ "Can you guess the number I have?"
while (readIORef flag) $ do
a <- getLine
putStrLn $ "You said:" ++ a
let i = read a in
writeIORef flag (i /= 42)
putStrLn "That's right!"
return ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment