IO and effects
Moggi separates computation from effect. A pure function returns a value; a
function that talks to the world returns IO a, where a is what it produces.
An IO a value is a description of effects — building one does nothing. main
is the description the runtime executes.
main :: IO ()
main = do
putStr "a"
putStrLn "b"
putStrLn (show (1 :: Int))
ab
1
The lines run in the order written, and putStr "a" really does write before
putStrLn "b". There is no deferred evaluation to reorder them: evaluation is
strict, and do sequences actions in bind order.
print x is putStr (show x): it adds no trailing newline. Write
putStrLn (show x) when you want a line.
do notation
do is sugar for >>= and >>, with two extra forms:
import System.Environment (getArgs)
main :: IO ()
main = do
args <- getArgs -- run it and bind the result
let count = length args -- a pure binding, no `in`
putStrLn (show count <> " argument(s)") -- run it, discard the result
pure () -- an action that does nothing
x <- actionrunsactionand binds its result.- A bare
actionruns it and discards the result. let name = expressionbinds a pure value for the rest of the block; there is noin.pure valueis the action with no effects that producesvalue.
The last statement is the block’s result, so a do block of type IO ()
normally ends with pure () or with an action that returns ().
do works for any type with a Monad instance, not only IO
(Classes); for IO the sequencing is the effect order.
main and the entry point
main is the entry point of the module compiled as the program. It must be an
IO action for the program to have an entry:
main :: IO Int
main = pure 42
This compiles and runs; the 42 is discarded. main :: IO a is accepted for any
a, so a function can return a value nobody reads.
A main of a non-IO type is not rejected, but it is not an entry point
either — moggi run reports that there is nothing to run:
error: no entry `main` found to run
If you see that message with a main in the file, its type is the reason.
The purity boundary
IO may appear only as the result of a function that performs effects. It
cannot be stored in a data type, a record field or a tuple:
data X = X (IO ())
Main.mog:1:13: type error: IO values are forbidden outside an IO-returning function
The rule is what keeps “pure” meaningful: a function whose signature has no
IO cannot perform effects, directly or by unpacking one, and there is no IO
value to pattern-match on. The one way across the line is unsafePerformIO,
whose name is the warning.
Running an action from pure code
import System.IO.Unsafe
answer :: Int -> Int
answer n = unsafePerformIO (pure (n + n))
unsafePerformIO :: IO a -> a runs the action and answers its result. The action
runs when the expression is evaluated: inside a function body that is on every
call, and in a top-level binding when the binding is initialised.
Use it only where the effect is invisible to the rest of the program or happens once by construction: a memo table, an identifier supply, a counter that pure code reads. It does not make the effect pure, and the type of a function that uses it no longer describes what that function does. Four consequences to plan for:
- Nothing sequences the action with the rest of the program except the demand for its result: it runs where the value is needed, not where the call is written.
- It can run more than once — once per evaluation — so a call written in a function body is not a once-per-program hook.
- Its exceptions surface where the value is forced, which can be far from the
unsafePerformIOitself. - Code that assumes purity breaks: a function handed to
map,sortor aFoldablemust not change state through it, because how often it is called is the compiler’s business, not the caller’s.
When the effect is local, ST says so in the type and needs no promise; when it
is not local, the code belongs in IO.
In a foreign declaration, IO may appear only outermost in the result
(FFI).
Advanced from here. Local mutation is a separate tool from IO, needed by
some algorithms and avoidable in most programs. Skip to the next page if your
program only reads input, writes output and returns values.
Local mutation with ST
Some algorithms want a mutable cell or array without touching the world. ST is
a thread of local mutation that is run purely: runST turns an ST s a into an
a, and the compiler refuses any thread whose cell could escape.
import Control.Monad.ST
import Data.STRef
answer :: ST s Int
answer = do
ref <- newSTRef 41
modifySTRef ref (+ 1)
readSTRef ref
main :: IO ()
main = putStrLn (show (runST answer))
42
STRef s a is a cell in thread s. The thread variable keeps one run’s cells
apart from another’s, and runST requires that s does not appear in the
result. A cell that would escape is rejected:
Main.mog:6:1: type error: ST values are forbidden outside an ST-returning function
For a loop, pass the cell to a recursive helper. A top-level function keeps the
helper’s signature and guards out of the do block:
import Control.Monad.ST
import Data.STRef
total :: Int -> STRef s Int -> Int -> ST s Int
total n ref i
| i > n = readSTRef ref
| otherwise = do
x <- readSTRef ref
writeSTRef ref (x + i)
total n ref (i + 1)
sumTo :: Int -> Int
sumTo n = runST do
ref <- newSTRef 0
total n ref 1
main :: IO ()
main = putStrLn (show (sumTo 10))
55
stToIO runs a RealWorld thread as an IO action when the mutation has to
meet the outside world:
import Control.Monad.ST
import Data.STRef
main :: IO ()
main = do
x <- stToIO do
ref <- newSTRef 1
modifySTRef ref (+ 1)
readSTRef ref
putStrLn (show x)
2
Mutable arrays use the same split: Data.Array is immutable, Data.Array.ST
and Data.Array.IO are the mutable variants, and Data.Array.MArray is the
class over both. They live in the array package, which is a separate library
root (Standard library).
IO or ST?
| Need | Use |
|---|---|
| Read or write the world: files, arguments, console, clock | IO |
| A mutable cell or array inside one pure function | ST |
Mutation whose result must be visible to IO |
ST with stToIO, or IO directly |
| A value that outlives the computation | neither: a cell cannot escape its run |
Limits
- Concurrency is host threads.
Control.ConcurrentprovidesforkIO,MVar,Chan,QSemandQSemN, and the JVM, .NET and PHP runtimes each back them with a real OS thread.throwToandkillThreadexist but can only target the calling thread: there is no cross-thread asynchronous delivery. Themaskfamily is the identity andgetMaskingStateis alwaysUnmaskedfor the same reason. Descriptor and STM waiting (threadWaitRead,threadWaitWriteand their STM forms) havebase’s signatures but report that the runtime has neither.IORefremains non-atomic; use anMVarwhere two threads share a cell. - No
IOin data, as above. If a computation must be passed around, pass a function returningIO. - No lifting between
STandIOexceptstToIO. AnIOaction cannot be run insideST. -
A multi-line
ifworks as adostatement. The branches may be laid out deeper than the block’s column, whether theifis a function body or a statement followed by more statements:describe :: Int -> IO () describe n = do if n > 0 then putStrLn "pos" else putStrLn "neg" putStrLn "done" - Handles are sequential streams. There is no seeking, no text encoding
selection and no explicit buffering; see the
standard library for what
System.IOprovides. - Exception reports are covered in Diagnostics:
erroraborts,throwIO/catchhandle typed exceptions, and an uncaught exception prints a report naming your code.
Where next
- Exceptions — the report format and per-backend precision.
- Type classes — why
doworks forMonadand what a constraint means. - Standard library —
System.IO,System.Environment,Control.Exception, and the packages that ship with the compiler.