System.Directory.Internal.Prelude
Stability | unstable |
---|---|
Portability | portable |
Safe Haskell | Safe-Inferred |
Language | Haskell2010 |
Description
Internal modules are always subject to change from version to version.
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.
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.
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.
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
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.
newEmptyMVar :: IO (MVar a) Source
Create an MVar
which is initially empty.
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.
Arguments
:: 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.
Arguments
:: 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 Source
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) Source
Similar to catch
, but returns an Either
result which is (Right a)
if no exception of type e
was raised, or (Left ex)
if an exception of type 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 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
.
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.
Arguments
:: 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 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
Show SomeException | Since: base-3.0 |
Defined in GHC.Exception.Type MethodsshowsPrec :: Int -> SomeException -> ShowS Source show :: SomeException -> String Source showList :: [SomeException] -> ShowS Source | |
Exception SomeException | Since: base-3.0 |
Defined in GHC.Exception.Type MethodstoException :: SomeException -> SomeException Source fromException :: SomeException -> Maybe SomeException Source |
unless :: Applicative f => Bool -> f () -> f () Source
The reverse of when
.
replicateM_ :: Applicative m => Int -> m a -> m () Source
Like replicateM
, but discards the result.
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c infixr 1 Source
Right-to-left composition of Kleisli arrows. (>=>)
, with the arguments flipped.
Note how this operator resembles function composition (.)
:
(.) :: (b -> c) -> (a -> b) -> a -> c (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 Source
Left-to-right composition of Kleisli arrows.
'(bs >=> cs) a
' can be understood as the do
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
(.&.) :: Bits a => a -> a -> a infixl 7 Source
Bitwise "and"
(.|.) :: Bits a => a -> a -> a infixl 5 Source
Bitwise "or"
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.
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
.
isAscii :: Char -> Bool Source
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 () Source
for_
is traverse_
with its arguments flipped. For a version that doesn't ignore the results see for
.
>>> for_ [1..4] print 1 2 3 4
traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f () Source
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
.
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c infixl 0 Source
on b u x y
runs the binary function b
on the results of applying unary function u
to two arguments x
and y
. From the opposite perspective, it transforms two inputs and combines the outputs.
((+) `on` f) x y = f x + f y
Typical usage: sortBy (compare `on` fst)
.
Algebraic properties:
(*) `on` id = (*) -- (if (*) ∉ {⊥, const ⊥})
((*) `on` f) `on` g = (*) `on` (f . g)
flip on f . flip on g = flip on (g . f)
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]
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 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 Source
An associative operation.
>>> [1,2,3] <> [4,5,6] [1,2,3,4,5,6]
mempty :: Monoid a => a Source
Identity of mappend
>>> "Hello world" <> mempty "Hello world"
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!"
writeIORef :: IORef a -> a -> IO () Source
Write a new value into an IORef
readIORef :: IORef a -> IO a Source
Read the value of an IORef
newIORef :: a -> IO (IORef a) Source
Build a new IORef
A mutable variable in the IO
monad
Instances
for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b) Source
for
is traverse
with its arguments flipped. For a version that ignores the results see for_
.
A value of type Ptr a
represents a pointer to an object, or an array of objects, which may be marshalled to or from Haskell values of type a
.
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 Methodsfold :: 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 |
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).
maybeWith :: (a -> (Ptr b -> IO c) -> IO c) -> Maybe a -> (Ptr b -> IO c) -> IO c Source
Converts a withXXX
combinator into one marshalling a value wrapped into a Maybe
, using nullPtr
to represent Nothing
.
with :: Storable a => a -> (Ptr a -> IO b) -> IO b Source
with val f
executes the computation f
, 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
allocaBytes :: Int -> (Ptr a -> IO b) -> IO b Source
allocaBytes n f
executes the computation f
, 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
alloca f
executes the computation f
, 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 Ptr a
, for some a
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
.
Minimal complete definition
sizeOf, alignment, (peek | peekElemOff | peekByteOff), (poke | pokeElemOff | pokeByteOff)
Methods
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 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
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
plusPtr :: Ptr a -> Int -> Ptr b Source
Advances the given address by the given offset in bytes.
The constant nullPtr
contains a distinguished value of Ptr
that is not associated with a valid memory location.
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 IOError
corresponding to the current value of getErrno
if the IO
action returns nullPtr
.
throwErrnoIfMinus1Retry_ :: (Eq a, Num a) => String -> IO a -> IO () Source
as throwErrnoIfMinus1
, but discards the result.
throwErrnoIfMinus1_ :: (Eq a, Num a) => String -> IO a -> IO () Source
as throwErrnoIfMinus1
, but discards the result.
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.
peekCWStringLen :: CWStringLen -> IO String Source
Marshal a C wide string with explicit length into a Haskell string.
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.
peekCString :: CString -> IO String Source
Marshal a NUL terminated C string into a Haskell string.
type CString = Ptr CChar Source
A C string is a reference to an array of C characters terminated by NUL.
type CWString = Ptr CWchar Source
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
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
Haskell type representing the C long
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 wchar_t
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
Enum CTime | |
Eq CTime | |
Num CTime | |
Ord CTime | |
Read CTime | |
Real CTime | |
Defined in Foreign.C.Types MethodstoRational :: CTime -> Rational Source | |
Show CTime | |
Storable CTime | |
Defined in Foreign.C.Types |
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 IOError
.
Constructors
OtherError | |
InappropriateType | |
UnsupportedOperation |
Instances
Eq IOErrorType | Since: base-4.1.0.0 |
Defined in GHC.IO.Exception | |
Show IOErrorType | Since: base-4.1.0.0 |
Defined in GHC.IO.Exception MethodsshowsPrec :: Int -> IOErrorType -> ShowS Source show :: IOErrorType -> String Source showList :: [IOErrorType] -> ShowS Source |
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.
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.
withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r Source
withBinaryFile name mode act
opens a file using openBinaryFile
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.
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.
A handle managing output to the Haskell program's standard error channel.
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.
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).
hPutStrLn :: Handle -> String -> IO () Source
The same as hPutStr
, but adds a newline character.
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; or -
isPermissionError
if another system resource limit would be exceeded.
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.
A handle managing output to the Haskell program's standard output channel.
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 Methodssucc :: 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 | |
Eq IOMode | Since: base-4.2.0.0 |
Ord IOMode | Since: base-4.2.0.0 |
Read IOMode | Since: base-4.2.0.0 |
Show IOMode | Since: base-4.2.0.0 |
Ix IOMode | Since: base-4.2.0.0 |
Defined in GHC.IO.IOMode Methodsrange :: (IOMode, IOMode) -> [IOMode] Source index :: (IOMode, IOMode) -> IOMode -> Int Source unsafeIndex :: (IOMode, IOMode) -> IOMode -> Int Source inRange :: (IOMode, IOMode) -> IOMode -> Bool Source rangeSize :: (IOMode, IOMode) -> Int Source unsafeRangeSize :: (IOMode, IOMode) -> Int Source |
catchIOError :: IO a -> (IOError -> IO a) -> IO a Source
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 Source
Catch any IOError
that occurs in the computation and throw a modified version.
ioeSetFileName :: IOError -> FilePath -> IOError Source
ioeSetLocation :: IOError -> String -> IOError Source
ioeSetErrorString :: IOError -> String -> IOError Source
ioeGetLocation :: IOError -> String Source
ioeGetErrorString :: IOError -> String Source
ioeGetErrorType :: IOError -> IOErrorType Source
permissionErrorType :: IOErrorType Source
I/O error where the operation failed because the user does not have sufficient operating system privilege to perform that operation.
illegalOperationErrorType :: IOErrorType Source
I/O error where the operation is not possible.
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.
mkIOError :: IOErrorType -> String -> Maybe Handle -> Maybe FilePath -> IOError Source
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) 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
userError :: String -> IOError Source
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)
type IOError = IOException Source
The Haskell 2010 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 Exception
.
In Haskell 2010, this is an opaque type.
withFilePath :: FilePath -> (CString -> IO a) -> IO a Source
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
Eq Void | Since: base-4.8.0.0 |
Data Void | Since: base-4.8.0.0 |
Defined in Data.Void Methodsgfoldl :: (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 | |
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 MethodstoException :: Void -> SomeException Source fromException :: SomeException -> Maybe Void Source displayException :: Void -> String Source | |
type Rep Void | |
© The University of Glasgow and others
Licensed under a BSD-style license (see top of the page).
https://downloads.haskell.org/~ghc/8.10.2/docs/html/libraries/directory-1.3.6.0/System-Directory-Internal-Prelude.html