Last active
January 2, 2016 11:59
-
-
Save pasberth/8299976 to your computer and use it in GitHub Desktop.
whileを使ったループ
This file contains hidden or 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 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