Skip to content
Haskell

IOとdo記法

Haskellの副作用のあるプログラミング。

#io#do-notation

Code

haskell
main :: IO ()
main = do
  putStrLn "What's your name?"
  name <- getLine
  putStrLn $ "Hello, " ++ name ++ "!"

  -- File I/O
  contents <- readFile "input.txt"
  writeFile "output.txt" (map toUpper contents)

  -- Handle exceptions
  result <- try (readFile "missing.txt") :: IO (Either IOException String)
  case result of
    Right content -> putStrLn content
    Left _        -> putStrLn "File not found"

-- IO actions compose
greet :: String -> IO ()
greet name = putStrLn $ "Hi " ++ name

askAndGreet :: IO ()
askAndGreet = do
  name <- getLine
  greet name

-- Sequencing (ignore result)
echoTwice :: IO ()
echoTwice = do
  getLine >>= putStrLn
  getLine >>= putStrLn
  -- or: l1 <- getLine; putStrLn l1; ...