Skip to content
Haskell

IO and do Notation

Side-effectful programming in Haskell.

By EZ4Code Team
iodo-notation

Code

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; ...

Explanation

IO actions are values describing side effects — they're not executed until main runs them. do notation is sugar for >>= chains. <- binds the result; let binds pure values. readFile/writeFile are convenient for whole-file I/O. Use try to catch IOException. The type system guarantees pure code can't have side effects — IO is clearly marked.

More Haskell Snippets