Skip to content

Instantly share code, notes, and snippets.

@gabebw
Created September 9, 2015 04:38
Show Gist options
  • Save gabebw/d8b159acdd993bc60b68 to your computer and use it in GitHub Desktop.
Save gabebw/d8b159acdd993bc60b68 to your computer and use it in GitHub Desktop.
LYAH: Ch 9, I/O
Hey there
line two
whoa
import System.Random
import System.IO
import System.Environment
import Control.Monad (forever)
-- forever :: Monad m => m a -> m b
printForever :: (Show a) => a -> IO b
printForever a = forever (print a)
printRandomNumber :: IO ()
printRandomNumber = do
n <- randomIO :: IO Int
print n
-- Unix `wc` program: `interact` reads all of STDIN and runs the provided
-- function (String -> String) over it
wc :: IO ()
wc = interact (\s -> (show $ length s) ++ "\n")
fileStuff :: IO String
fileStuff = do
putStrLn ""
contents <- readFile "file.txt"
putStrLn ">> Contents of file.txt:"
putStrLn contents
writeFile "hey.txt" "Hi everyone!"
putStrLn ">> Reading out hey.txt, which we just wrote:"
handle <- openFile "hey.txt" ReadMode -- gives us a Handle
putStrLn ">> First line of hey.txt:"
hGetLine handle
putStrLn ">> Rest of hey.txt:"
hGetContents handle
-- How to desugar:
-- http://www.haskellforall.com/2014/10/how-to-desugar-haskell-code.html
printRandomNumber' :: IO ()
printRandomNumber' = (randomIO :: IO Int) >>= (\n -> print n)
printRandomNumber'' :: IO ()
printRandomNumber'' = (randomIO :: IO Int) >>= print
-- >>= :: (Monad m) => m a -> (a -> m b) -> m b
-- Above: IO is the monad `m`
-- IO a -> (a -> IO b) -> IO b
-- randomIO is of type IO a, here cast to IO Int, so a is Int:
-- IO Int -> (Int -> IO b) -> IO b
-- print is (Int -> IO b), since it takes anything Showable and gives `IO ()`:
-- IO Int -> (Int -> IO ()) -> IO ()
-- Thus the return type is IO ()
* Haskell I/O is lazy like everything else
* New I/O control functions: `forever`, `interact`
* New I/O actions: `openFile`, `readFile`, `writeFile`, `withFile`, `appendFile`
* File handle functions: `hGetContents`, `hGetLine`, etc
* Random numbers: `random`, `randomR`, `mkStdGen`, `getStdGen`
#!/bin/sh
cabal install random
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment