7. IO

Created Saturday 23 August 2014

Overview

Hello World

main = putStrLn "Hello World"
  1. Save as "HelloWorld.hs"
  2. Type "ghc HelloWorld.hs"
  3. Run HelloWorld executable

IO Actions

main = putStrLn "Hello World"

putStrLn :: String -=> IO ()

Do Blocks

main :: IO ()
main = do
putStrLn "Hello"
putStrLn "World"

helloWorld :: IO ()
helloWorld = putStrLn "Hello World"

main :: IO ()
main = do
helloWorld
helloWorld
helloWorld

introduce :: String -> String -> IO ()
introduce name1 name2 = do
putStrLn (name1 ++ ", this is " ++ name2)
putStrLn (name2 ++ ", this is " ++ name1)

main :: IO ()
main = do
introduce "Alice" "Bob"
introduce "Alice" "Sally"

IO Values

main :: IO ()
main = do
line <- getLine
putStrLn ("you said: " ++ line)

getLine :: IO String

greet :: IO ()
greet = do
putStrLn "Who are you?"
who <- getLine
putStrLn ("Hello " ++ who)
greetForever :: IO ()
greetForever = do
greet
greetForever
main :: IO ()
main = greetForever
ERROR
extractValue :: IO a -> a

return Function

return :: a -> IO a

promptInfo :: IO (String, String)
promptInfo = do
putStrLn "What is your name?"
name <- getLine
putStrLn "What is your favorite color?"
color <- getLine
return (name, color)

main :: IO ()
main = do
(name, color) <- promptInfo
putStrLn ("Hello " ++ name)
putStrLn ("I like " ++ color ++ " too!")

Combine 2 inputs into one IO action
main :: IO ()
main = do
line1 <- getLine
line2 <- getLine
lines <- return (line1 ++ line2)
putStrLn lines
But the right way to do this...
main :: IO ()
main = do
line1 <- getLine
line2 <- getLine
let lines = line1 ++ line2
putStrLn lines

Some Useful IO Actions

putStrLn :: String -> IO ()
getLine :: IO String
print :: (Show a) => a -> IO ()
readFile :: FilePath -> IO String
writeFile :: FilePath -> String -> IO ()
appendFile :: FilePath -> String -> IO ()
interact :: (String -> String) -> IO ()
reverseLines :: String -> String
reverseLines input =
unlines (map reverse (lines input))
main :: IO ()
main = interact reverseLines

Program Organization

encrypt :: Char -> Char
encrypt c
| 'A' <= c && c < 'Z' =
toEnum (fromEnum 'A' + 1)
| c == 'Z' = 'A'
| otherwise = c
DON'T
handleChar :: IO ()
handleChar = do
c <- getChar
let u = encrypt c
putChar c

inputLoop :: IO ()
inputLoop = do
handleChar
inputLoop

main :: IO ()
main = inputLoop
INSTEAD DO
main :: IO ()
main = interact (map encrypt)



Backlinks: