base-3.0.2.0: Basic librariesContentsIndex
GHC.IOBase
Portabilitynon-portable (GHC Extensions)
Stabilityinternal
Maintainercvs-ghc@haskell.org
Description
Definitions for the IO monad and its friends.
Synopsis
newtype IO a = IO (State# RealWorld -> (#State# RealWorld, a#))
unIO :: IO a -> State# RealWorld -> (#State# RealWorld, a#)
failIO :: String -> IO a
liftIO :: IO a -> State# RealWorld -> STret RealWorld a
bindIO :: IO a -> (a -> IO b) -> IO b
thenIO :: IO a -> IO b -> IO b
returnIO :: a -> IO a
unsafePerformIO :: IO a -> a
unsafeInterleaveIO :: IO a -> IO a
unsafeDupablePerformIO :: IO a -> a
unsafeDupableInterleaveIO :: IO a -> IO a
noDuplicate :: IO ()
stToIO :: ST RealWorld a -> IO a
ioToST :: IO a -> ST RealWorld a
unsafeIOToST :: IO a -> ST s a
unsafeSTToIO :: ST s a -> IO a
newtype IORef a = IORef (STRef RealWorld a)
newIORef :: a -> IO (IORef a)
readIORef :: IORef a -> IO a
writeIORef :: IORef a -> a -> IO ()
newtype IOArray i e = IOArray (STArray RealWorld i e)
newIOArray :: Ix i => (i, i) -> e -> IO (IOArray i e)
readIOArray :: Ix i => IOArray i e -> i -> IO e
writeIOArray :: Ix i => IOArray i e -> i -> e -> IO ()
unsafeReadIOArray :: Ix i => IOArray i e -> Int -> IO e
unsafeWriteIOArray :: Ix i => IOArray i e -> Int -> e -> IO ()
data MVar a = MVar (MVar# RealWorld a)
type FilePath = String
data Handle
= FileHandle FilePath !(MVar Handle__)
| DuplexHandle FilePath !(MVar Handle__) !(MVar Handle__)
data Handle__ = Handle__ {
haFD :: !FD
haType :: HandleType
haIsBin :: Bool
haIsStream :: Bool
haBufferMode :: BufferMode
haBuffer :: !(IORef Buffer)
haBuffers :: !(IORef BufferList)
haOtherSide :: Maybe (MVar Handle__)
}
data HandleType
= ClosedHandle
| SemiClosedHandle
| ReadHandle
| WriteHandle
| AppendHandle
| ReadWriteHandle
data IOMode
= ReadMode
| WriteMode
| AppendMode
| ReadWriteMode
type FD = CInt
data Buffer = Buffer {
bufBuf :: RawBuffer
bufRPtr :: !Int
bufWPtr :: !Int
bufSize :: !Int
bufState :: BufferState
}
type RawBuffer = MutableByteArray# RealWorld
data BufferState
= ReadBuffer
| WriteBuffer
data BufferList
= BufferListNil
| BufferListCons RawBuffer BufferList
data BufferMode
= NoBuffering
| LineBuffering
| BlockBuffering (Maybe Int)
bufferIsWritable :: Buffer -> Bool
bufferEmpty :: Buffer -> Bool
bufferFull :: Buffer -> Bool
data Exception
= ArithException ArithException
| ArrayException ArrayException
| AssertionFailed String
| AsyncException AsyncException
| BlockedOnDeadMVar
| BlockedIndefinitely
| NestedAtomically
| Deadlock
| DynException Dynamic
| ErrorCall String
| ExitException ExitCode
| IOException IOException
| NoMethodError String
| NonTermination
| PatternMatchFail String
| RecConError String
| RecSelError String
| RecUpdError String
data ArithException
= Overflow
| Underflow
| LossOfPrecision
| DivideByZero
| Denormal
data AsyncException
= StackOverflow
| HeapOverflow
| ThreadKilled
data ArrayException
= IndexOutOfBounds String
| UndefinedElement String
heapOverflow :: Exception
throw :: Exception -> a
throwIO :: Exception -> IO a
ioException :: IOException -> IO a
type IOError = IOException
data IOException = IOError {
ioe_handle :: Maybe Handle
ioe_type :: IOErrorType
ioe_location :: String
ioe_description :: String
ioe_filename :: Maybe FilePath
}
data IOErrorType
= AlreadyExists
| NoSuchThing
| ResourceBusy
| ResourceExhausted
| EOF
| IllegalOperation
| PermissionDenied
| UserError
| UnsatisfiedConstraints
| SystemError
| ProtocolError
| OtherError
| InvalidArgument
| InappropriateType
| HardwareFault
| UnsupportedOperation
| TimeExpired
| ResourceVanished
| Interrupted
| DynIOError Dynamic
ioError :: IOError -> IO a
userError :: String -> IOError
data ExitCode
= ExitSuccess
| ExitFailure Int
Documentation
newtype IO a

A value of type IO a is a computation which, when performed, does some I/O before returning a value of type a.

There is really only one way to "perform" an I/O action: bind it to Main.main in your program. When your program is run, the I/O will be performed. It isn't possible to perform I/O from an arbitrary function, unless that function is itself in the IO monad and called at some point, directly or indirectly, from Main.main.

IO is a monad, so IO actions can be combined using either the do-notation or the >> and >>= operations from the Monad class.

Constructors
IO (State# RealWorld -> (#State# RealWorld, a#))
show/hide Instances
unIO :: IO a -> State# RealWorld -> (#State# RealWorld, a#)
failIO :: String -> IO a
liftIO :: IO a -> State# RealWorld -> STret RealWorld a
bindIO :: IO a -> (a -> IO b) -> IO b
thenIO :: IO a -> IO b -> IO b
returnIO :: a -> IO a
unsafePerformIO :: IO a -> a

This is the "back door" into the IO monad, allowing IO computation to be performed at any time. For this to be safe, the IO computation should be free of side effects and independent of its environment.

If the I/O computation wrapped in unsafePerformIO performs side effects, then the relative order in which those side effects take place (relative to the main I/O trunk, or other calls to unsafePerformIO) is indeterminate. You have to be careful when writing and compiling modules that use unsafePerformIO:

  • Use {-# NOINLINE foo #-} as a pragma on any function foo that calls unsafePerformIO. If the call is inlined, the I/O may be performed more than once.
  • Use the compiler flag -fno-cse to prevent common sub-expression elimination being performed on the module, which might combine two side effects that were meant to be separate. A good example is using multiple global variables (like test in the example below).
  • Make sure that the either you switch off let-floating, or that the call to unsafePerformIO cannot float outside a lambda. For example, if you say: f x = unsafePerformIO (newIORef []) you may get only one reference cell shared between all calls to f. Better would be f x = unsafePerformIO (newIORef [x]) because now it can't float outside the lambda.

It is less well known that unsafePerformIO is not type safe. For example:

     test :: IORef [a]
     test = unsafePerformIO $ newIORef []
     
     main = do
     	      writeIORef test [42]
     	      bang <- readIORef test
     	      print (bang :: [Char])

This program will core dump. This problem with polymorphic references is well known in the ML community, and does not arise with normal monadic use of references. There is no easy way to make it impossible once you use unsafePerformIO. Indeed, it is possible to write coerce :: a -> b with the help of unsafePerformIO. So be careful!

unsafeInterleaveIO :: IO a -> IO a
unsafeDupablePerformIO :: IO a -> a
unsafeDupableInterleaveIO :: IO a -> IO a
noDuplicate :: IO ()

Ensures that the suspensions under evaluation by the current thread are unique; that is, the current thread is not evaluating anything that is also under evaluation by another thread that has also executed noDuplicate.

This operation is used in the definition of unsafePerformIO to prevent the IO action from being executed multiple times, which is usually undesirable.

stToIO :: ST RealWorld a -> IO a
A monad transformer embedding strict state transformers in the IO monad. The RealWorld parameter indicates that the internal state used by the ST computation is a special one supplied by the IO monad, and thus distinct from those used by invocations of runST.
ioToST :: IO a -> ST RealWorld a
unsafeIOToST :: IO a -> ST s a
unsafeSTToIO :: ST s a -> IO a
newtype IORef a
A mutable variable in the IO monad
Constructors
IORef (STRef RealWorld a)
show/hide Instances
newIORef :: a -> IO (IORef a)
Build a new IORef
readIORef :: IORef a -> IO a
Read the value of an IORef
writeIORef :: IORef a -> a -> IO ()
Write a new value into an IORef
newtype IOArray i e

An IOArray is a mutable, boxed, non-strict array in the IO monad. The type arguments are as follows:

  • i: the index type of the array (should be an instance of Ix)
  • e: the element type of the array.
Constructors
IOArray (STArray RealWorld i e)
show/hide Instances
Eq (IOArray i e)
newIOArray :: Ix i => (i, i) -> e -> IO (IOArray i e)
Build a new IOArray
readIOArray :: Ix i => IOArray i e -> i -> IO e
Read a value from an IOArray
writeIOArray :: Ix i => IOArray i e -> i -> e -> IO ()
Write a new value into an IOArray
unsafeReadIOArray :: Ix i => IOArray i e -> Int -> IO e
Read a value from an IOArray
unsafeWriteIOArray :: Ix i => IOArray i e -> Int -> e -> IO ()
Write a new value into an IOArray
data MVar a
An MVar (pronounced "em-var") is a synchronising variable, used for communication between concurrent threads. It can be thought of as a a box, which may be empty or full.
Constructors
MVar (MVar# RealWorld a)
show/hide Instances
type FilePath = String
File and directory names are values of type String, whose precise meaning is operating system dependent. Files can be opened, yielding a handle which can then be used to operate on the contents of that file.
data Handle

Haskell defines operations to read and write characters from and to files, represented by values of type Handle. Each value of this type is a handle: a record used by the Haskell run-time system to manage I/O with file system objects. A handle has at least the following properties:

  • whether it manages input or output or both;
  • whether it is open, closed or semi-closed;
  • whether the object is seekable;
  • whether buffering is disabled, or enabled on a line or block basis;
  • a buffer (whose length may be zero).

Most handles will also have a current I/O position indicating where the next input or output operation will occur. A handle is readable if it manages only input or both input and output; likewise, it is writable if it manages only output or both input and output. A handle is open when first allocated. Once it is closed it can no longer be used for either input or output, though an implementation cannot re-use its storage while references remain to it. Handles are in the Show and Eq classes. The string produced by showing a handle is system dependent; it should include enough information to identify the handle for debugging. A handle is equal according to == only to itself; no attempt is made to compare the internal state of different handles for equality.

GHC note: a Handle will be automatically closed when the garbage collector detects that it has become unreferenced by the program. However, relying on this behaviour is not generally recommended: the garbage collector is unpredictable. If possible, use explicit an explicit hClose to close Handles when they are no longer required. GHC does not currently attempt to free up file descriptors when they have run out, it is your responsibility to ensure that this doesn't happen.

Constructors
FileHandle FilePath !(MVar Handle__)
DuplexHandle FilePath !(MVar Handle__) !(MVar Handle__)
show/hide Instances
data Handle__
Constructors
Handle__
haFD :: !FD
haType :: HandleType
haIsBin :: Bool
haIsStream :: Bool
haBufferMode :: BufferMode
haBuffer :: !(IORef Buffer)
haBuffers :: !(IORef BufferList)
haOtherSide :: Maybe (MVar Handle__)
data HandleType
Constructors
ClosedHandle
SemiClosedHandle
ReadHandle
WriteHandle
AppendHandle
ReadWriteHandle
show/hide Instances
data IOMode
Constructors
ReadMode
WriteMode
AppendMode
ReadWriteMode
show/hide Instances
type FD = CInt
data Buffer
Constructors
Buffer
bufBuf :: RawBuffer
bufRPtr :: !Int
bufWPtr :: !Int
bufSize :: !Int
bufState :: BufferState
type RawBuffer = MutableByteArray# RealWorld
data BufferState
Constructors
ReadBuffer
WriteBuffer
show/hide Instances
data BufferList
Constructors
BufferListNil
BufferListCons RawBuffer BufferList
data BufferMode

Three kinds of buffering are supported: line-buffering, block-buffering or no-buffering. These modes have the following effects. For output, items are written out, or flushed, from the internal buffer according to the buffer mode:

  • line-buffering: the entire output buffer is flushed whenever a newline is output, the buffer overflows, a System.IO.hFlush is issued, or the handle is closed.
  • block-buffering: the entire buffer is written out whenever it overflows, a System.IO.hFlush is issued, or the handle is closed.
  • no-buffering: output is written immediately, and never stored in the buffer.

An implementation is free to flush the buffer more frequently, but not less frequently, than specified above. The output buffer is emptied as soon as it has been written out.

Similarly, input occurs according to the buffer mode for the handle:

  • line-buffering: when the buffer for the handle is not empty, the next item is obtained from the buffer; otherwise, when the buffer is empty, characters up to and including the next newline character are read into the buffer. No characters are available until the newline character is available or the buffer is full.
  • block-buffering: when the buffer for the handle becomes empty, the next block of data is read into the buffer.
  • no-buffering: the next input item is read and returned. The System.IO.hLookAhead operation implies that even a no-buffered handle may require a one-character buffer.

The default buffering mode when a handle is opened is implementation-dependent and may depend on the file system object which is attached to that handle. For most implementations, physical files will normally be block-buffered and terminals will normally be line-buffered.

Constructors
NoBufferingbuffering is disabled if possible.
LineBufferingline-buffering should be enabled if possible.
BlockBuffering (Maybe Int)block-buffering should be enabled if possible. The size of the buffer is n items if the argument is Just n and is otherwise implementation-dependent.
show/hide Instances
bufferIsWritable :: Buffer -> Bool
bufferEmpty :: Buffer -> Bool
bufferFull :: Buffer -> Bool
data Exception
The type of exceptions. Every kind of system-generated exception has a constructor in the Exception type, and values of other types may be injected into Exception by coercing them to Dynamic (see the section on Dynamic Exceptions: Control.Exception#DynamicExceptions).
Constructors
ArithException ArithExceptionExceptions raised by arithmetic operations. (NOTE: GHC currently does not throw ArithExceptions except for DivideByZero).
ArrayException ArrayExceptionExceptions raised by array-related operations. (NOTE: GHC currently does not throw ArrayExceptions).
AssertionFailed StringThis exception is thrown by the assert operation when the condition fails. The String argument contains the location of the assertion in the source program.
AsyncException AsyncExceptionAsynchronous exceptions (see section on Asynchronous Exceptions: Control.Exception#AsynchronousExceptions).
BlockedOnDeadMVarThe current thread was executing a call to Control.Concurrent.MVar.takeMVar that could never return, because there are no other references to this MVar.
BlockedIndefinitelyThe current thread was waiting to retry an atomic memory transaction that could never become possible to complete because there are no other threads referring to any of the TVars involved.
NestedAtomicallyThe runtime detected an attempt to nest one STM transaction inside another one, presumably due to the use of unsafePeformIO with atomically.
DeadlockThere are no runnable threads, so the program is deadlocked. The Deadlock exception is raised in the main thread only (see also: Control.Concurrent).
DynException DynamicDynamically typed exceptions (see section on Dynamic Exceptions: Control.Exception#DynamicExceptions).
ErrorCall StringThe ErrorCall exception is thrown by error. The String argument of ErrorCall is the string passed to error when it was called.
ExitException ExitCodeThe ExitException exception is thrown by System.Exit.exitWith (and System.Exit.exitFailure). The ExitCode argument is the value passed to System.Exit.exitWith. An unhandled ExitException exception in the main thread will cause the program to be terminated with the given exit code.
IOException IOExceptionThese are the standard IO exceptions generated by Haskell's IO operations. See also System.IO.Error.
NoMethodError StringAn attempt was made to invoke a class method which has no definition in this instance, and there was no default definition given in the class declaration. GHC issues a warning when you compile an instance which has missing methods.
NonTerminationThe current thread is stuck in an infinite loop. This exception may or may not be thrown when the program is non-terminating.
PatternMatchFail StringA pattern matching failure. The String argument should contain a descriptive message including the function name, source file and line number.
RecConError StringAn attempt was made to evaluate a field of a record for which no value was given at construction time. The String argument gives the location of the record construction in the source program.
RecSelError StringA field selection was attempted on a constructor that doesn't have the requested field. This can happen with multi-constructor records when one or more fields are missing from some of the constructors. The String argument gives the location of the record selection in the source program.
RecUpdError StringAn attempt was made to update a field in a record, where the record doesn't have the requested field. This can only occur with multi-constructor records, when one or more fields are missing from some of the constructors. The String argument gives the location of the record update in the source program.
show/hide Instances
data ArithException
The type of arithmetic exceptions
Constructors
Overflow
Underflow
LossOfPrecision
DivideByZero
Denormal
show/hide Instances
data AsyncException
Asynchronous exceptions
Constructors
StackOverflowThe current thread's stack exceeded its limit. Since an exception has been raised, the thread's stack will certainly be below its limit again, but the programmer should take remedial action immediately.
HeapOverflow

The program's heap is reaching its limit, and the program should take action to reduce the amount of live data it has. Notes:

  • It is undefined which thread receives this exception.
  • GHC currently does not throw HeapOverflow exceptions.
ThreadKilledThis exception is raised by another thread calling Control.Concurrent.killThread, or by the system if it needs to terminate the thread for some reason.
show/hide Instances
data ArrayException
Exceptions generated by array operations
Constructors
IndexOutOfBounds StringAn attempt was made to index an array outside its declared bounds.
UndefinedElement StringAn attempt was made to evaluate an element of an array that had not been initialized.
show/hide Instances
heapOverflow :: Exception
throw :: Exception -> a
Throw an exception. Exceptions may be thrown from purely functional code, but may only be caught within the IO monad.
throwIO :: Exception -> IO a

A variant of throw that can be used within the IO monad.

Although throwIO has a type that is an instance of the type of throw, the two functions are subtly different:

 throw e   `seq` x  ===> throw e
 throwIO e `seq` x  ===> x

The first example will cause the exception e to be raised, whereas the second one won't. In fact, throwIO will only cause an exception to be raised when it is used within the IO monad. The throwIO variant should be used in preference to throw to raise an exception within the IO monad because it guarantees ordering with respect to other IO operations, whereas throw does not.

ioException :: IOException -> IO a
type IOError = IOException

The Haskell 98 type for exceptions in the IO monad. Any I/O operation may raise an IOError instead of returning a result. For a more general type of exception, including also those that arise in pure code, see Control.Exception.Exception.

In Haskell 98, this is an opaque type.

data IOException
Exceptions that occur in the IO monad. An IOException records a more specific error type, a descriptive string and maybe the handle that was used when the error was flagged.
Constructors
IOError
ioe_handle :: Maybe Handle
ioe_type :: IOErrorType
ioe_location :: String
ioe_description :: String
ioe_filename :: Maybe FilePath
show/hide Instances
data IOErrorType
An abstract type that contains a value for each variant of IOError.
Constructors
AlreadyExists
NoSuchThing
ResourceBusy
ResourceExhausted
EOF
IllegalOperation
PermissionDenied
UserError
UnsatisfiedConstraints
SystemError
ProtocolError
OtherError
InvalidArgument
InappropriateType
HardwareFault
UnsupportedOperation
TimeExpired
ResourceVanished
Interrupted
DynIOError Dynamic
show/hide Instances
ioError :: IOError -> IO a
Raise an IOError in the IO monad.
userError :: String -> IOError

Construct an IOError value with a string describing the error. The fail method of the IO instance of the Monad class raises a userError, thus:

 instance Monad IO where 
   ...
   fail s = ioError (userError s)
data ExitCode
Constructors
ExitSuccessindicates successful termination;
ExitFailure Intindicates program failure with an exit code. The exact interpretation of the code is operating-system dependent. In particular, some values may be prohibited (e.g. 0 on a POSIX-compliant system).
show/hide Instances
Produced by Haddock version 2.2.2