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
- putMVar :: MVar a -> a -> IO ()
- readMVar :: MVar a -> IO a
- takeMVar :: MVar a -> IO a
- newEmptyMVar :: IO (MVar a)
- bracket_ :: IO a -> IO b -> IO c -> IO c
- finally :: IO a -> IO b -> IO a
- bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
- onException :: IO a -> IO b -> IO a
- try :: Exception e => IO a -> IO (Either e a)
- mask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
- throwIO :: Exception e => e -> IO a
- 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 => (b -> m c) -> (a -> m b) -> a -> m c
- (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> 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
- isAlpha :: Char -> Bool
- isAscii :: Char -> Bool
- for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f ()
- traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()
- on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
- catMaybes :: [Maybe a] -> [a]
- maybeToList :: Maybe a -> [a]
- fromMaybe :: a -> Maybe a -> a
- (<>) :: Semigroup a => a -> a -> a
- mempty :: Monoid a => a
- mconcat :: Monoid a => [a] -> a
- writeIORef :: IORef a -> a -> IO ()
- readIORef :: IORef a -> IO a
- newIORef :: a -> IO (IORef a)
- data 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
- maybeWith :: (a -> (Ptr b -> IO c) -> IO c) -> Maybe a -> (Ptr b -> IO c) -> IO c
- with :: Storable a => a -> (Ptr a -> IO b) -> IO b
- 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)
- throwErrnoIfMinus1Retry_ :: (Eq a, Num a) => String -> IO a -> IO ()
- throwErrnoIfMinus1_ :: (Eq a, Num a) => String -> IO a -> IO ()
- withCWString :: String -> (CWString -> IO a) -> IO a
- peekCWStringLen :: CWStringLen -> IO String
- withCString :: String -> (CString -> IO a) -> IO a
- peekCString :: CString -> IO String
- type CString = Ptr CChar
- type CWString = Ptr CWchar
- newtype CUChar = CUChar Word8
- newtype CUShort = CUShort Word16
- newtype CInt = CInt Int32
- newtype CLong = CLong Int64
- newtype CULong = CULong Word64
- newtype CWchar = CWchar Int32
- newtype CTime = CTime Int64
- getFileSystemEncoding :: IO TextEncoding
- data IOErrorType
- lookupEnv :: String -> IO (Maybe String)
- getEnv :: String -> IO String
- getArgs :: IO [String]
- exitFailure :: IO a
- data Handle
- openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle)
- withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
- hClose :: Handle -> IO ()
- stderr :: Handle
- hGetBuf :: Handle -> Ptr a -> Int -> IO Int
- hPutBuf :: Handle -> Ptr a -> Int -> IO ()
- hPutStrLn :: Handle -> String -> IO ()
- hPutStr :: Handle -> String -> IO ()
- hFlush :: Handle -> IO ()
- stdout :: Handle
- data IOMode
- catchIOError :: IO a -> (IOError -> IO a) -> IO a
- modifyIOError :: (IOError -> IOError) -> IO a -> IO a
- ioeSetFileName :: IOError -> FilePath -> IOError
- ioeSetLocation :: IOError -> String -> IOError
- ioeSetErrorString :: IOError -> String -> IOError
- ioeGetLocation :: IOError -> String
- ioeGetErrorString :: IOError -> String
- ioeGetErrorType :: IOError -> IOErrorType
- permissionErrorType :: IOErrorType
- illegalOperationErrorType :: IOErrorType
- isPermissionError :: IOError -> Bool
- isIllegalOperation :: IOError -> Bool
- isDoesNotExistError :: IOError -> Bool
- isAlreadyExistsError :: IOError -> Bool
- mkIOError :: IOErrorType -> String -> Maybe Handle -> Maybe FilePath -> IOError
- tryIOError :: IO a -> IO (Either IOError a)
- userError :: String -> IOError
- type IOError = IOException
- 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) #
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 #
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 () #
killThread
raises the ThreadKilled
exception in the given
thread (GHC only).
killThread tid = throwTo tid ThreadKilled
forkIO :: IO () -> IO ThreadId #
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.
putMVar :: MVar a -> a -> IO () #
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.
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
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.
newEmptyMVar :: IO (MVar a) #
Create an MVar
which is initially empty.
bracket_ :: IO a -> IO b -> IO c -> IO c #
A variant of bracket
where the return value from the first computation
is not required.
:: 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.
:: 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
onException :: IO a -> IO b -> IO a #
Like finally
, but only performs the final action if there was an
exception raised by the computation.
try :: Exception e => IO a -> IO (Either e a) #
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 than it will be propogated
up to the next enclosing exception handler.
try a = catch (Right `liftM` a) (return . Left)
mask :: ((forall a. IO a -> IO a) -> IO b) -> IO b #
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
.
throwIO :: Exception e => e -> IO a #
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.
:: 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 propogated further up. If you call it again, you
might get a the opposite behaviour. This is ok, because catch
is an
IO
computation.
data SomeException #
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
Show SomeException | Since: base-3.0 |
Defined in GHC.Exception.Type showsPrec :: Int -> SomeException -> ShowS # show :: SomeException -> String # showList :: [SomeException] -> ShowS # | |
Exception SomeException | Since: base-3.0 |
Defined in GHC.Exception.Type |
unless :: Applicative f => Bool -> f () -> f () #
The reverse of when
.
replicateM_ :: Applicative m => Int -> m a -> m () #
Like replicateM
, but discards the result.
replicateM :: Applicative m => Int -> m a -> m [a] #
performs the action replicateM
n actn
times,
gathering the results.
Using ApplicativeDo
: '
' can be understood as
the replicateM
5 asdo
expression
do a1 <- as a2 <- as a3 <- as a4 <- as a5 <- as pure [a1,a2,a3,a4,a5]
Note the Applicative
constraint.
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 #
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 () #
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 #
Reverse all the bits in the argument
Convert a letter to the corresponding upper-case letter, if any. Any other character is returned unchanged.
Convert a letter to the corresponding lower-case letter, if any. Any other character is returned unchanged.
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
.
Selects the first 128 characters of the Unicode character set, corresponding to the ASCII character set.
for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f () #
traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f () #
Map each element of a structure to an action, evaluate these
actions from left to right, and ignore the results. For a version
that doesn't ignore the results see traverse
.
catMaybes :: [Maybe a] -> [a] #
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]
maybeToList :: Maybe a -> [a] #
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 #
The fromMaybe
function takes a default value and and Maybe
value. If the Maybe
is Nothing
, it returns the default values;
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
(<>) :: Semigroup a => a -> a -> a infixr 6 #
An associative operation.
>>>
[1,2,3] <> [4,5,6]
[1,2,3,4,5,6]
mconcat :: Monoid a => [a] -> a #
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!"
writeIORef :: IORef a -> a -> IO () #
Write a new value into an IORef
A mutable variable in the IO
monad
for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b) #
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
Eq (Ptr a) | Since: base-2.1 |
Ord (Ptr a) | Since: base-2.1 |
Show (Ptr a) | Since: base-2.1 |
Foldable (UAddr :: Type -> Type) | Since: base-4.9.0.0 |
Defined in Data.Foldable fold :: Monoid m => UAddr m -> m # foldMap :: Monoid m => (a -> m) -> UAddr a -> m # foldMap' :: Monoid m => (a -> m) -> UAddr a -> m # foldr :: (a -> b -> b) -> b -> UAddr a -> b # foldr' :: (a -> b -> b) -> b -> UAddr a -> b # foldl :: (b -> a -> b) -> b -> UAddr a -> b # foldl' :: (b -> a -> b) -> b -> UAddr a -> b # foldr1 :: (a -> a -> a) -> UAddr a -> a # foldl1 :: (a -> a -> a) -> UAddr a -> a # elem :: Eq a => a -> UAddr a -> Bool # maximum :: Ord a => UAddr a -> a # minimum :: Ord a => UAddr a -> a # | |
Traversable (UAddr :: Type -> Type) | Since: base-4.9.0.0 |
Storable (Ptr a) | Since: base-2.1 |
withArray :: Storable a => [a] -> (Ptr a -> IO b) -> IO b #
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 #
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 #
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.
allocaBytes :: Int -> (Ptr a -> IO b) -> IO b #
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 #
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.
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.
Computes the alignment constraint of the argument. An
alignment constraint x
is fulfilled by any address divisible
by x
. The value of the argument is not used.
peekElemOff :: Ptr a -> Int -> IO a #
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 () #
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 #
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 () #
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
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.
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 () #
as throwErrnoIfMinus1_
, but exceptions include the given path when
appropriate.
throwErrnoIfMinus1Retry_ :: (Eq a, Num a) => String -> IO a -> IO () #
as throwErrnoIfMinus1
, but discards the result.
throwErrnoIfMinus1_ :: (Eq a, Num a) => String -> IO a -> IO () #
as throwErrnoIfMinus1
, but discards the result.
withCWString :: String -> (CWString -> IO a) -> IO a #
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.
peekCWStringLen :: CWStringLen -> IO String #
Marshal a C wide string with explicit length into a Haskell string.
withCString :: String -> (CString -> IO a) -> IO a #
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.
peekCString :: CString -> IO String #
Marshal a NUL terminated C string into a Haskell string.
A C wide string is a reference to an array of C wide characters terminated by NUL.
Haskell type representing the C unsigned char
type.
(The concrete types of Foreign.C.Types are platform-specific.)
Instances
Bounded CUChar | |
Enum CUChar | |
Defined in Foreign.C.Types | |
Eq CUChar | |
Integral CUChar | |
Num CUChar | |
Ord CUChar | |
Read CUChar | |
Real CUChar | |
Defined in Foreign.C.Types toRational :: CUChar -> Rational # | |
Show CUChar | |
Storable CUChar | |
Bits CUChar | |
Defined in Foreign.C.Types (.&.) :: CUChar -> CUChar -> CUChar # (.|.) :: CUChar -> CUChar -> CUChar # xor :: CUChar -> CUChar -> CUChar # complement :: CUChar -> CUChar # shift :: CUChar -> Int -> CUChar # rotate :: CUChar -> Int -> CUChar # setBit :: CUChar -> Int -> CUChar # clearBit :: CUChar -> Int -> CUChar # complementBit :: CUChar -> Int -> CUChar # testBit :: CUChar -> Int -> Bool # bitSizeMaybe :: CUChar -> Maybe Int # shiftL :: CUChar -> Int -> CUChar # unsafeShiftL :: CUChar -> Int -> CUChar # shiftR :: CUChar -> Int -> CUChar # unsafeShiftR :: CUChar -> Int -> CUChar # rotateL :: CUChar -> Int -> CUChar # | |
FiniteBits CUChar | |
Defined in Foreign.C.Types finiteBitSize :: CUChar -> Int # countLeadingZeros :: CUChar -> Int # countTrailingZeros :: CUChar -> Int # |
Haskell type representing the C unsigned short
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
Bounded CInt | |
Enum CInt | |
Eq CInt | |
Integral CInt | |
Num CInt | |
Ord CInt | |
Read CInt | |
Real CInt | |
Defined in Foreign.C.Types toRational :: CInt -> Rational # | |
Show CInt | |
Storable CInt | |
Defined in Foreign.C.Types | |
Bits CInt | |
Defined in Foreign.C.Types (.&.) :: CInt -> CInt -> CInt # (.|.) :: CInt -> CInt -> CInt # complement :: CInt -> CInt # shift :: CInt -> Int -> CInt # rotate :: CInt -> Int -> CInt # setBit :: CInt -> Int -> CInt # clearBit :: CInt -> Int -> CInt # complementBit :: CInt -> Int -> CInt # testBit :: CInt -> Int -> Bool # bitSizeMaybe :: CInt -> Maybe Int # shiftL :: CInt -> Int -> CInt # unsafeShiftL :: CInt -> Int -> CInt # shiftR :: CInt -> Int -> CInt # unsafeShiftR :: CInt -> Int -> CInt # rotateL :: CInt -> Int -> CInt # | |
FiniteBits CInt | |
Defined in Foreign.C.Types |
Haskell type representing the C long
type.
(The concrete types of Foreign.C.Types are platform-specific.)
Instances
Bounded CLong | |
Enum CLong | |
Eq CLong | |
Integral CLong | |
Num CLong | |
Ord CLong | |
Read CLong | |
Real CLong | |
Defined in Foreign.C.Types toRational :: CLong -> Rational # | |
Show CLong | |
Storable CLong | |
Bits CLong | |
Defined in Foreign.C.Types (.&.) :: CLong -> CLong -> CLong # (.|.) :: CLong -> CLong -> CLong # xor :: CLong -> CLong -> CLong # complement :: CLong -> CLong # shift :: CLong -> Int -> CLong # rotate :: CLong -> Int -> CLong # setBit :: CLong -> Int -> CLong # clearBit :: CLong -> Int -> CLong # complementBit :: CLong -> Int -> CLong # testBit :: CLong -> Int -> Bool # bitSizeMaybe :: CLong -> Maybe Int # shiftL :: CLong -> Int -> CLong # unsafeShiftL :: CLong -> Int -> CLong # shiftR :: CLong -> Int -> CLong # unsafeShiftR :: CLong -> Int -> CLong # rotateL :: CLong -> Int -> CLong # | |
FiniteBits CLong | |
Defined in Foreign.C.Types finiteBitSize :: CLong -> Int # countLeadingZeros :: CLong -> Int # countTrailingZeros :: CLong -> Int # |
Haskell type representing the C unsigned long
type.
(The concrete types of Foreign.C.Types are platform-specific.)
Instances
Bounded CULong | |
Enum CULong | |
Defined in Foreign.C.Types | |
Eq CULong | |
Integral CULong | |
Num CULong | |
Ord CULong | |
Read CULong | |
Real CULong | |
Defined in Foreign.C.Types toRational :: CULong -> Rational # | |
Show CULong | |
Storable CULong | |
Bits CULong | |
Defined in Foreign.C.Types (.&.) :: CULong -> CULong -> CULong # (.|.) :: CULong -> CULong -> CULong # xor :: CULong -> CULong -> CULong # complement :: CULong -> CULong # shift :: CULong -> Int -> CULong # rotate :: CULong -> Int -> CULong # setBit :: CULong -> Int -> CULong # clearBit :: CULong -> Int -> CULong # complementBit :: CULong -> Int -> CULong # testBit :: CULong -> Int -> Bool # bitSizeMaybe :: CULong -> Maybe Int # shiftL :: CULong -> Int -> CULong # unsafeShiftL :: CULong -> Int -> CULong # shiftR :: CULong -> Int -> CULong # unsafeShiftR :: CULong -> Int -> CULong # rotateL :: CULong -> Int -> CULong # | |
FiniteBits CULong | |
Defined in Foreign.C.Types finiteBitSize :: CULong -> Int # countLeadingZeros :: CULong -> Int # countTrailingZeros :: CULong -> Int # |
Haskell type representing the C wchar_t
type.
(The concrete types of Foreign.C.Types are platform-specific.)
Instances
Bounded CWchar | |
Enum CWchar | |
Defined in Foreign.C.Types | |
Eq CWchar | |
Integral CWchar | |
Num CWchar | |
Ord CWchar | |
Read CWchar | |
Real CWchar | |
Defined in Foreign.C.Types toRational :: CWchar -> Rational # | |
Show CWchar | |
Storable CWchar | |
Bits CWchar | |
Defined in Foreign.C.Types (.&.) :: CWchar -> CWchar -> CWchar # (.|.) :: CWchar -> CWchar -> CWchar # xor :: CWchar -> CWchar -> CWchar # complement :: CWchar -> CWchar # shift :: CWchar -> Int -> CWchar # rotate :: CWchar -> Int -> CWchar # setBit :: CWchar -> Int -> CWchar # clearBit :: CWchar -> Int -> CWchar # complementBit :: CWchar -> Int -> CWchar # testBit :: CWchar -> Int -> Bool # bitSizeMaybe :: CWchar -> Maybe Int # shiftL :: CWchar -> Int -> CWchar # unsafeShiftL :: CWchar -> Int -> CWchar # shiftR :: CWchar -> Int -> CWchar # unsafeShiftR :: CWchar -> Int -> CWchar # rotateL :: CWchar -> Int -> CWchar # | |
FiniteBits CWchar | |
Defined in Foreign.C.Types finiteBitSize :: CWchar -> Int # countLeadingZeros :: CWchar -> Int # countTrailingZeros :: CWchar -> Int # |
Haskell type representing the C time_t
type.
(The concrete types of Foreign.C.Types are platform-specific.)
Instances
Enum CTime | |
Eq CTime | |
Num CTime | |
Ord CTime | |
Read CTime | |
Real CTime | |
Defined in Foreign.C.Types toRational :: CTime -> Rational # | |
Show CTime | |
Storable CTime | |
getFileSystemEncoding :: IO TextEncoding #
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 #
An abstract type that contains a value for each variant of IOError
.
Instances
Eq IOErrorType | Since: base-4.1.0.0 |
Defined in GHC.IO.Exception (==) :: IOErrorType -> IOErrorType -> Bool # (/=) :: IOErrorType -> IOErrorType -> Bool # | |
Show IOErrorType | Since: base-4.1.0.0 |
Defined in GHC.IO.Exception showsPrec :: Int -> IOErrorType -> ShowS # show :: IOErrorType -> String # showList :: [IOErrorType] -> ShowS # |
lookupEnv :: String -> IO (Maybe String) #
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 #
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.
Computation getArgs
returns a list of the program's command
line arguments (not including the program name).
exitFailure :: IO a #
The computation exitFailure
is equivalent to
exitWith
(
ExitFailure
exitfail)
,
where exitfail is implementation-dependent.
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.
openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle) #
Like openTempFile
, but opens the file in binary mode. See openBinaryFile
for more comments.
withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r #
opens a file using withBinaryFile
name mode actopenBinaryFile
and passes the resulting handle to the computation act
. The handle
will be closed on exit from withBinaryFile
, whether by normal
termination or by raising an exception.
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.
hGetBuf :: Handle -> Ptr a -> Int -> IO Int #
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.
hPutBuf :: Handle -> Ptr a -> Int -> IO () #
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).
hPutStr :: Handle -> String -> IO () #
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.
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.
See openFile
catchIOError :: IO a -> (IOError -> IO a) -> IO a #
The catchIOError
function establishes a handler that receives any
IOError
raised in the action protected by catchIOError
.
An IOError
is caught by
the most recent handler established by one of the exception handling
functions. These handlers are
not selective: all IOError
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 IOError
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
modifyIOError :: (IOError -> IOError) -> IO a -> IO a #
Catch any IOError
that occurs in the computation and throw a
modified version.
ioeSetFileName :: IOError -> FilePath -> IOError #
ioeSetLocation :: IOError -> String -> IOError #
ioeSetErrorString :: IOError -> String -> IOError #
ioeGetLocation :: IOError -> String #
ioeGetErrorString :: IOError -> String #
ioeGetErrorType :: IOError -> IOErrorType #
permissionErrorType :: IOErrorType #
I/O error where the operation failed because the user does not have sufficient operating system privilege to perform that operation.
illegalOperationErrorType :: IOErrorType #
I/O error where the operation is not possible.
isPermissionError :: IOError -> Bool #
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 #
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 #
An error indicating that an IO
operation failed because
one of its arguments does not exist.
isAlreadyExistsError :: IOError -> Bool #
An error indicating that an IO
operation failed because
one of its arguments already exists.
mkIOError :: IOErrorType -> String -> Maybe Handle -> Maybe FilePath -> IOError #
Construct an IOError
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.
tryIOError :: IO a -> IO (Either IOError a) #
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
type IOError = IOException #
timeout :: Int -> IO a -> IO (Maybe a) #
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
Eq Void | Since: base-4.8.0.0 |
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 # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c Void # dataTypeOf :: Void -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c Void) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c Void) # gmapT :: (forall b. Data b => b -> b) -> Void -> Void # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Void -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Void -> r # gmapQ :: (forall d. Data d => d -> u) -> Void -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Void -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Void -> m Void # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Void -> m Void # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Void -> m Void # | |
Ord 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 |
Ix Void | Since: base-4.8.0.0 |
Generic Void | Since: base-4.8.0.0 |
Semigroup Void | Since: base-4.9.0.0 |
Exception Void | Since: base-4.8.0.0 |
Defined in Data.Void toException :: Void -> SomeException # fromException :: SomeException -> Maybe Void # displayException :: Void -> String # | |
type Rep Void | |