Stability | unstable |
---|---|
Portability | portable |
Safe Haskell | Safe-Inferred |
Language | Haskell2010 |
Internal modules are always subject to change from version to version.
Synopsis
- module Prelude
- second :: Arrow a => a b c -> a (d, b) (d, c)
- forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId
- killThread :: ThreadId -> IO ()
- forkIO :: IO () -> IO ThreadId
- takeMVar :: MVar a -> IO a
- readMVar :: MVar a -> IO a
- putMVar :: MVar a -> a -> IO ()
- newEmptyMVar :: IO (MVar a)
- try :: Exception e => IO a -> IO (Either e a)
- onException :: IO a -> IO b -> IO a
- finally :: IO a -> IO b -> IO a
- bracket_ :: IO a -> IO b -> IO c -> IO c
- bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
- throwIO :: Exception e => e -> IO a
- mask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
- catch :: Exception e => IO a -> (e -> IO a) -> IO a
- data SomeException
- unless :: Applicative f => Bool -> f () -> f ()
- replicateM_ :: Applicative m => Int -> m a -> m ()
- replicateM :: Applicative m => Int -> m a -> m [a]
- (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
- (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
- when :: Applicative f => Bool -> f () -> f ()
- complement :: Bits a => a -> a
- (.&.) :: Bits a => a -> a -> a
- (.|.) :: Bits a => a -> a -> a
- toUpper :: Char -> Char
- toLower :: Char -> Char
- isAscii :: Char -> Bool
- isAlpha :: Char -> Bool
- traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()
- for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f ()
- on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
- maybeToList :: Maybe a -> [a]
- fromMaybe :: a -> Maybe a -> a
- catMaybes :: [Maybe a] -> [a]
- (<>) :: Semigroup a => a -> a -> a
- mempty :: Monoid a => a
- mconcat :: Monoid a => [a] -> a
- data IORef a
- writeIORef :: IORef a -> a -> IO ()
- readIORef :: IORef a -> IO a
- newIORef :: a -> IO (IORef a)
- for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b)
- data Ptr a
- withArray :: Storable a => [a] -> (Ptr a -> IO b) -> IO b
- allocaArray :: Storable a => Int -> (Ptr a -> IO b) -> IO b
- with :: Storable a => a -> (Ptr a -> IO b) -> IO b
- maybeWith :: (a -> (Ptr b -> IO c) -> IO c) -> Maybe a -> (Ptr b -> IO c) -> IO c
- allocaBytesAligned :: Int -> Int -> (Ptr a -> IO b) -> IO b
- allocaBytes :: Int -> (Ptr a -> IO b) -> IO b
- alloca :: Storable a => (Ptr a -> IO b) -> IO b
- class Storable a where
- plusPtr :: Ptr a -> Int -> Ptr b
- nullPtr :: Ptr a
- throwErrnoPathIfMinus1_ :: (Eq a, Num a) => String -> FilePath -> IO a -> IO ()
- throwErrnoIfNull :: String -> IO (Ptr a) -> IO (Ptr a)
- throwErrnoIfMinus1_ :: (Eq a, Num a) => String -> IO a -> IO ()
- throwErrnoIfMinus1Retry_ :: (Eq a, Num a) => String -> IO a -> IO ()
- type CWString = Ptr CWchar
- type CString = Ptr CChar
- withCWString :: String -> (CWString -> IO a) -> IO a
- withCString :: String -> (CString -> IO a) -> IO a
- peekCWStringLen :: CWStringLen -> IO String
- peekCString :: CString -> IO String
- newtype CWchar = CWchar Int32
- newtype CUShort = CUShort Word16
- newtype CULong = CULong Word64
- newtype CUChar = CUChar Word8
- newtype CTime = CTime Int64
- newtype CLong = CLong Int64
- newtype CInt = CInt Int32
- getFileSystemEncoding :: IO TextEncoding
- data IOErrorType
- lookupEnv :: String -> IO (Maybe String)
- getEnv :: String -> IO String
- getArgs :: IO [String]
- exitFailure :: IO a
- openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle)
- hClose :: Handle -> IO ()
- withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
- stderr :: Handle
- hPutStrLn :: Handle -> String -> IO ()
- hPutStr :: Handle -> String -> IO ()
- hPutBuf :: Handle -> Ptr a -> Int -> IO ()
- hGetBuf :: Handle -> Ptr a -> Int -> IO Int
- hFlush :: Handle -> IO ()
- stdout :: Handle
- data Handle
- data IOMode
- tryIOError :: IO a -> IO (Either IOError a)
- permissionErrorType :: IOErrorType
- modifyIOError :: (IOError -> IOError) -> IO a -> IO a
- mkIOError :: IOErrorType -> String -> Maybe Handle -> Maybe FilePath -> IOError
- isPermissionError :: IOError -> Bool
- isIllegalOperation :: IOError -> Bool
- isDoesNotExistError :: IOError -> Bool
- isAlreadyExistsError :: IOError -> Bool
- ioeSetLocation :: IOError -> String -> IOError
- ioeSetFileName :: IOError -> FilePath -> IOError
- ioeSetErrorString :: IOError -> String -> IOError
- ioeGetLocation :: IOError -> String
- ioeGetErrorType :: IOError -> IOErrorType
- ioeGetErrorString :: IOError -> String
- illegalOperationErrorType :: IOErrorType
- catchIOError :: IO a -> (IOError -> IO a) -> IO a
- type IOError = IOException
- userError :: String -> IOError
- withFilePath :: FilePath -> (CString -> IO a) -> IO a
- type EpochTime = CTime
- timeout :: Int -> IO a -> IO (Maybe a)
- data Void
Documentation
module Prelude
second :: Arrow a => a b c -> a (d, b) (d, c) Source #
A mirror image of first
.
The default definition may be overridden with a more efficient version if desired.
forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId Source #
Fork a thread and call the supplied function when the thread is about to terminate, with an exception or a returned value. The function is called with asynchronous exceptions masked.
forkFinally action and_then = mask $ \restore -> forkIO $ try (restore action) >>= and_then
This function is useful for informing the parent when a child terminates, for example.
Since: base-4.6.0.0
killThread :: ThreadId -> IO () Source #
killThread
raises the ThreadKilled
exception in the given
thread (GHC only).
killThread tid = throwTo tid ThreadKilled
forkIO :: IO () -> IO ThreadId Source #
Creates a new thread to run the IO
computation passed as the
first argument, and returns the ThreadId
of the newly created
thread.
The new thread will be a lightweight, unbound thread. Foreign calls
made by this thread are not guaranteed to be made by any particular OS
thread; if you need foreign calls to be made by a particular OS
thread, then use forkOS
instead.
The new thread inherits the masked state of the parent (see
mask
).
The newly created thread has an exception handler that discards the
exceptions BlockedIndefinitelyOnMVar
, BlockedIndefinitelyOnSTM
, and
ThreadKilled
, and passes all other exceptions to the uncaught
exception handler.
takeMVar :: MVar a -> IO a Source #
Return the contents of the MVar
. If the MVar
is currently
empty, takeMVar
will wait until it is full. After a takeMVar
,
the MVar
is left empty.
There are two further important properties of takeMVar
:
takeMVar
is single-wakeup. That is, if there are multiple threads blocked intakeMVar
, and theMVar
becomes full, only one thread will be woken up. The runtime guarantees that the woken thread completes itstakeMVar
operation.- When multiple threads are blocked on an
MVar
, they are woken up in FIFO order. This is useful for providing fairness properties of abstractions built usingMVar
s.
readMVar :: MVar a -> IO a Source #
Atomically read the contents of an MVar
. If the MVar
is
currently empty, readMVar
will wait until it is full.
readMVar
is guaranteed to receive the next putMVar
.
readMVar
is multiple-wakeup, so when multiple readers are
blocked on an MVar
, all of them are woken up at the same time.
Compatibility note: Prior to base 4.7, readMVar
was a combination
of takeMVar
and putMVar
. This mean that in the presence of
other threads attempting to putMVar
, readMVar
could block.
Furthermore, readMVar
would not receive the next putMVar
if there
was already a pending thread blocked on takeMVar
. The old behavior
can be recovered by implementing 'readMVar as follows:
readMVar :: MVar a -> IO a readMVar m = mask_ $ do a <- takeMVar m putMVar m a return a
putMVar :: MVar a -> a -> IO () Source #
Put a value into an MVar
. If the MVar
is currently full,
putMVar
will wait until it becomes empty.
There are two further important properties of putMVar
:
putMVar
is single-wakeup. That is, if there are multiple threads blocked inputMVar
, and theMVar
becomes empty, only one thread will be woken up. The runtime guarantees that the woken thread completes itsputMVar
operation.- When multiple threads are blocked on an
MVar
, they are woken up in FIFO order. This is useful for providing fairness properties of abstractions built usingMVar
s.
try :: Exception e => IO a -> IO (Either e a) Source #
Similar to catch
, but returns an Either
result which is
(
if no exception of type Right
a)e
was raised, or (
if an exception of type Left
ex)e
was raised and its value is ex
.
If any other type of exception is raised then it will be propagated
up to the next enclosing exception handler.
try a = catch (Right `liftM` a) (return . Left)
onException :: IO a -> IO b -> IO a Source #
Like finally
, but only performs the final action if there was an
exception raised by the computation.
:: IO a | computation to run first |
-> IO b | computation to run afterward (even if an exception was raised) |
-> IO a |
A specialised variant of bracket
with just a computation to run
afterward.
bracket_ :: IO a -> IO b -> IO c -> IO c Source #
A variant of bracket
where the return value from the first computation
is not required.
:: IO a | computation to run first ("acquire resource") |
-> (a -> IO b) | computation to run last ("release resource") |
-> (a -> IO c) | computation to run in-between |
-> IO c |
When you want to acquire a resource, do some work with it, and
then release the resource, it is a good idea to use bracket
,
because bracket
will install the necessary exception handler to
release the resource in the event that an exception is raised
during the computation. If an exception is raised, then bracket
will
re-raise the exception (after performing the release).
A common example is opening a file:
bracket (openFile "filename" ReadMode) (hClose) (\fileHandle -> do { ... })
The arguments to bracket
are in this order so that we can partially apply
it, e.g.:
withFile name mode = bracket (openFile name mode) hClose
Bracket wraps the release action with mask
, which is sufficient to ensure
that the release action executes to completion when it does not invoke any
interruptible actions, even in the presence of asynchronous exceptions. For
example, hClose
is uninterruptible when it is not racing other uses of the
handle. Similarly, closing a socket (from "network" package) is also
uninterruptible under similar conditions. An example of an interruptible
action is killThread
. Completion of interruptible release actions can be
ensured by wrapping them in in uninterruptibleMask_
, but this risks making
the program non-responsive to Control-C
, or timeouts. Another option is to
run the release action asynchronously in its own thread:
void $ uninterruptibleMask_ $ forkIO $ do { ... }
The resource will be released as soon as possible, but the thread that invoked bracket will not block in an uninterruptible state.
throwIO :: Exception e => e -> IO a Source #
A variant of throw
that can only 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.
mask :: ((forall a. IO a -> IO a) -> IO b) -> IO b Source #
Executes an IO computation with asynchronous
exceptions masked. That is, any thread which attempts to raise
an exception in the current thread with throwTo
will be blocked until asynchronous exceptions are unmasked again.
The argument passed to mask
is a function that takes as its
argument another function, which can be used to restore the
prevailing masking state within the context of the masked
computation. For example, a common way to use mask
is to protect
the acquisition of a resource:
mask $ \restore -> do x <- acquire restore (do_something_with x) `onException` release release
This code guarantees that acquire
is paired with release
, by masking
asynchronous exceptions for the critical parts. (Rather than write
this code yourself, it would be better to use
bracket
which abstracts the general pattern).
Note that the restore
action passed to the argument to mask
does not necessarily unmask asynchronous exceptions, it just
restores the masking state to that of the enclosing context. Thus
if asynchronous exceptions are already masked, mask
cannot be used
to unmask exceptions again. This is so that if you call a library function
with exceptions masked, you can be sure that the library call will not be
able to unmask exceptions again. If you are writing library code and need
to use asynchronous exceptions, the only way is to create a new thread;
see forkIOWithUnmask
.
Asynchronous exceptions may still be received while in the masked state if the masked thread blocks in certain ways; see Control.Exception.
Threads created by forkIO
inherit the
MaskingState
from the parent; that is, to start a thread in the
MaskedInterruptible
state,
use mask_ $ forkIO ...
. This is particularly useful if you need
to establish an exception handler in the forked thread before any
asynchronous exceptions are received. To create a new thread in
an unmasked state use forkIOWithUnmask
.
:: Exception e | |
=> IO a | The computation to run |
-> (e -> IO a) | Handler to invoke if an exception is raised |
-> IO a |
This is the simplest of the exception-catching functions. It takes a single argument, runs it, and if an exception is raised the "handler" is executed, with the value of the exception passed as an argument. Otherwise, the result is returned as normal. For example:
catch (readFile f) (\e -> do let err = show (e :: IOException) hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err) return "")
Note that we have to give a type signature to e
, or the program
will not typecheck as the type is ambiguous. While it is possible
to catch exceptions of any type, see the section "Catching all
exceptions" (in Control.Exception) for an explanation of the problems with doing so.
For catching exceptions in pure (non-IO
) expressions, see the
function evaluate
.
Note that due to Haskell's unspecified evaluation order, an
expression may throw one of several possible exceptions: consider
the expression (error "urk") + (1 `div` 0)
. Does
the expression throw
ErrorCall "urk"
, or DivideByZero
?
The answer is "it might throw either"; the choice is
non-deterministic. If you are catching any type of exception then you
might catch either. If you are calling catch
with type
IO Int -> (ArithException -> IO Int) -> IO Int
then the handler may
get run with DivideByZero
as an argument, or an ErrorCall "urk"
exception may be propagated further up. If you call it again, you
might get the opposite behaviour. This is ok, because catch
is an
IO
computation.
data SomeException Source #
The SomeException
type is the root of the exception type hierarchy.
When an exception of type e
is thrown, behind the scenes it is
encapsulated in a SomeException
.
Instances
Exception SomeException | Since: base-3.0 |
Defined in GHC.Exception.Type | |
Show SomeException | Since: base-3.0 |
Defined in GHC.Exception.Type |
replicateM_ :: Applicative m => Int -> m a -> m () Source #
replicateM :: Applicative m => Int -> m a -> m [a] Source #
performs the action replicateM
n actact
n
times,
and then returns the list of results:
Examples
>>>
import Control.Monad.State
>>>
runState (replicateM 3 $ state $ \s -> (s, s + 1)) 1
([1,2,3],4)
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 Source #
Left-to-right composition of Kleisli arrows.
'(bs
' can be understood as the >=>
cs) ado
expression
do b <- bs a cs b
when :: Applicative f => Bool -> f () -> f () Source #
Conditional execution of Applicative
expressions. For example,
when debug (putStrLn "Debugging")
will output the string Debugging
if the Boolean value debug
is True
, and otherwise do nothing.
complement :: Bits a => a -> a Source #
Reverse all the bits in the argument
toUpper :: Char -> Char Source #
Convert a letter to the corresponding upper-case letter, if any. Any other character is returned unchanged.
toLower :: Char -> Char Source #
Convert a letter to the corresponding lower-case letter, if any. Any other character is returned unchanged.
isAscii :: Char -> Bool Source #
Selects the first 128 characters of the Unicode character set, corresponding to the ASCII character set.
isAlpha :: Char -> Bool Source #
Selects alphabetic Unicode characters (lower-case, upper-case and
title-case letters, plus letters of caseless scripts and modifiers letters).
This function is equivalent to isLetter
.
traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f () Source #
Map each element of a structure to an Applicative
action, evaluate these
actions from left to right, and ignore the results. For a version that
doesn't ignore the results see traverse
.
traverse_
is just like mapM_
, but generalised to Applicative
actions.
Examples
Basic usage:
>>>
traverse_ print ["Hello", "world", "!"]
"Hello" "world" "!"
for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f () Source #
for_
is traverse_
with its arguments flipped. For a version
that doesn't ignore the results see for
. This
is forM_
generalised to Applicative
actions.
for_
is just like forM_
, but generalised to Applicative
actions.
Examples
Basic usage:
>>>
for_ [1..4] print
1 2 3 4
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c infixl 0 Source #
maybeToList :: Maybe a -> [a] Source #
The maybeToList
function returns an empty list when given
Nothing
or a singleton list when given Just
.
Examples
Basic usage:
>>>
maybeToList (Just 7)
[7]
>>>
maybeToList Nothing
[]
One can use maybeToList
to avoid pattern matching when combined
with a function that (safely) works on lists:
>>>
import Text.Read ( readMaybe )
>>>
sum $ maybeToList (readMaybe "3")
3>>>
sum $ maybeToList (readMaybe "")
0
fromMaybe :: a -> Maybe a -> a Source #
The fromMaybe
function takes a default value and a Maybe
value. If the Maybe
is Nothing
, it returns the default value;
otherwise, it returns the value contained in the Maybe
.
Examples
Basic usage:
>>>
fromMaybe "" (Just "Hello, World!")
"Hello, World!"
>>>
fromMaybe "" Nothing
""
Read an integer from a string using readMaybe
. If we fail to
parse an integer, we want to return 0
by default:
>>>
import Text.Read ( readMaybe )
>>>
fromMaybe 0 (readMaybe "5")
5>>>
fromMaybe 0 (readMaybe "")
0
catMaybes :: [Maybe a] -> [a] Source #
The catMaybes
function takes a list of Maybe
s and returns
a list of all the Just
values.
Examples
Basic usage:
>>>
catMaybes [Just 1, Nothing, Just 3]
[1,3]
When constructing a list of Maybe
values, catMaybes
can be used
to return all of the "success" results (if the list is the result
of a map
, then mapMaybe
would be more appropriate):
>>>
import Text.Read ( readMaybe )
>>>
[readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
[Just 1,Nothing,Just 3]>>>
catMaybes $ [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
[1,3]
(<>) :: Semigroup a => a -> a -> a infixr 6 Source #
An associative operation.
>>>
[1,2,3] <> [4,5,6]
[1,2,3,4,5,6]
mconcat :: Monoid a => [a] -> a Source #
Fold a list using the monoid.
For most types, the default definition for mconcat
will be
used, but the function is included in the class definition so
that an optimized version can be provided for specific types.
>>>
mconcat ["Hello", " ", "Haskell", "!"]
"Hello Haskell!"
A mutable variable in the IO
monad
for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b) Source #
A value of type
represents a pointer to an object, or an
array of objects, which may be marshalled to or from Haskell values
of type Ptr
aa
.
The type a
will often be an instance of class
Storable
which provides the marshalling operations.
However this is not essential, and you can provide your own operations
to access the pointer. For example you might write small foreign
functions to get or set the fields of a C struct
.
Instances
Foldable (UAddr :: TYPE LiftedRep -> Type) | Since: base-4.9.0.0 |
Defined in Data.Foldable fold :: Monoid m => UAddr m -> m Source # foldMap :: Monoid m => (a -> m) -> UAddr a -> m Source # foldMap' :: Monoid m => (a -> m) -> UAddr a -> m Source # foldr :: (a -> b -> b) -> b -> UAddr a -> b Source # foldr' :: (a -> b -> b) -> b -> UAddr a -> b Source # foldl :: (b -> a -> b) -> b -> UAddr a -> b Source # foldl' :: (b -> a -> b) -> b -> UAddr a -> b Source # foldr1 :: (a -> a -> a) -> UAddr a -> a Source # foldl1 :: (a -> a -> a) -> UAddr a -> a Source # toList :: UAddr a -> [a] Source # null :: UAddr a -> Bool Source # length :: UAddr a -> Int Source # elem :: Eq a => a -> UAddr a -> Bool Source # maximum :: Ord a => UAddr a -> a Source # minimum :: Ord a => UAddr a -> a Source # | |
Traversable (UAddr :: Type -> Type) | Since: base-4.9.0.0 |
Storable (Ptr a) | Since: base-2.1 |
Defined in Foreign.Storable sizeOf :: Ptr a -> Int Source # alignment :: Ptr a -> Int Source # peekElemOff :: Ptr (Ptr a) -> Int -> IO (Ptr a) Source # pokeElemOff :: Ptr (Ptr a) -> Int -> Ptr a -> IO () Source # peekByteOff :: Ptr b -> Int -> IO (Ptr a) Source # pokeByteOff :: Ptr b -> Int -> Ptr a -> IO () Source # | |
Show (Ptr a) | Since: base-2.1 |
Eq (Ptr a) | Since: base-2.1 |
Ord (Ptr a) | Since: base-2.1 |
withArray :: Storable a => [a] -> (Ptr a -> IO b) -> IO b Source #
Temporarily store a list of storable values in memory
(like with
, but for multiple elements).
allocaArray :: Storable a => Int -> (Ptr a -> IO b) -> IO b Source #
Temporarily allocate space for the given number of elements
(like alloca
, but for multiple elements).
with :: Storable a => a -> (Ptr a -> IO b) -> IO b Source #
executes the computation with
val ff
, passing as argument
a pointer to a temporarily allocated block of memory into which
val
has been marshalled (the combination of alloca
and poke
).
The memory is freed when f
terminates (either normally or via an
exception), so the pointer passed to f
must not be used after this.
allocaBytesAligned :: Int -> Int -> (Ptr a -> IO b) -> IO b Source #
executes the computation allocaBytesAligned
size align ff
,
passing as argument a pointer to a temporarily allocated block of memory
of size
bytes and aligned to align
bytes. The value of align
must
be a power of two.
The memory is freed when f
terminates (either normally or via an
exception), so the pointer passed to f
must not be used after this.
allocaBytes :: Int -> (Ptr a -> IO b) -> IO b Source #
executes the computation allocaBytes
n ff
, passing as argument
a pointer to a temporarily allocated block of memory of n
bytes.
The block of memory is sufficiently aligned for any of the basic
foreign types that fits into a memory block of the allocated size.
The memory is freed when f
terminates (either normally or via an
exception), so the pointer passed to f
must not be used after this.
alloca :: Storable a => (Ptr a -> IO b) -> IO b Source #
executes the computation alloca
ff
, passing as argument
a pointer to a temporarily allocated block of memory sufficient to
hold values of type a
.
The memory is freed when f
terminates (either normally or via an
exception), so the pointer passed to f
must not be used after this.
class Storable a where Source #
The member functions of this class facilitate writing values of primitive types to raw memory (which may have been allocated with the above mentioned routines) and reading values from blocks of raw memory. The class, furthermore, includes support for computing the storage requirements and alignment restrictions of storable types.
Memory addresses are represented as values of type
, for some
Ptr
aa
which is an instance of class Storable
. The type argument to
Ptr
helps provide some valuable type safety in FFI code (you can't
mix pointers of different types without an explicit cast), while
helping the Haskell type system figure out which marshalling method is
needed for a given pointer.
All marshalling between Haskell and a foreign language ultimately
boils down to translating Haskell data structures into the binary
representation of a corresponding data structure of the foreign
language and vice versa. To code this marshalling in Haskell, it is
necessary to manipulate primitive data types stored in unstructured
memory blocks. The class Storable
facilitates this manipulation on
all types for which it is instantiated, which are the standard basic
types of Haskell, the fixed size Int
types (Int8
, Int16
,
Int32
, Int64
), the fixed size Word
types (Word8
, Word16
,
Word32
, Word64
), StablePtr
, all types from Foreign.C.Types,
as well as Ptr
.
sizeOf, alignment, (peek | peekElemOff | peekByteOff), (poke | pokeElemOff | pokeByteOff)
Computes the storage requirements (in bytes) of the argument. The value of the argument is not used.
alignment :: a -> Int Source #
Computes the alignment constraint of the argument. An
alignment constraint x
is fulfilled by any address divisible
by x
. The alignment must be a power of two if this instance
is to be used with alloca
or allocaArray
. The value of
the argument is not used.
peekElemOff :: Ptr a -> Int -> IO a Source #
Read a value from a memory area regarded as an array
of values of the same kind. The first argument specifies
the start address of the array and the second the index into
the array (the first element of the array has index
0
). The following equality holds,
peekElemOff addr idx = IOExts.fixIO $ \result -> peek (addr `plusPtr` (idx * sizeOf result))
Note that this is only a specification, not necessarily the concrete implementation of the function.
pokeElemOff :: Ptr a -> Int -> a -> IO () Source #
Write a value to a memory area regarded as an array of values of the same kind. The following equality holds:
pokeElemOff addr idx x = poke (addr `plusPtr` (idx * sizeOf x)) x
peekByteOff :: Ptr b -> Int -> IO a Source #
Read a value from a memory location given by a base address and offset. The following equality holds:
peekByteOff addr off = peek (addr `plusPtr` off)
pokeByteOff :: Ptr b -> Int -> a -> IO () Source #
Write a value to a memory location given by a base address and offset. The following equality holds:
pokeByteOff addr off x = poke (addr `plusPtr` off) x
peek :: Ptr a -> IO a Source #
Read a value from the given memory location.
Note that the peek and poke functions might require properly
aligned addresses to function correctly. This is architecture
dependent; thus, portable code should ensure that when peeking or
poking values of some type a
, the alignment
constraint for a
, as given by the function
alignment
is fulfilled.
poke :: Ptr a -> a -> IO () Source #
Write the given value to the given memory location. Alignment
restrictions might apply; see peek
.
Instances
throwErrnoPathIfMinus1_ :: (Eq a, Num a) => String -> FilePath -> IO a -> IO () Source #
as throwErrnoIfMinus1_
, but exceptions include the given path when
appropriate.
throwErrnoIfNull :: String -> IO (Ptr a) -> IO (Ptr a) Source #
Throw an IOException
corresponding to the current value of getErrno
if the IO
action returns nullPtr
.
throwErrnoIfMinus1_ :: (Eq a, Num a) => String -> IO a -> IO () Source #
as throwErrnoIfMinus1
, but discards the result.
throwErrnoIfMinus1Retry_ :: (Eq a, Num a) => String -> IO a -> IO () Source #
as throwErrnoIfMinus1
, but discards the result.
type CWString = Ptr CWchar Source #
A C wide string is a reference to an array of C wide characters terminated by NUL.
type CString = Ptr CChar Source #
A C string is a reference to an array of C characters terminated by NUL.
withCWString :: String -> (CWString -> IO a) -> IO a Source #
Marshal a Haskell string into a NUL terminated C wide string using temporary storage.
- the Haskell string may not contain any NUL characters
- the memory is freed when the subcomputation terminates (either normally or via an exception), so the pointer to the temporary storage must not be used after this.
withCString :: String -> (CString -> IO a) -> IO a Source #
Marshal a Haskell string into a NUL terminated C string using temporary storage.
- the Haskell string may not contain any NUL characters
- the memory is freed when the subcomputation terminates (either normally or via an exception), so the pointer to the temporary storage must not be used after this.
peekCWStringLen :: CWStringLen -> IO String Source #
Marshal a C wide string with explicit length into a Haskell string.
peekCString :: CString -> IO String Source #
Marshal a NUL terminated C string into a Haskell string.
Haskell type representing the C wchar_t
type.
(The concrete types of Foreign.C.Types are platform-specific.)
Instances
Haskell type representing the C unsigned short
type.
(The concrete types of Foreign.C.Types are platform-specific.)
Instances
Haskell type representing the C unsigned long
type.
(The concrete types of Foreign.C.Types are platform-specific.)
Instances
Haskell type representing the C unsigned char
type.
(The concrete types of Foreign.C.Types are platform-specific.)
Instances
Haskell type representing the C time_t
type.
(The concrete types of Foreign.C.Types are platform-specific.)
Instances
Storable CTime | |
Defined in Foreign.C.Types sizeOf :: CTime -> Int Source # alignment :: CTime -> Int Source # peekElemOff :: Ptr CTime -> Int -> IO CTime Source # pokeElemOff :: Ptr CTime -> Int -> CTime -> IO () Source # peekByteOff :: Ptr b -> Int -> IO CTime Source # pokeByteOff :: Ptr b -> Int -> CTime -> IO () Source # | |
Enum CTime | |
Defined in Foreign.C.Types succ :: CTime -> CTime Source # pred :: CTime -> CTime Source # toEnum :: Int -> CTime Source # fromEnum :: CTime -> Int Source # enumFrom :: CTime -> [CTime] Source # enumFromThen :: CTime -> CTime -> [CTime] Source # enumFromTo :: CTime -> CTime -> [CTime] Source # enumFromThenTo :: CTime -> CTime -> CTime -> [CTime] Source # | |
Num CTime | |
Read CTime | |
Real CTime | |
Defined in Foreign.C.Types toRational :: CTime -> Rational Source # | |
Show CTime | |
Eq CTime | |
Ord CTime | |
Haskell type representing the C long
type.
(The concrete types of Foreign.C.Types are platform-specific.)
Instances
Haskell type representing the C int
type.
(The concrete types of Foreign.C.Types are platform-specific.)
Instances
getFileSystemEncoding :: IO TextEncoding Source #
The Unicode encoding of the current locale, but allowing arbitrary undecodable bytes to be round-tripped through it.
This TextEncoding
is used to decode and encode command line arguments
and environment variables on non-Windows platforms.
On Windows, this encoding *should not* be used if possible because the use of code pages is deprecated: Strings should be retrieved via the "wide" W-family of UTF-16 APIs instead
Since: base-4.5.0.0
data IOErrorType Source #
An abstract type that contains a value for each variant of IOException
.
Instances
Show IOErrorType | Since: base-4.1.0.0 |
Defined in GHC.IO.Exception | |
Eq IOErrorType | Since: base-4.1.0.0 |
Defined in GHC.IO.Exception (==) :: IOErrorType -> IOErrorType -> Bool # (/=) :: IOErrorType -> IOErrorType -> Bool # |
lookupEnv :: String -> IO (Maybe String) Source #
Return the value of the environment variable var
, or Nothing
if
there is no such value.
For POSIX users, this is equivalent to getEnv
.
Since: base-4.6.0.0
getEnv :: String -> IO String Source #
Computation getEnv
var
returns the value
of the environment variable var
. For the inverse, the
setEnv
function can be used.
This computation may fail with:
isDoesNotExistError
if the environment variable does not exist.
getArgs :: IO [String] Source #
Computation getArgs
returns a list of the program's command
line arguments (not including the program name).
exitFailure :: IO a Source #
The computation exitFailure
is equivalent to
exitWith
(
ExitFailure
exitfail)
,
where exitfail is implementation-dependent.
openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle) Source #
Like openTempFile
, but opens the file in binary mode. See openBinaryFile
for more comments.
hClose :: Handle -> IO () Source #
Computation hClose
hdl
makes handle hdl
closed. Before the
computation finishes, if hdl
is writable its buffer is flushed as
for hFlush
.
Performing hClose
on a handle that has already been closed has no effect;
doing so is not an error. All other operations on a closed handle will fail.
If hClose
fails for any reason, any further operations (apart from
hClose
) on the handle will still fail as if hdl
had been successfully
closed.
hClose
is an interruptible operation in the sense described in
Control.Exception. If hClose
is interrupted by an asynchronous
exception in the process of flushing its buffers, then the I/O device
(e.g., file) will be closed anyway.
hPutStr :: Handle -> String -> IO () Source #
Computation hPutStr
hdl s
writes the string
s
to the file or channel managed by hdl
.
This operation may fail with:
isFullError
if the device is full; orisPermissionError
if another system resource limit would be exceeded.
hPutBuf :: Handle -> Ptr a -> Int -> IO () Source #
hPutBuf
hdl buf count
writes count
8-bit bytes from the
buffer buf
to the handle hdl
. It returns ().
hPutBuf
ignores any text encoding that applies to the Handle
,
writing the bytes directly to the underlying file or device.
hPutBuf
ignores the prevailing TextEncoding
and
NewlineMode
on the Handle
, and writes bytes directly.
This operation may fail with:
ResourceVanished
if the handle is a pipe or socket, and the reading end is closed. (If this is a POSIX system, and the program has not asked to ignore SIGPIPE, then a SIGPIPE may be delivered instead, whose default action is to terminate the program).
hGetBuf :: Handle -> Ptr a -> Int -> IO Int Source #
hGetBuf
hdl buf count
reads data from the handle hdl
into the buffer buf
until either EOF is reached or
count
8-bit bytes have been read.
It returns the number of bytes actually read. This may be zero if
EOF was reached before any data was read (or if count
is zero).
hGetBuf
never raises an EOF exception, instead it returns a value
smaller than count
.
If the handle is a pipe or socket, and the writing end
is closed, hGetBuf
will behave as if EOF was reached.
hGetBuf
ignores the prevailing TextEncoding
and NewlineMode
on the Handle
, and reads bytes directly.
hFlush :: Handle -> IO () Source #
The action hFlush
hdl
causes any items buffered for output
in handle hdl
to be sent immediately to the operating system.
This operation may fail with:
isFullError
if the device is full;isPermissionError
if a system resource limit would be exceeded. It is unspecified whether the characters in the buffer are discarded or retained under these circumstances.
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.
See openFile
Instances
Enum IOMode | Since: base-4.2.0.0 |
Defined in GHC.IO.IOMode succ :: IOMode -> IOMode Source # pred :: IOMode -> IOMode Source # toEnum :: Int -> IOMode Source # fromEnum :: IOMode -> Int Source # enumFrom :: IOMode -> [IOMode] Source # enumFromThen :: IOMode -> IOMode -> [IOMode] Source # enumFromTo :: IOMode -> IOMode -> [IOMode] Source # enumFromThenTo :: IOMode -> IOMode -> IOMode -> [IOMode] Source # | |
Ix IOMode | Since: base-4.2.0.0 |
Read IOMode | Since: base-4.2.0.0 |
Show IOMode | Since: base-4.2.0.0 |
Eq IOMode | Since: base-4.2.0.0 |
Ord IOMode | Since: base-4.2.0.0 |
tryIOError :: IO a -> IO (Either IOError a) Source #
The construct tryIOError
comp
exposes IO errors which occur within a
computation, and which are not fully handled.
Non-I/O exceptions are not caught by this variant; to catch all
exceptions, use try
from Control.Exception.
Since: base-4.4.0.0
permissionErrorType :: IOErrorType Source #
I/O error where the operation failed because the user does not have sufficient operating system privilege to perform that operation.
modifyIOError :: (IOError -> IOError) -> IO a -> IO a Source #
Catch any IOException
that occurs in the computation and throw a
modified version.
mkIOError :: IOErrorType -> String -> Maybe Handle -> Maybe FilePath -> IOError Source #
Construct an IOException
of the given type where the second argument
describes the error location and the third and fourth argument
contain the file handle and file path of the file involved in the
error if applicable.
isPermissionError :: IOError -> Bool Source #
An error indicating that an IO
operation failed because
the user does not have sufficient operating system privilege
to perform that operation.
isIllegalOperation :: IOError -> Bool Source #
An error indicating that an IO
operation failed because
the operation was not possible.
Any computation which returns an IO
result may fail with
isIllegalOperation
. In some cases, an implementation will not be
able to distinguish between the possible error causes. In this case
it should fail with isIllegalOperation
.
isDoesNotExistError :: IOError -> Bool Source #
An error indicating that an IO
operation failed because
one of its arguments does not exist.
isAlreadyExistsError :: IOError -> Bool Source #
An error indicating that an IO
operation failed because
one of its arguments already exists.
ioeGetLocation :: IOError -> String Source #
ioeGetErrorType :: IOError -> IOErrorType Source #
ioeGetErrorString :: IOError -> String Source #
illegalOperationErrorType :: IOErrorType Source #
I/O error where the operation is not possible.
catchIOError :: IO a -> (IOError -> IO a) -> IO a Source #
The catchIOError
function establishes a handler that receives any
IOException
raised in the action protected by catchIOError
.
An IOException
is caught by
the most recent handler established by one of the exception handling
functions. These handlers are
not selective: all IOException
s are caught. Exception propagation
must be explicitly provided in a handler by re-raising any unwanted
exceptions. For example, in
f = catchIOError g (\e -> if IO.isEOFError e then return [] else ioError e)
the function f
returns []
when an end-of-file exception
(cf. isEOFError
) occurs in g
; otherwise, the
exception is propagated to the next outer handler.
When an exception propagates outside the main program, the Haskell
system prints the associated IOException
value and exits the program.
Non-I/O exceptions are not caught by this variant; to catch all
exceptions, use catch
from Control.Exception.
Since: base-4.4.0.0
type IOError = IOException Source #
The Haskell 2010 type for exceptions in the IO
monad.
Any I/O operation may raise an IOException
instead of returning a result.
For a more general type of exception, including also those that arise
in pure code, see Exception
.
In Haskell 2010, this is an opaque type.
userError :: String -> IOError Source #
Construct an IOException
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)
timeout :: Int -> IO a -> IO (Maybe a) Source #
Wrap an IO
computation to time out and return Nothing
in case no result
is available within n
microseconds (1/10^6
seconds). In case a result
is available before the timeout expires, Just a
is returned. A negative
timeout interval means "wait indefinitely". When specifying long timeouts,
be careful not to exceed maxBound :: Int
.
>>>
timeout 1000000 (threadDelay 1000 *> pure "finished on time")
Just "finished on time"
>>>
timeout 10000 (threadDelay 100000 *> pure "finished on time")
Nothing
The design of this combinator was guided by the objective that timeout n f
should behave exactly the same as f
as long as f
doesn't time out. This
means that f
has the same myThreadId
it would have without the timeout
wrapper. Any exceptions f
might throw cancel the timeout and propagate
further up. It also possible for f
to receive exceptions thrown to it by
another thread.
A tricky implementation detail is the question of how to abort an IO
computation. This combinator relies on asynchronous exceptions internally
(namely throwing the computation the Timeout
exception). The technique
works very well for computations executing inside of the Haskell runtime
system, but it doesn't work at all for non-Haskell code. Foreign function
calls, for example, cannot be timed out with this combinator simply because
an arbitrary C function cannot receive asynchronous exceptions. When
timeout
is used to wrap an FFI call that blocks, no timeout event can be
delivered until the FFI call returns, which pretty much negates the purpose
of the combinator. In practice, however, this limitation is less severe than
it may sound. Standard I/O functions like hGetBuf
,
hPutBuf
, Network.Socket.accept, or hWaitForInput
appear to be blocking, but they really don't because the runtime system uses
scheduling mechanisms like select(2)
to perform asynchronous I/O, so it
is possible to interrupt standard socket I/O or file I/O using this
combinator.
Uninhabited data type
Since: base-4.8.0.0
Instances
Data Void | Since: base-4.8.0.0 |
Defined in Data.Void gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Void -> c Void Source # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c Void Source # toConstr :: Void -> Constr Source # dataTypeOf :: Void -> DataType Source # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c Void) Source # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c Void) Source # gmapT :: (forall b. Data b => b -> b) -> Void -> Void Source # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Void -> r Source # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Void -> r Source # gmapQ :: (forall d. Data d => d -> u) -> Void -> [u] Source # gmapQi :: Int -> (forall d. Data d => d -> u) -> Void -> u Source # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Void -> m Void Source # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Void -> m Void Source # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Void -> m Void Source # | |
Semigroup Void | Since: base-4.9.0.0 |
Exception Void | Since: base-4.8.0.0 |
Defined in Data.Void toException :: Void -> SomeException Source # fromException :: SomeException -> Maybe Void Source # displayException :: Void -> String Source # | |
Generic Void | |
Ix Void | Since: base-4.8.0.0 |
Read Void | Reading a Since: base-4.8.0.0 |
Show Void | Since: base-4.8.0.0 |
Eq Void | Since: base-4.8.0.0 |
Ord Void | Since: base-4.8.0.0 |
type Rep Void | Since: base-4.8.0.0 |