Introduction to Haskell IO

From HaskellWiki
(Redirected from IOIntroDraft)
Jump to navigation Jump to search

This article is a draft, with further revisions planned by User:Newsham. Draft is typically different than stub in that the User:Newsham is normally in an active edit process. Feel free to help by expanding the article..


About this document

XXX. The target audience is a beginning haskell programmer who has some haskell under his belt but is not yet comfortable with IO or monads. The goal is to get the reader proficient in writing useful code as quickly as possible. The pace will be slow and detailed to avoid confusing programmers who are unfamiliar with haskell, may not have a strong background in math or functional programming.


Sections

  1. Introduction to Haskell IO/General introduction
  2. Actions
  3. Introduction to Haskell IO/Introduction to IO
  4. Introduction to Haskell IO/Monadic lifters and IO
  5. Introduction to Haskell IO/Introduction to more IO

Notes

XXX Here is the planned layout - needs to be broken into the above articles

  1. intro
    1. programming in haskell is not hard!
      1. even the scary "monad" stuff.
    2. explain target and goals
      1. what you should already know
        1. partial application, types, constructed types, general haskell stuff..
    3. we'll get you writing code as soon as possible!
    4. describe chapters
      1. skipping around is allowed. the "do" and "IO" lessons have some important concepts that are used throughout. the rest can be read as needed.
  2. talk about do notation and actions
    1. introduce "actions"
      1. actions are inert until executed
      2. actions can be combined into larger actions
      3. actions can return a value or nothing.
      4. we can pretend that actions take parameters (although they dont). this is done by making a function which returns an action THERES A DIFFERENCE BETWEEN AN ACTION AND A FUNCTION THAT MAKES AN ACTION!
      5. action types are monads. there are different types, such as "IO" actions. dont worry about that yet!
    2. introduce "do" as a way to combine actions together
      1. do-binding similar to let-binding, but with an action
      2. show two-action do.
      3. adjacent actions get combined - nesting similar to let-nesting
      4. different rules for combining...
      5. show nested two-action do's
      6. let-binding allowed
      7. "return" is an action that returns its input (like identity). x <- return 5 for example It DOES NOT "return" control flow out of the current action or do block!
      8. the entire do-block is one action.
      9. you can still use things like "if" as long as they evaluate to an action.
        1. if you need multiple actions in a "then" you need a "do" block to combine them down to one action!
        2. we'll see example later to clarify (hope your brain didnt hurt on that)
    3. nested do's
      1. do's as separate functions.
  3. the most important type of actions are IO actions
    1. introducing "IO"
      1. meaning
      2. how it gets invoked
        1. IO actions are inert until "run by main"
      3. combining rule
        1. rule for combining actions: one happens, then the next happens. the results of the first are observable to the second (and successive). IO actions are performed sequentially.
      4. what "return" means
    2. Some simple IO functions (file, cmd)
    3. IO action examples -
      1. printing
      2. reading line
      3. opening file
      4. reading file
      5. make sure to show if/then/else with nested do block!
      6. show some recursion.
    4. examples
      1. read a line, write a line
      2. read a line, increment the value, write that
      3. read two lines, add the value, write that
      4. adding random numbers to user input
    5. an important note about IO monads
      1. you cannot escape! there's a reason for this
      2. unless you cheat: unsafePerformIO
  4. using the "M"s
    1. lifts
      1. what liftM means in IO
        1. liftM is just short for do { x <- act1; return (f x) }
        2. rewrite example of read one line add the vale and write that
      2. what liftM2 means in IO
        1. liftM2 is just short for do { x <- act1; y <- act2; return (x `op` y) }
        2. rewrite example of read two lines add the value and write that
      3. this generalizes - liftM3, liftM4, ...
    2. what fmap means in IO
    3. some control flow in IO
      1. when, unless
      2. replicateM_, replicateM
      3. forM_, forM
      4. mapM_, mapM are just swapped around forM_, forM
      5. loop carried variables: foldM_ and foldM
      6. rewrite previous recursion example using one of these.
      7. show several other examples
      8. exceptions?
      9. there's more...
      10. fixIO?
  5. More IO functions for you
    1. you already know enough to write some complex real-world programs!
      1. throw in a complex example.. open a network socket, connect to a service, interact with it, print a result, and shut down.
    2. which functions?
      1. errors
        1. ioError, userError, catch
      2. command
        1. getArgs, getProgname, getEnv
        2. exitFailure
      3. file and console io
        1. putChar, putStr, putStrLn, print
        2. getChar, getLine, getContents, isEOF
        3. readFile, writeFile
        4. readIO, readLn
        5. openFile :: FilePath -> IOMode -> IO Handle
        6. openBinaryFile
        7. stdin/stdout/stderr
        8. hClose hGetChar hReady
        9. hGetLine hPutChar hPutStr hPutStrLn hPrint, hIsEOF
        10. interact
      4. filesystem
        1. createDirectory, removeDirectory, renameDirectory
        2. setCurrentDirectory
        3. getDirectoryContents, doesFileExist, doesDirectoryExist
      5. random
        1. randomIO, randomRIO
      6. time? (these are somewhat complicated)
        1. getClockTime, toCalendarTime, formatCalendarTime
      7. system
      8. network
        1. listenOn, accept, connectTo, sClose, sendTo, recvFrom
        2. getHostByName, getHostByAddr,
      9. signals
    3. Some advanced IO stuff (move to later chapter? appendix?)
      1. teaser? light mention?
      2. IORefs? ST?
      3. IO with packed strings?
      4. newUnique?
      5. threads? STM?
      6. FFI?
      7. System.Win32?
      8. Graphics?
  6. "global" variables, the Reader and State monads.
    1. these actions dont run themselves. you have to run them.
      1. describe running later in an example
    2. reader lets you have read-only state that gets passed around implicitely
    3. rule for combining reader actions
      1. just ordering?
    4. return just "wraps" the value, as always.
    5. reader has function "ask"
    6. small functional example
      1. show how to "run" an action.
    7. small IO example
      1. the ReaderT monad. We can combine reader with other action types.
      2. running this one is more complicated.. we need both the reader and the IO to run.
      3. liftIO is needed. what does it do?
    8. we can use all the "M" tricks we learned from IO
      1. what liftM, liftM2, etc.. mean for reader
    9. slightly bigger example
      1. more complex data.
      2. reader also has "asks" that can be used to extract complex state or process it.
    10. if we want to write to the global state, we need the State monad.
    11. state's rules for combining
      1. successive (enclosed) actions run with access to the changes of the previous action. Exactly as we would expect.
    12. new functions "get", "put", "gets", "puts". No "ask" or "asks".
    13. state needs to be run (just like reader did)
    14. we can use all the "M" tricks we learned from IO
    15. a moderate example building on the reader example
      1. use StateT
    16. there's also "Writer". Its like State - Reader.
      1. it has "tell". You figure it out!
  7. Maybe - computation with simple failure. search.
    1. very different meaning than other actions!
    2. rule for combining
      1. next action only runs if current one didnt "fail" (return Nothing)
    3. what "return" does
    4. hey, this "action" isn't inert!
    5. Maybe is used often in the libraries
      1. list lookup
      2. map lookup
    6. some maybe functions
      1. fromJust, isJust, ...
    7. the "M" bunch
      1. liftMs work... what they mean
      2. conditionals and looping?
    8. a new one: mplus
    9. implementing a search algorithm using Maybe
    10. (some example using monad transformers?)
  8. Error - errors with failure values.
  9. List
    1. computation that can return many or no values.
    2. generators
    3. search algorithms again!
    4. rule for combining actions
      1. next actionruns with ALL VALUES from the current action
      2. or doesn't run if the list is empty!
    5. what "return" does
    6. some simple generators
    7. relate generators to list comprehensions
    8. introduce guard and relate that to list comprehensions
    9. what the normal "M" guys mean for lists
    10. List is a superset of Maybe in many ways
    11. how mplus works
    12. our Maybe search code previously works with no code modifications!
      1. instead of finding the FIRST result, it finds ALL results!
    13. as usual we can combine list monads with other monads
      1. how about an search algorithm using StateT?
  10. the ((->) r) monad
    1. actions are functions. These are of course inert.
    2. rule for combining combines functions
    3. we can use "do" notation to combine some functions in complex ways!
    4. we can use the normal "M" tools too!
      1. liftM
      2. mapM
      3. join
  11. What it all means
    1. the common theme here was
      1. some action
      2. actions can be combined. there's a rule for combining
      3. there's a way to make an action that returns a value
      4. the monad laws
    2. thats all a monad is.
    3. do, liftM, etc.. work with any monad.
      1. review the definition? show the definition of some more of them?
    4. do notation is just a convenience
      1. it translates into something very similar to let-binding.
      2. you can rewrite do blocks as nested do blocks where each do block combines only two actions. This is how actions are combined... its called "bind" (we're doing do-binding!)
      3. the "bind" operator is called ">>="
      4. show example of desugaring.
        1. work through the entire example showing how it gets worked out (perhaps Maybe monad would be good here)
      5. you can use bind directly! Sometimes the code is simpler. Sometimes its not. Show some examples.
      6. do has some other "goodies" like pattern matching and "lets" lets desugar to the obvious thing.
    5. what about IO!@? IO can be thought of as a function on the real world! in reality IO enforces ordering, which lets haskell do its lazy evaluation. It doesnt really represent "the real world" internally some how!
    6. you can make your own if you want!
      1. show examples of some of the other implementations
        1. State
        2. Maybe
        3. mplus
      2. when you do, people can use your new monad in do blocks!
      3. all of the "M" tools are yours for free! (thats why we use general abstractions! not to confuse you!)
      4. instance Monad. small example
  12. Where to go from here
    1. good tutorial on monad transformers
    2. the ghc library documentation
    3. write code!