Skip to content

Instantly share code, notes, and snippets.

@d6y
Created December 23, 2016 13:28
Show Gist options
  • Save d6y/82e574575189824dd9cae4c631a9943e to your computer and use it in GitHub Desktop.
Save d6y/82e574575189824dd9cae4c631a9943e to your computer and use it in GitHub Desktop.
IO notes for Functional Brighton

IO

Basic concepts and mechanisms

  • pure functions, no side effects, good for reasoning
  • IO system separates pure functions from side-effects
  • Hello world, various ways to run it
  • putStrLn and getLine, do notation
  • Types of IO () and IO String
  • Reverse example, with IF and recursive call
  • Values you can pass around, executed by main (or in the REPL, or by unsafePerformIO)

More functions (some via import Control.Monad)

  • putChar, putStr, print, getChar
  • when
  • sequence :: [IO a] -> IO [a]
  • mapM and mapM_ (map and then sequence)
  • forM
  • forever
  • getContents
  • interact

System functions

From import System.IO, and System.Directory

  • openFile, hGetContents, hClose, and withFile
  • hGetLine, hPutStr, hPutStrLn, hGetChar
  • readFile, writeFile, appendFile
  • doesFileExist
  • hSetBuffering, BufferMode (NoBuffering, LineBuffering, BlockBuffering (Maybe Int)), hFlush.
  • openTempFile, removeFile, renameFile

### From System.Environment

  • getProgName, getArgs

From System.Random

Run stack install random or cabal install random

  • random, randoms, randomR, randomRs
  • RandomGen, Random
  • StdGen, mkStdGen, getStdGen, newStdGen

E.g.,

random (mkStdGen 100) :: (Bool, StdGen)

ByteStrings

  • Data.ByteString (strict) and Data.ByteString.Lazy.
  • Word8 (range 0-255)
  • pack, unpack
  • cons (lazy), cons' (strict), empty
  • fromChunks, toChunks
  • functions with same name as those in List
  • functions with same name as System.IO
import qualified Data.ByteString.Lazy as B  
import qualified Data.ByteString as S 

IO Code can throw exceptions

  • as can pure code (such as div 4 0 or head [])
  • can be caught in IO only
  • catch (from import Control.Exception.Base)
  • IOError
  • isDoesNotExistError (in System.IO.Error), isAlreadyExistsError ...
  • userError, ioError

Exercises

1. Lottery

From: https://github.com/noelmarkham/learn-you-a-haskell-exercises/blob/master/09-input-and-output.hs

{- Write a lottery number picker
 - This function should take a StdGen instance, and produce a list of six unique numbers between 1 and 49, in numerical order
 -}
lottery :: StdGen -> [Int]
lottery gen = undefined

2. Xmas

Draw an ASCII xmas tree. E.g., combine triangle(s) and rectangle. The program should accept the height of the tree as input.

Inspiration: https://duckduckgo.com/?q=ascii+christmas+tree&t=ffab&iax=1&ia=images

E.g.,

How tall a tree? 3

   *
  ***
 *****
   |
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment