-- Hoogle documentation, generated by Haddock
-- See Hoogle, http://www.haskell.org/hoogle/


-- | Basic libraries
--   
--   This package contains the Prelude and its support libraries, and a
--   large collection of useful libraries ranging from data structures to
--   parsing combinators and debugging utilities.
@package base


-- | The highly unsafe primitive <a>unsafeCoerce</a> converts a value from
--   any type to any other type. Needless to say, if you use this function,
--   it is your responsibility to ensure that the old and new types have
--   identical internal representations, in order to prevent runtime
--   corruption.
--   
--   The types for which <a>unsafeCoerce</a> is representation-safe may
--   differ from compiler to compiler (and version to version).
--   
--   <ul>
--   <li>Documentation for correct usage in GHC will be found under
--   <a>unsafeCoerce#</a> in GHC.Base (around which <a>unsafeCoerce</a> is
--   just a trivial wrapper).</li>
--   <li>In nhc98, the only representation-safe coercions are between Enum
--   types with the same range (e.g. Int, Int32, Char, Word32), or between
--   a newtype and the type that it wraps.</li>
--   </ul>
module Unsafe.Coerce
unsafeCoerce :: a -> b

module GHC.IO.Encoding.CodePage


-- | The tuple data types, and associated functions.
module Data.Tuple

-- | Extract the first component of a pair.
fst :: (a, b) -> a

-- | Extract the second component of a pair.
snd :: (a, b) -> b

-- | <a>curry</a> converts an uncurried function to a curried function.
curry :: ((a, b) -> c) -> a -> b -> c

-- | <a>uncurry</a> converts a curried function to a function on pairs.
uncurry :: (a -> b -> c) -> ((a, b) -> c)

-- | Swap the components of a pair.
swap :: (a, b) -> (b, a)


-- | The Maybe type, and associated operations.
module Data.Maybe

-- | The <a>Maybe</a> type encapsulates an optional value. A value of type
--   <tt><a>Maybe</a> a</tt> either contains a value of type <tt>a</tt>
--   (represented as <tt><a>Just</a> a</tt>), or it is empty (represented
--   as <a>Nothing</a>). Using <a>Maybe</a> is a good way to deal with
--   errors or exceptional cases without resorting to drastic measures such
--   as <a>error</a>.
--   
--   The <a>Maybe</a> type is also a monad. It is a simple kind of error
--   monad, where all errors are represented by <a>Nothing</a>. A richer
--   error monad can be built using the <a>Either</a> type.
data Maybe a
Nothing :: Maybe a
Just :: a -> Maybe a

-- | The <a>maybe</a> function takes a default value, a function, and a
--   <a>Maybe</a> value. If the <a>Maybe</a> value is <a>Nothing</a>, the
--   function returns the default value. Otherwise, it applies the function
--   to the value inside the <a>Just</a> and returns the result.
maybe :: b -> (a -> b) -> Maybe a -> b

-- | The <a>isJust</a> function returns <a>True</a> iff its argument is of
--   the form <tt>Just _</tt>.
isJust :: Maybe a -> Bool

-- | The <a>isNothing</a> function returns <a>True</a> iff its argument is
--   <a>Nothing</a>.
isNothing :: Maybe a -> Bool

-- | The <a>fromJust</a> function extracts the element out of a <a>Just</a>
--   and throws an error if its argument is <a>Nothing</a>.
fromJust :: Maybe a -> a

-- | The <a>fromMaybe</a> function takes a default value and and
--   <a>Maybe</a> value. If the <a>Maybe</a> is <a>Nothing</a>, it returns
--   the default values; otherwise, it returns the value contained in the
--   <a>Maybe</a>.
fromMaybe :: a -> Maybe a -> a

-- | The <a>listToMaybe</a> function returns <a>Nothing</a> on an empty
--   list or <tt><a>Just</a> a</tt> where <tt>a</tt> is the first element
--   of the list.
listToMaybe :: [a] -> Maybe a

-- | The <a>maybeToList</a> function returns an empty list when given
--   <a>Nothing</a> or a singleton list when not given <a>Nothing</a>.
maybeToList :: Maybe a -> [a]

-- | The <a>catMaybes</a> function takes a list of <a>Maybe</a>s and
--   returns a list of all the <a>Just</a> values.
catMaybes :: [Maybe a] -> [a]

-- | The <a>mapMaybe</a> function is a version of <a>map</a> which can
--   throw out elements. In particular, the functional argument returns
--   something of type <tt><a>Maybe</a> b</tt>. If this is <a>Nothing</a>,
--   no element is added on to the result list. If it just <tt><a>Just</a>
--   b</tt>, then <tt>b</tt> is included in the result list.
mapMaybe :: (a -> Maybe b) -> [a] -> [b]
instance Eq a => Eq (Maybe a)
instance Ord a => Ord (Maybe a)
instance Monad Maybe
instance Functor Maybe

module GHC.Char

-- | The <a>toEnum</a> method restricted to the type <a>Char</a>.
chr :: Int -> Char


-- | Converting values to readable strings: the <a>Show</a> class and
--   associated functions.
module Text.Show

-- | The <tt>shows</tt> functions return a function that prepends the
--   output <a>String</a> to an existing <a>String</a>. This allows
--   constant-time concatenation of results using function composition.
type ShowS = String -> String

-- | Conversion of values to readable <a>String</a>s.
--   
--   Minimal complete definition: <a>showsPrec</a> or <a>show</a>.
--   
--   Derived instances of <a>Show</a> have the following properties, which
--   are compatible with derived instances of <a>Read</a>:
--   
--   <ul>
--   <li>The result of <a>show</a> is a syntactically correct Haskell
--   expression containing only constants, given the fixity declarations in
--   force at the point where the type is declared. It contains only the
--   constructor names defined in the data type, parentheses, and spaces.
--   When labelled constructor fields are used, braces, commas, field
--   names, and equal signs are also used.</li>
--   <li>If the constructor is defined to be an infix operator, then
--   <a>showsPrec</a> will produce infix applications of the
--   constructor.</li>
--   <li>the representation will be enclosed in parentheses if the
--   precedence of the top-level constructor in <tt>x</tt> is less than
--   <tt>d</tt> (associativity is ignored). Thus, if <tt>d</tt> is
--   <tt>0</tt> then the result is never surrounded in parentheses; if
--   <tt>d</tt> is <tt>11</tt> it is always surrounded in parentheses,
--   unless it is an atomic expression.</li>
--   <li>If the constructor is defined using record syntax, then
--   <a>show</a> will produce the record-syntax form, with the fields given
--   in the same order as the original declaration.</li>
--   </ul>
--   
--   For example, given the declarations
--   
--   <pre>
--   infixr 5 :^:
--   data Tree a =  Leaf a  |  Tree a :^: Tree a
--   </pre>
--   
--   the derived instance of <a>Show</a> is equivalent to
--   
--   <pre>
--   instance (Show a) =&gt; Show (Tree a) where
--   
--          showsPrec d (Leaf m) = showParen (d &gt; app_prec) $
--               showString "Leaf " . showsPrec (app_prec+1) m
--            where app_prec = 10
--   
--          showsPrec d (u :^: v) = showParen (d &gt; up_prec) $
--               showsPrec (up_prec+1) u .
--               showString " :^: "      .
--               showsPrec (up_prec+1) v
--            where up_prec = 5
--   </pre>
--   
--   Note that right-associativity of <tt>:^:</tt> is ignored. For example,
--   
--   <ul>
--   <li><tt><a>show</a> (Leaf 1 :^: Leaf 2 :^: Leaf 3)</tt> produces the
--   string <tt>"Leaf 1 :^: (Leaf 2 :^: Leaf 3)"</tt>.</li>
--   </ul>
class Show a where showsPrec _ x s = show x ++ s show x = shows x "" showList ls s = showList__ shows ls s
showsPrec :: Show a => Int -> a -> ShowS
show :: Show a => a -> String
showList :: Show a => [a] -> ShowS

-- | equivalent to <a>showsPrec</a> with a precedence of 0.
shows :: Show a => a -> ShowS

-- | utility function converting a <a>Char</a> to a show function that
--   simply prepends the character unchanged.
showChar :: Char -> ShowS

-- | utility function converting a <a>String</a> to a show function that
--   simply prepends the string unchanged.
showString :: String -> ShowS

-- | utility function that surrounds the inner show function with
--   parentheses when the <a>Bool</a> parameter is <a>True</a>.
showParen :: Bool -> ShowS -> ShowS

-- | Show a list (using square brackets and commas), given a function for
--   showing elements.
showListWith :: (a -> ShowS) -> [a] -> ShowS


-- | The <a>Functor</a>, <a>Monad</a> and <a>MonadPlus</a> classes, with
--   some useful operations on monads.
module Control.Monad

-- | The <a>Functor</a> class is used for types that can be mapped over.
--   Instances of <a>Functor</a> should satisfy the following laws:
--   
--   <pre>
--   fmap id  ==  id
--   fmap (f . g)  ==  fmap f . fmap g
--   </pre>
--   
--   The instances of <a>Functor</a> for lists, <a>Maybe</a> and <a>IO</a>
--   satisfy these laws.
class Functor f where <$ = fmap . const
fmap :: Functor f => (a -> b) -> f a -> f b

-- | The <a>Monad</a> class defines the basic operations over a
--   <i>monad</i>, a concept from a branch of mathematics known as
--   <i>category theory</i>. From the perspective of a Haskell programmer,
--   however, it is best to think of a monad as an <i>abstract datatype</i>
--   of actions. Haskell's <tt>do</tt> expressions provide a convenient
--   syntax for writing monadic expressions.
--   
--   Minimal complete definition: <a>&gt;&gt;=</a> and <a>return</a>.
--   
--   Instances of <a>Monad</a> should satisfy the following laws:
--   
--   <pre>
--   return a &gt;&gt;= k  ==  k a
--   m &gt;&gt;= return  ==  m
--   m &gt;&gt;= (\x -&gt; k x &gt;&gt;= h)  ==  (m &gt;&gt;= k) &gt;&gt;= h
--   </pre>
--   
--   Instances of both <a>Monad</a> and <a>Functor</a> should additionally
--   satisfy the law:
--   
--   <pre>
--   fmap f xs  ==  xs &gt;&gt;= return . f
--   </pre>
--   
--   The instances of <a>Monad</a> for lists, <a>Maybe</a> and <a>IO</a>
--   defined in the <a>Prelude</a> satisfy these laws.
class Monad m where m >> k = m >>= \ _ -> k fail s = error s
(>>=) :: Monad m => m a -> (a -> m b) -> m b
(>>) :: Monad m => m a -> m b -> m b
return :: Monad m => a -> m a
fail :: Monad m => String -> m a

-- | Monads that also support choice and failure.
class Monad m => MonadPlus m
mzero :: MonadPlus m => m a
mplus :: MonadPlus m => m a -> m a -> m a

-- | <tt><a>mapM</a> f</tt> is equivalent to <tt><a>sequence</a> .
--   <a>map</a> f</tt>.
mapM :: Monad m => (a -> m b) -> [a] -> m [b]

-- | <tt><a>mapM_</a> f</tt> is equivalent to <tt><a>sequence_</a> .
--   <a>map</a> f</tt>.
mapM_ :: Monad m => (a -> m b) -> [a] -> m ()

-- | <a>forM</a> is <a>mapM</a> with its arguments flipped
forM :: Monad m => [a] -> (a -> m b) -> m [b]

-- | <a>forM_</a> is <a>mapM_</a> with its arguments flipped
forM_ :: Monad m => [a] -> (a -> m b) -> m ()

-- | Evaluate each action in the sequence from left to right, and collect
--   the results.
sequence :: Monad m => [m a] -> m [a]

-- | Evaluate each action in the sequence from left to right, and ignore
--   the results.
sequence_ :: Monad m => [m a] -> m ()

-- | Same as <a>&gt;&gt;=</a>, but with the arguments interchanged.
(=<<) :: Monad m => (a -> m b) -> m a -> m b

-- | Left-to-right Kleisli composition of monads.
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)

-- | Right-to-left Kleisli composition of monads.
--   <tt>(<a>&gt;=&gt;</a>)</tt>, with the arguments flipped
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c)

-- | <tt><a>forever</a> act</tt> repeats the action infinitely.
forever :: Monad m => m a -> m b

-- | <tt><a>void</a> value</tt> discards or ignores the result of
--   evaluation, such as the return value of an <a>IO</a> action.
void :: Functor f => f a -> f ()

-- | The <a>join</a> function is the conventional monad join operator. It
--   is used to remove one level of monadic structure, projecting its bound
--   argument into the outer level.
join :: Monad m => m (m a) -> m a

-- | This generalizes the list-based <a>concat</a> function.
msum :: MonadPlus m => [m a] -> m a

-- | Direct <a>MonadPlus</a> equivalent of <a>filter</a>
--   <tt><a>filter</a></tt> = <tt>(mfilter:: (a -&gt; Bool) -&gt; [a] -&gt;
--   [a]</tt> applicable to any <a>MonadPlus</a>, for example <tt>mfilter
--   odd (Just 1) == Just 1</tt> <tt>mfilter odd (Just 2) == Nothing</tt>
mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a

-- | This generalizes the list-based <a>filter</a> function.
filterM :: Monad m => (a -> m Bool) -> [a] -> m [a]

-- | The <a>mapAndUnzipM</a> function maps its first argument over a list,
--   returning the result as a pair of lists. This function is mainly used
--   with complicated data structures or a state-transforming monad.
mapAndUnzipM :: Monad m => (a -> m (b, c)) -> [a] -> m ([b], [c])

-- | The <a>zipWithM</a> function generalizes <a>zipWith</a> to arbitrary
--   monads.
zipWithM :: Monad m => (a -> b -> m c) -> [a] -> [b] -> m [c]

-- | <a>zipWithM_</a> is the extension of <a>zipWithM</a> which ignores the
--   final result.
zipWithM_ :: Monad m => (a -> b -> m c) -> [a] -> [b] -> m ()

-- | The <a>foldM</a> function is analogous to <a>foldl</a>, except that
--   its result is encapsulated in a monad. Note that <a>foldM</a> works
--   from left-to-right over the list arguments. This could be an issue
--   where <tt>(<a>&gt;&gt;</a>)</tt> and the `folded function' are not
--   commutative.
--   
--   <pre>
--   foldM f a1 [x1, x2, ..., xm]
--   </pre>
--   
--   ==
--   
--   <pre>
--   do
--     a2 &lt;- f a1 x1
--     a3 &lt;- f a2 x2
--     ...
--     f am xm
--   </pre>
--   
--   If right-to-left evaluation is required, the input list should be
--   reversed.
foldM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a

-- | Like <a>foldM</a>, but discards the result.
foldM_ :: Monad m => (a -> b -> m a) -> a -> [b] -> m ()

-- | <tt><a>replicateM</a> n act</tt> performs the action <tt>n</tt> times,
--   gathering the results.
replicateM :: Monad m => Int -> m a -> m [a]

-- | Like <a>replicateM</a>, but discards the result.
replicateM_ :: Monad m => Int -> m a -> m ()

-- | <tt><a>guard</a> b</tt> is <tt><a>return</a> ()</tt> if <tt>b</tt> is
--   <a>True</a>, and <a>mzero</a> if <tt>b</tt> is <a>False</a>.
guard :: MonadPlus m => Bool -> m ()

-- | Conditional execution of monadic expressions. For example,
--   
--   <pre>
--   when debug (putStr "Debugging\n")
--   </pre>
--   
--   will output the string <tt>Debugging\n</tt> if the Boolean value
--   <tt>debug</tt> is <a>True</a>, and otherwise do nothing.
when :: Monad m => Bool -> m () -> m ()

-- | The reverse of <a>when</a>.
unless :: Monad m => Bool -> m () -> m ()

-- | Promote a function to a monad.
liftM :: Monad m => (a1 -> r) -> m a1 -> m r

-- | Promote a function to a monad, scanning the monadic arguments from
--   left to right. For example,
--   
--   <pre>
--   liftM2 (+) [0,1] [0,2] = [0,2,1,3]
--   liftM2 (+) (Just 1) Nothing = Nothing
--   </pre>
liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r

-- | Promote a function to a monad, scanning the monadic arguments from
--   left to right (cf. <a>liftM2</a>).
liftM3 :: Monad m => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r

-- | Promote a function to a monad, scanning the monadic arguments from
--   left to right (cf. <a>liftM2</a>).
liftM4 :: Monad m => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r

-- | Promote a function to a monad, scanning the monadic arguments from
--   left to right (cf. <a>liftM2</a>).
liftM5 :: Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r

-- | In many situations, the <a>liftM</a> operations can be replaced by
--   uses of <a>ap</a>, which promotes function application.
--   
--   <pre>
--   return f `ap` x1 `ap` ... `ap` xn
--   </pre>
--   
--   is equivalent to
--   
--   <pre>
--   liftMn f x1 x2 ... xn
--   </pre>
ap :: Monad m => m (a -> b) -> m a -> m b
instance MonadPlus Maybe
instance MonadPlus []


-- | Marshalling support. Unsafe API.
module Foreign.Marshal.Unsafe

-- | Sometimes an external entity is a pure function, except that it passes
--   arguments and/or results via pointers. The function
--   <tt>unsafeLocalState</tt> permits the packaging of such entities as
--   pure functions.
--   
--   The only IO operations allowed in the IO action passed to
--   <tt>unsafeLocalState</tt> are (a) local allocation (<tt>alloca</tt>,
--   <tt>allocaBytes</tt> and derived operations such as <tt>withArray</tt>
--   and <tt>withCString</tt>), and (b) pointer operations
--   (<tt>Foreign.Storable</tt> and <tt>Foreign.Ptr</tt>) on the pointers
--   to local storage, and (c) foreign functions whose only observable
--   effect is to read and/or write the locally allocated memory. Passing
--   an IO operation that does not obey these rules results in undefined
--   behaviour.
--   
--   It is expected that this operation will be replaced in a future
--   revision of Haskell.
unsafeLocalState :: IO a -> a


-- | This module defines bitwise operations for signed and unsigned
--   integers. Instances of the class <a>Bits</a> for the <a>Int</a> and
--   <a>Integer</a> types are available from this module, and instances for
--   explicitly sized integral types are available from the <a>Data.Int</a>
--   and <a>Data.Word</a> modules.
module Data.Bits

-- | The <a>Bits</a> class defines bitwise operations over integral types.
--   
--   <ul>
--   <li>Bits are numbered from 0 with bit 0 being the least significant
--   bit.</li>
--   </ul>
--   
--   Minimal complete definition: <a>.&amp;.</a>, <a>.|.</a>, <a>xor</a>,
--   <a>complement</a>, (<a>shift</a> or (<a>shiftL</a> and
--   <a>shiftR</a>)), (<a>rotate</a> or (<a>rotateL</a> and
--   <a>rotateR</a>)), <a>bitSize</a>, <a>isSigned</a>, <a>testBit</a>,
--   <a>bit</a>, and <a>popCount</a>. The latter three can be implemented
--   using <a>testBitDefault</a>, 'bitDefault, and <a>popCountDefault</a>,
--   if <tt>a</tt> is also an instance of <a>Num</a>.
class Eq a => Bits a where x shift i | i < 0 = x `shiftR` (- i) | i > 0 = x `shiftL` i | otherwise = x x rotate i | i < 0 = x `rotateR` (- i) | i > 0 = x `rotateL` i | otherwise = x x setBit i = x .|. bit i x clearBit i = x .&. complement (bit i) x complementBit i = x `xor` bit i x shiftL i = x `shift` i x unsafeShiftL i = x `shiftL` i x shiftR i = x `shift` (- i) x unsafeShiftR i = x `shiftR` i x rotateL i = x `rotate` i x rotateR i = x `rotate` (- i)
(.&.) :: Bits a => a -> a -> a
(.|.) :: Bits a => a -> a -> a
xor :: Bits a => a -> a -> a
complement :: Bits a => a -> a
shift :: Bits a => a -> Int -> a
rotate :: Bits a => a -> Int -> a
bit :: Bits a => Int -> a
setBit :: Bits a => a -> Int -> a
clearBit :: Bits a => a -> Int -> a
complementBit :: Bits a => a -> Int -> a
testBit :: Bits a => a -> Int -> Bool
bitSize :: Bits a => a -> Int
isSigned :: Bits a => a -> Bool
shiftL :: Bits a => a -> Int -> a
unsafeShiftL :: Bits a => a -> Int -> a
shiftR :: Bits a => a -> Int -> a
unsafeShiftR :: Bits a => a -> Int -> a
rotateL :: Bits a => a -> Int -> a
rotateR :: Bits a => a -> Int -> a
popCount :: Bits a => a -> Int

-- | Default implementation for <a>bit</a>.
--   
--   Note that: <tt>bitDefault i = 1 <a>shiftL</a> i</tt>
bitDefault :: (Bits a, Num a) => Int -> a

-- | Default implementation for <a>testBit</a>.
--   
--   Note that: <tt>testBitDefault x i = (x .&amp;. bit i) /= 0</tt>
testBitDefault :: (Bits a, Num a) => a -> Int -> Bool

-- | Default implementation for <a>popCount</a>.
--   
--   This implementation is intentionally naive. Instances are expected to
--   provide an optimized implementation for their size.
popCountDefault :: (Bits a, Num a) => a -> Int
instance Bits Integer
instance Bits Word
instance Bits Int


-- | Orderings
module Data.Ord

-- | The <a>Ord</a> class is used for totally ordered datatypes.
--   
--   Instances of <a>Ord</a> can be derived for any user-defined datatype
--   whose constituent types are in <a>Ord</a>. The declared order of the
--   constructors in the data declaration determines the ordering in
--   derived <a>Ord</a> instances. The <a>Ordering</a> datatype allows a
--   single comparison to determine the precise ordering of two objects.
--   
--   Minimal complete definition: either <a>compare</a> or <a>&lt;=</a>.
--   Using <a>compare</a> can be more efficient for complex types.
class Eq a => Ord a
compare :: Ord a => a -> a -> Ordering
(<) :: Ord a => a -> a -> Bool
(>=) :: Ord a => a -> a -> Bool
(>) :: Ord a => a -> a -> Bool
(<=) :: Ord a => a -> a -> Bool
max :: Ord a => a -> a -> a
min :: Ord a => a -> a -> a
data Ordering :: *
LT :: Ordering
EQ :: Ordering
GT :: Ordering

-- | The <a>Down</a> type allows you to reverse sort order conveniently. A
--   value of type <tt><a>Down</a> a</tt> contains a value of type
--   <tt>a</tt> (represented as <tt><a>Down</a> a</tt>). If <tt>a</tt> has
--   an <tt><a>Ord</a></tt> instance associated with it then comparing two
--   values thus wrapped will give you the opposite of their normal sort
--   order. This is particularly useful when sorting in generalised list
--   comprehensions, as in: <tt>then sortWith by <a>Down</a> x</tt>
newtype Down a
Down :: a -> Down a

-- | <pre>
--   comparing p x y = compare (p x) (p y)
--   </pre>
--   
--   Useful combinator for use in conjunction with the <tt>xxxBy</tt>
--   family of functions from <a>Data.List</a>, for example:
--   
--   <pre>
--   ... sortBy (comparing fst) ...
--   </pre>
comparing :: Ord a => (b -> a) -> b -> b -> Ordering
instance Eq a => Eq (Down a)
instance Ord a => Ord (Down a)


-- | This is a library of parser combinators, originally written by Koen
--   Claessen. It parses all alternatives in parallel, so it never keeps
--   hold of the beginning of the input string, a common source of space
--   leaks with other parsers. The '(+++)' choice combinator is genuinely
--   commutative; it makes no difference which branch is "shorter".
module Text.ParserCombinators.ReadP
data ReadP a

-- | Consumes and returns the next character. Fails if there is no input
--   left.
get :: ReadP Char

-- | Look-ahead: returns the part of the input that is left, without
--   consuming it.
look :: ReadP String

-- | Symmetric choice.
(+++) :: ReadP a -> ReadP a -> ReadP a

-- | Local, exclusive, left-biased choice: If left parser locally produces
--   any result at all, then right parser is not used.
(<++) :: ReadP a -> ReadP a -> ReadP a

-- | Transforms a parser into one that does the same, but in addition
--   returns the exact characters read. IMPORTANT NOTE: <a>gather</a> gives
--   a runtime error if its first argument is built using any occurrences
--   of readS_to_P.
gather :: ReadP a -> ReadP (String, a)

-- | Always fails.
pfail :: ReadP a

-- | Succeeds iff we are at the end of input
eof :: ReadP ()

-- | Consumes and returns the next character, if it satisfies the specified
--   predicate.
satisfy :: (Char -> Bool) -> ReadP Char

-- | Parses and returns the specified character.
char :: Char -> ReadP Char

-- | Parses and returns the specified string.
string :: String -> ReadP String

-- | Parses the first zero or more characters satisfying the predicate.
--   Always succeds, exactly once having consumed all the characters Hence
--   NOT the same as (many (satisfy p))
munch :: (Char -> Bool) -> ReadP String

-- | Parses the first one or more characters satisfying the predicate.
--   Fails if none, else succeeds exactly once having consumed all the
--   characters Hence NOT the same as (many1 (satisfy p))
munch1 :: (Char -> Bool) -> ReadP String

-- | Skips all whitespace.
skipSpaces :: ReadP ()

-- | Combines all parsers in the specified list.
choice :: [ReadP a] -> ReadP a

-- | <tt>count n p</tt> parses <tt>n</tt> occurrences of <tt>p</tt> in
--   sequence. A list of results is returned.
count :: Int -> ReadP a -> ReadP [a]

-- | <tt>between open close p</tt> parses <tt>open</tt>, followed by
--   <tt>p</tt> and finally <tt>close</tt>. Only the value of <tt>p</tt> is
--   returned.
between :: ReadP open -> ReadP close -> ReadP a -> ReadP a

-- | <tt>option x p</tt> will either parse <tt>p</tt> or return <tt>x</tt>
--   without consuming any input.
option :: a -> ReadP a -> ReadP a

-- | <tt>optional p</tt> optionally parses <tt>p</tt> and always returns
--   <tt>()</tt>.
optional :: ReadP a -> ReadP ()

-- | Parses zero or more occurrences of the given parser.
many :: ReadP a -> ReadP [a]

-- | Parses one or more occurrences of the given parser.
many1 :: ReadP a -> ReadP [a]

-- | Like <a>many</a>, but discards the result.
skipMany :: ReadP a -> ReadP ()

-- | Like <a>many1</a>, but discards the result.
skipMany1 :: ReadP a -> ReadP ()

-- | <tt>sepBy p sep</tt> parses zero or more occurrences of <tt>p</tt>,
--   separated by <tt>sep</tt>. Returns a list of values returned by
--   <tt>p</tt>.
sepBy :: ReadP a -> ReadP sep -> ReadP [a]

-- | <tt>sepBy1 p sep</tt> parses one or more occurrences of <tt>p</tt>,
--   separated by <tt>sep</tt>. Returns a list of values returned by
--   <tt>p</tt>.
sepBy1 :: ReadP a -> ReadP sep -> ReadP [a]

-- | <tt>endBy p sep</tt> parses zero or more occurrences of <tt>p</tt>,
--   separated and ended by <tt>sep</tt>.
endBy :: ReadP a -> ReadP sep -> ReadP [a]

-- | <tt>endBy p sep</tt> parses one or more occurrences of <tt>p</tt>,
--   separated and ended by <tt>sep</tt>.
endBy1 :: ReadP a -> ReadP sep -> ReadP [a]

-- | <tt>chainr p op x</tt> parses zero or more occurrences of <tt>p</tt>,
--   separated by <tt>op</tt>. Returns a value produced by a <i>right</i>
--   associative application of all functions returned by <tt>op</tt>. If
--   there are no occurrences of <tt>p</tt>, <tt>x</tt> is returned.
chainr :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a

-- | <tt>chainl p op x</tt> parses zero or more occurrences of <tt>p</tt>,
--   separated by <tt>op</tt>. Returns a value produced by a <i>left</i>
--   associative application of all functions returned by <tt>op</tt>. If
--   there are no occurrences of <tt>p</tt>, <tt>x</tt> is returned.
chainl :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a

-- | Like <a>chainl</a>, but parses one or more occurrences of <tt>p</tt>.
chainl1 :: ReadP a -> ReadP (a -> a -> a) -> ReadP a

-- | Like <a>chainr</a>, but parses one or more occurrences of <tt>p</tt>.
chainr1 :: ReadP a -> ReadP (a -> a -> a) -> ReadP a

-- | <tt>manyTill p end</tt> parses zero or more occurrences of <tt>p</tt>,
--   until <tt>end</tt> succeeds. Returns a list of values returned by
--   <tt>p</tt>.
manyTill :: ReadP a -> ReadP end -> ReadP [a]

-- | A parser for a type <tt>a</tt>, represented as a function that takes a
--   <a>String</a> and returns a list of possible parses as
--   <tt>(a,<a>String</a>)</tt> pairs.
--   
--   Note that this kind of backtracking parser is very inefficient;
--   reading a large structure may be quite slow (cf <a>ReadP</a>).
type ReadS a = String -> [(a, String)]

-- | Converts a parser into a Haskell ReadS-style function. This is the
--   main way in which you can "run" a <a>ReadP</a> parser: the expanded
--   type is <tt> readP_to_S :: ReadP a -&gt; String -&gt; [(a,String)]
--   </tt>
readP_to_S :: ReadP a -> ReadS a

-- | Converts a Haskell ReadS-style function into a parser. Warning: This
--   introduces local backtracking in the resulting parser, and therefore a
--   possible inefficiency.
readS_to_P :: ReadS a -> ReadP a
instance MonadPlus ReadP
instance Monad ReadP
instance Functor ReadP
instance MonadPlus P
instance Monad P


-- | The cut-down Haskell lexer, used by Text.Read
module Text.Read.Lex

-- | Haskell lexemes.
data Lexeme

-- | Character literal
Char :: Char -> Lexeme

-- | String literal, with escapes interpreted
String :: String -> Lexeme

-- | Punctuation or reserved symbol, e.g. <tt>(</tt>, <tt>::</tt>
Punc :: String -> Lexeme

-- | Haskell identifier, e.g. <tt>foo</tt>, <tt>Baz</tt>
Ident :: String -> Lexeme

-- | Haskell symbol, e.g. <tt>&gt;&gt;</tt>, <tt>:%</tt>
Symbol :: String -> Lexeme
Number :: Number -> Lexeme
EOF :: Lexeme
numberToInteger :: Number -> Maybe Integer
numberToRational :: Number -> Rational
numberToRangedRational :: (Int, Int) -> Number -> Maybe Rational
lex :: ReadP Lexeme

-- | Haskell lexer: returns the lexed string, rather than the lexeme
hsLex :: ReadP String
lexChar :: ReadP Char
readIntP :: Num a => a -> (Char -> Bool) -> (Char -> Int) -> ReadP a
readOctP :: (Eq a, Num a) => ReadP a
readDecP :: (Eq a, Num a) => ReadP a
readHexP :: (Eq a, Num a) => ReadP a
instance Eq Number
instance Show Number
instance Eq Lexeme
instance Show Lexeme


-- | This library defines parser combinators for precedence parsing.
module Text.ParserCombinators.ReadPrec
data ReadPrec a
type Prec = Int
minPrec :: Prec

-- | Lift a precedence-insensitive <a>ReadP</a> to a <a>ReadPrec</a>.
lift :: ReadP a -> ReadPrec a

-- | <tt>(prec n p)</tt> checks whether the precedence context is less than
--   or equal to <tt>n</tt>, and
--   
--   <ul>
--   <li>if not, fails</li>
--   <li>if so, parses <tt>p</tt> in context <tt>n</tt>.</li>
--   </ul>
prec :: Prec -> ReadPrec a -> ReadPrec a

-- | Increases the precedence context by one.
step :: ReadPrec a -> ReadPrec a

-- | Resets the precedence context to zero.
reset :: ReadPrec a -> ReadPrec a

-- | Consumes and returns the next character. Fails if there is no input
--   left.
get :: ReadPrec Char

-- | Look-ahead: returns the part of the input that is left, without
--   consuming it.
look :: ReadPrec String

-- | Symmetric choice.
(+++) :: ReadPrec a -> ReadPrec a -> ReadPrec a

-- | Local, exclusive, left-biased choice: If left parser locally produces
--   any result at all, then right parser is not used.
(<++) :: ReadPrec a -> ReadPrec a -> ReadPrec a

-- | Always fails.
pfail :: ReadPrec a

-- | Combines all parsers in the specified list.
choice :: [ReadPrec a] -> ReadPrec a
readPrec_to_P :: ReadPrec a -> (Int -> ReadP a)
readP_to_Prec :: (Int -> ReadP a) -> ReadPrec a
readPrec_to_S :: ReadPrec a -> (Int -> ReadS a)
readS_to_Prec :: (Int -> ReadS a) -> ReadPrec a
instance MonadPlus ReadPrec
instance Monad ReadPrec
instance Functor ReadPrec


-- | Signed integer types
module Data.Int

-- | A fixed-precision integer type with at least the range <tt>[-2^29 ..
--   2^29-1]</tt>. The exact range for a given implementation can be
--   determined by using <a>minBound</a> and <a>maxBound</a> from the
--   <a>Bounded</a> class.
data Int :: *

-- | 8-bit signed integer type
data Int8

-- | 16-bit signed integer type
data Int16

-- | 32-bit signed integer type
data Int32

-- | 64-bit signed integer type
data Int64


-- | Unsigned integer types.
module Data.Word

-- | A <a>Word</a> is an unsigned integral type, with the same size as
--   <a>Int</a>.
data Word :: *

-- | 8-bit unsigned integer type
data Word8

-- | 16-bit unsigned integer type
data Word16

-- | 32-bit unsigned integer type
data Word32

-- | 64-bit unsigned integer type
data Word64

module GHC.Fingerprint.Type
data Fingerprint
Fingerprint :: {-# UNPACK #-} !Word64 -> {-# UNPACK #-} !Word64 -> Fingerprint
instance Eq Fingerprint
instance Ord Fingerprint


-- | Odds and ends, mostly functions for reading and showing
--   <a>RealFloat</a>-like kind of values.
module Numeric

-- | Converts a possibly-negative <a>Real</a> value to a string.
showSigned :: Real a => (a -> ShowS) -> Int -> a -> ShowS

-- | Shows a <i>non-negative</i> <a>Integral</a> number using the base
--   specified by the first argument, and the character representation
--   specified by the second.
showIntAtBase :: (Integral a, Show a) => a -> (Int -> Char) -> a -> ShowS

-- | Show <i>non-negative</i> <a>Integral</a> numbers in base 10.
showInt :: Integral a => a -> ShowS

-- | Show <i>non-negative</i> <a>Integral</a> numbers in base 16.
showHex :: (Integral a, Show a) => a -> ShowS

-- | Show <i>non-negative</i> <a>Integral</a> numbers in base 8.
showOct :: (Integral a, Show a) => a -> ShowS

-- | Show a signed <a>RealFloat</a> value using scientific (exponential)
--   notation (e.g. <tt>2.45e2</tt>, <tt>1.5e-3</tt>).
--   
--   In the call <tt><a>showEFloat</a> digs val</tt>, if <tt>digs</tt> is
--   <a>Nothing</a>, the value is shown to full precision; if <tt>digs</tt>
--   is <tt><a>Just</a> d</tt>, then at most <tt>d</tt> digits after the
--   decimal point are shown.
showEFloat :: RealFloat a => Maybe Int -> a -> ShowS

-- | Show a signed <a>RealFloat</a> value using standard decimal notation
--   (e.g. <tt>245000</tt>, <tt>0.0015</tt>).
--   
--   In the call <tt><a>showFFloat</a> digs val</tt>, if <tt>digs</tt> is
--   <a>Nothing</a>, the value is shown to full precision; if <tt>digs</tt>
--   is <tt><a>Just</a> d</tt>, then at most <tt>d</tt> digits after the
--   decimal point are shown.
showFFloat :: RealFloat a => Maybe Int -> a -> ShowS

-- | Show a signed <a>RealFloat</a> value using standard decimal notation
--   for arguments whose absolute value lies between <tt>0.1</tt> and
--   <tt>9,999,999</tt>, and scientific notation otherwise.
--   
--   In the call <tt><a>showGFloat</a> digs val</tt>, if <tt>digs</tt> is
--   <a>Nothing</a>, the value is shown to full precision; if <tt>digs</tt>
--   is <tt><a>Just</a> d</tt>, then at most <tt>d</tt> digits after the
--   decimal point are shown.
showGFloat :: RealFloat a => Maybe Int -> a -> ShowS

-- | Show a signed <a>RealFloat</a> value to full precision using standard
--   decimal notation for arguments whose absolute value lies between
--   <tt>0.1</tt> and <tt>9,999,999</tt>, and scientific notation
--   otherwise.
showFloat :: RealFloat a => a -> ShowS

-- | <a>floatToDigits</a> takes a base and a non-negative <a>RealFloat</a>
--   number, and returns a list of digits and an exponent. In particular,
--   if <tt>x&gt;=0</tt>, and
--   
--   <pre>
--   floatToDigits base x = ([d1,d2,...,dn], e)
--   </pre>
--   
--   then
--   
--   <ol>
--   <li><pre>n &gt;= 1</pre></li>
--   <li><pre>x = 0.d1d2...dn * (base**e)</pre></li>
--   <li><pre>0 &lt;= di &lt;= base-1</pre></li>
--   </ol>
floatToDigits :: RealFloat a => Integer -> a -> ([Int], Int)

-- | Reads a <i>signed</i> <a>Real</a> value, given a reader for an
--   unsigned value.
readSigned :: Real a => ReadS a -> ReadS a

-- | Reads an <i>unsigned</i> <a>Integral</a> value in an arbitrary base.
readInt :: Num a => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a

-- | Read an unsigned number in decimal notation.
readDec :: (Eq a, Num a) => ReadS a

-- | Read an unsigned number in octal notation.
readOct :: (Eq a, Num a) => ReadS a

-- | Read an unsigned number in hexadecimal notation. Both upper or lower
--   case letters are allowed.
readHex :: (Eq a, Num a) => ReadS a

-- | Reads an <i>unsigned</i> <a>RealFrac</a> value, expressed in decimal
--   scientific notation.
readFloat :: RealFrac a => ReadS a

-- | Reads a non-empty string of decimal digits.
lexDigits :: ReadS String

-- | Converts a <a>Rational</a> value into any type in class
--   <a>RealFloat</a>.
fromRat :: RealFloat a => Rational -> a


-- | This module is part of the Foreign Function Interface (FFI) and will
--   usually be imported via the module <a>Foreign</a>.
module Foreign.StablePtr

-- | A <i>stable pointer</i> is a reference to a Haskell expression that is
--   guaranteed not to be affected by garbage collection, i.e., it will
--   neither be deallocated nor will the value of the stable pointer itself
--   change during garbage collection (ordinary references may be relocated
--   during garbage collection). Consequently, stable pointers can be
--   passed to foreign code, which can treat it as an opaque reference to a
--   Haskell value.
--   
--   A value of type <tt>StablePtr a</tt> is a stable pointer to a Haskell
--   expression of type <tt>a</tt>.
data StablePtr a

-- | Create a stable pointer referring to the given Haskell value.
newStablePtr :: a -> IO (StablePtr a)

-- | Obtain the Haskell value referenced by a stable pointer, i.e., the
--   same value that was passed to the corresponding call to
--   <tt>makeStablePtr</tt>. If the argument to <a>deRefStablePtr</a> has
--   already been freed using <a>freeStablePtr</a>, the behaviour of
--   <a>deRefStablePtr</a> is undefined.
deRefStablePtr :: StablePtr a -> IO a

-- | Dissolve the association between the stable pointer and the Haskell
--   value. Afterwards, if the stable pointer is passed to
--   <a>deRefStablePtr</a> or <a>freeStablePtr</a>, the behaviour is
--   undefined. However, the stable pointer may still be passed to
--   <a>castStablePtrToPtr</a>, but the <tt><a>Ptr</a> ()</tt> value
--   returned by <a>castStablePtrToPtr</a>, in this case, is undefined (in
--   particular, it may be <a>nullPtr</a>). Nevertheless, the call to
--   <a>castStablePtrToPtr</a> is guaranteed not to diverge.
freeStablePtr :: StablePtr a -> IO ()

-- | Coerce a stable pointer to an address. No guarantees are made about
--   the resulting value, except that the original stable pointer can be
--   recovered by <a>castPtrToStablePtr</a>. In particular, the address may
--   not refer to an accessible memory location and any attempt to pass it
--   to the member functions of the class <a>Storable</a> leads to
--   undefined behaviour.
castStablePtrToPtr :: StablePtr a -> Ptr ()

-- | The inverse of <a>castStablePtrToPtr</a>, i.e., we have the identity
--   
--   <pre>
--   sp == castPtrToStablePtr (castStablePtrToPtr sp)
--   </pre>
--   
--   for any stable pointer <tt>sp</tt> on which <a>freeStablePtr</a> has
--   not been executed yet. Moreover, <a>castPtrToStablePtr</a> may only be
--   applied to pointers that have been produced by
--   <a>castStablePtrToPtr</a>.
castPtrToStablePtr :: Ptr () -> StablePtr a


-- | Type classes for I/O providers.
module GHC.IO.Device

-- | A low-level I/O provider where the data is bytes in memory.
class RawIO a
read :: RawIO a => a -> Ptr Word8 -> Int -> IO Int
readNonBlocking :: RawIO a => a -> Ptr Word8 -> Int -> IO (Maybe Int)
write :: RawIO a => a -> Ptr Word8 -> Int -> IO ()
writeNonBlocking :: RawIO a => a -> Ptr Word8 -> Int -> IO Int

-- | I/O operations required for implementing a <tt>Handle</tt>.
class IODevice a where isTerminal _ = return False isSeekable _ = return False seek _ _ _ = ioe_unsupportedOperation tell _ = ioe_unsupportedOperation getSize _ = ioe_unsupportedOperation setSize _ _ = ioe_unsupportedOperation setEcho _ _ = ioe_unsupportedOperation getEcho _ = ioe_unsupportedOperation setRaw _ _ = ioe_unsupportedOperation dup _ = ioe_unsupportedOperation dup2 _ _ = ioe_unsupportedOperation
ready :: IODevice a => a -> Bool -> Int -> IO Bool
close :: IODevice a => a -> IO ()
isTerminal :: IODevice a => a -> IO Bool
isSeekable :: IODevice a => a -> IO Bool
seek :: IODevice a => a -> SeekMode -> Integer -> IO ()
tell :: IODevice a => a -> IO Integer
getSize :: IODevice a => a -> IO Integer
setSize :: IODevice a => a -> Integer -> IO ()
setEcho :: IODevice a => a -> Bool -> IO ()
getEcho :: IODevice a => a -> IO Bool
setRaw :: IODevice a => a -> Bool -> IO ()
devType :: IODevice a => a -> IO IODeviceType
dup :: IODevice a => a -> IO a
dup2 :: IODevice a => a -> a -> IO a

-- | Type of a device that can be used to back a <a>Handle</a> (see also
--   <a>mkFileHandle</a>). The standard libraries provide creation of
--   <a>Handle</a>s via Posix file operations with file descriptors (see
--   <a>mkHandleFromFD</a>) with FD being the underlying <a>IODevice</a>
--   instance.
--   
--   Users may provide custom instances of <a>IODevice</a> which are
--   expected to conform the following rules:
data IODeviceType

-- | The standard libraries do not have direct support for this device
--   type, but a user implementation is expected to provide a list of file
--   names in the directory, in any order, separated by <tt>'\0'</tt>
--   characters, excluding the <tt><a>.</a></tt> and <tt><a>..</a></tt>
--   names. See also <a>getDirectoryContents</a>. Seek operations are not
--   supported on directories (other than to the zero position).
Directory :: IODeviceType

-- | A duplex communications channel (results in creation of a duplex
--   <a>Handle</a>). The standard libraries use this device type when
--   creating <a>Handle</a>s for open sockets.
Stream :: IODeviceType

-- | A file that may be read or written, and also may be seekable.
RegularFile :: IODeviceType

-- | A <a>raw</a> (disk) device which supports block binary read and write
--   operations and may be seekable only to positions of certain
--   granularity (block- aligned).
RawDevice :: IODeviceType

-- | A mode that determines the effect of <tt>hSeek</tt> <tt>hdl mode
--   i</tt>.
data SeekMode

-- | the position of <tt>hdl</tt> is set to <tt>i</tt>.
AbsoluteSeek :: SeekMode

-- | the position of <tt>hdl</tt> is set to offset <tt>i</tt> from the
--   current position.
RelativeSeek :: SeekMode

-- | the position of <tt>hdl</tt> is set to offset <tt>i</tt> from the end
--   of the file.
SeekFromEnd :: SeekMode
instance Eq IODeviceType
instance Eq SeekMode
instance Ord SeekMode
instance Ix SeekMode
instance Enum SeekMode
instance Read SeekMode
instance Show SeekMode


-- | The module <a>Foreign.Storable</a> provides most elementary support
--   for marshalling and is part of the language-independent portion of the
--   Foreign Function Interface (FFI), and will normally be imported via
--   the <a>Foreign</a> module.
module Foreign.Storable

-- | 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 <tt><a>Ptr</a>
--   a</tt>, for some <tt>a</tt> which is an instance of class
--   <a>Storable</a>. The type argument to <a>Ptr</a> 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 <a>Storable</a> facilitates this manipulation
--   on all types for which it is instantiated, which are the standard
--   basic types of Haskell, the fixed size <tt>Int</tt> types
--   (<a>Int8</a>, <a>Int16</a>, <a>Int32</a>, <a>Int64</a>), the fixed
--   size <tt>Word</tt> types (<a>Word8</a>, <a>Word16</a>, <a>Word32</a>,
--   <a>Word64</a>), <a>StablePtr</a>, all types from
--   <a>Foreign.C.Types</a>, as well as <a>Ptr</a>.
--   
--   Minimal complete definition: <a>sizeOf</a>, <a>alignment</a>, one of
--   <a>peek</a>, <a>peekElemOff</a> and <a>peekByteOff</a>, and one of
--   <a>poke</a>, <a>pokeElemOff</a> and <a>pokeByteOff</a>.
class Storable a where peekElemOff = peekElemOff_ undefined where peekElemOff_ :: a -> Ptr a -> Int -> IO a peekElemOff_ undef ptr off = peekByteOff ptr (off * sizeOf undef) pokeElemOff ptr off val = pokeByteOff ptr (off * sizeOf val) val peekByteOff ptr off = peek (ptr `plusPtr` off) pokeByteOff ptr off = poke (ptr `plusPtr` off) peek ptr = peekElemOff ptr 0 poke ptr = pokeElemOff ptr 0
sizeOf :: Storable a => a -> Int
alignment :: Storable a => a -> Int
peekElemOff :: Storable a => Ptr a -> Int -> IO a
pokeElemOff :: Storable a => Ptr a -> Int -> a -> IO ()
peekByteOff :: Storable a => Ptr b -> Int -> IO a
pokeByteOff :: Storable a => Ptr b -> Int -> a -> IO ()
peek :: Storable a => Ptr a -> IO a
poke :: Storable a => Ptr a -> a -> IO ()
instance Storable Fingerprint
instance Storable Int64
instance Storable Int32
instance Storable Int16
instance Storable Int8
instance Storable Word64
instance Storable Word32
instance Storable Word16
instance Storable Word8
instance Storable Double
instance Storable Float
instance Storable (StablePtr a)
instance Storable (FunPtr a)
instance Storable (Ptr a)
instance Storable Word
instance Storable Int
instance Storable Char
instance Storable Bool


-- | Mapping of C types to corresponding Haskell types.
module Foreign.C.Types

-- | Haskell type representing the C <tt>char</tt> type.
newtype CChar
CChar :: Int8 -> CChar

-- | Haskell type representing the C <tt>signed char</tt> type.
newtype CSChar
CSChar :: Int8 -> CSChar

-- | Haskell type representing the C <tt>unsigned char</tt> type.
newtype CUChar
CUChar :: Word8 -> CUChar

-- | Haskell type representing the C <tt>short</tt> type.
newtype CShort
CShort :: Int16 -> CShort

-- | Haskell type representing the C <tt>unsigned short</tt> type.
newtype CUShort
CUShort :: Word16 -> CUShort

-- | Haskell type representing the C <tt>int</tt> type.
newtype CInt
CInt :: Int32 -> CInt

-- | Haskell type representing the C <tt>unsigned int</tt> type.
newtype CUInt
CUInt :: Word32 -> CUInt

-- | Haskell type representing the C <tt>long</tt> type.
newtype CLong
CLong :: Int32 -> CLong

-- | Haskell type representing the C <tt>unsigned long</tt> type.
newtype CULong
CULong :: Word32 -> CULong

-- | Haskell type representing the C <tt>ptrdiff_t</tt> type.
newtype CPtrdiff
CPtrdiff :: Int32 -> CPtrdiff

-- | Haskell type representing the C <tt>size_t</tt> type.
newtype CSize
CSize :: Word32 -> CSize

-- | Haskell type representing the C <tt>wchar_t</tt> type.
newtype CWchar
CWchar :: Int32 -> CWchar

-- | Haskell type representing the C <tt>sig_atomic_t</tt> type.
newtype CSigAtomic
CSigAtomic :: Int32 -> CSigAtomic

-- | Haskell type representing the C <tt>long long</tt> type.
newtype CLLong
CLLong :: Int64 -> CLLong

-- | Haskell type representing the C <tt>unsigned long long</tt> type.
newtype CULLong
CULLong :: Word64 -> CULLong
newtype CIntPtr
CIntPtr :: Int32 -> CIntPtr
newtype CUIntPtr
CUIntPtr :: Word32 -> CUIntPtr
newtype CIntMax
CIntMax :: Int64 -> CIntMax
newtype CUIntMax
CUIntMax :: Word64 -> CUIntMax

-- | Haskell type representing the C <tt>clock_t</tt> type.
newtype CClock
CClock :: Int32 -> CClock

-- | Haskell type representing the C <tt>time_t</tt> type.
newtype CTime
CTime :: Int32 -> CTime

-- | Haskell type representing the C <tt>useconds_t</tt> type.
newtype CUSeconds
CUSeconds :: Word32 -> CUSeconds

-- | Haskell type representing the C <tt>suseconds_t</tt> type.
newtype CSUSeconds
CSUSeconds :: Int32 -> CSUSeconds

-- | Haskell type representing the C <tt>float</tt> type.
newtype CFloat
CFloat :: Float -> CFloat

-- | Haskell type representing the C <tt>double</tt> type.
newtype CDouble
CDouble :: Double -> CDouble

-- | Haskell type representing the C <tt>FILE</tt> type.
data CFile

-- | Haskell type representing the C <tt>fpos_t</tt> type.
data CFpos

-- | Haskell type representing the C <tt>jmp_buf</tt> type.
data CJmpBuf
instance Typeable CUIntMax
instance Typeable CIntMax
instance Typeable CUIntPtr
instance Typeable CIntPtr
instance Typeable CSUSeconds
instance Typeable CUSeconds
instance Typeable CTime
instance Typeable CClock
instance Typeable CSigAtomic
instance Typeable CWchar
instance Typeable CSize
instance Typeable CPtrdiff
instance Typeable CDouble
instance Typeable CFloat
instance Typeable CULLong
instance Typeable CLLong
instance Typeable CULong
instance Typeable CLong
instance Typeable CUInt
instance Typeable CInt
instance Typeable CUShort
instance Typeable CShort
instance Typeable CUChar
instance Typeable CSChar
instance Typeable CChar
instance Eq CChar
instance Ord CChar
instance Num CChar
instance Enum CChar
instance Storable CChar
instance Real CChar
instance Bounded CChar
instance Integral CChar
instance Bits CChar
instance Eq CSChar
instance Ord CSChar
instance Num CSChar
instance Enum CSChar
instance Storable CSChar
instance Real CSChar
instance Bounded CSChar
instance Integral CSChar
instance Bits CSChar
instance Eq CUChar
instance Ord CUChar
instance Num CUChar
instance Enum CUChar
instance Storable CUChar
instance Real CUChar
instance Bounded CUChar
instance Integral CUChar
instance Bits CUChar
instance Eq CShort
instance Ord CShort
instance Num CShort
instance Enum CShort
instance Storable CShort
instance Real CShort
instance Bounded CShort
instance Integral CShort
instance Bits CShort
instance Eq CUShort
instance Ord CUShort
instance Num CUShort
instance Enum CUShort
instance Storable CUShort
instance Real CUShort
instance Bounded CUShort
instance Integral CUShort
instance Bits CUShort
instance Eq CInt
instance Ord CInt
instance Num CInt
instance Enum CInt
instance Storable CInt
instance Real CInt
instance Bounded CInt
instance Integral CInt
instance Bits CInt
instance Eq CUInt
instance Ord CUInt
instance Num CUInt
instance Enum CUInt
instance Storable CUInt
instance Real CUInt
instance Bounded CUInt
instance Integral CUInt
instance Bits CUInt
instance Eq CLong
instance Ord CLong
instance Num CLong
instance Enum CLong
instance Storable CLong
instance Real CLong
instance Bounded CLong
instance Integral CLong
instance Bits CLong
instance Eq CULong
instance Ord CULong
instance Num CULong
instance Enum CULong
instance Storable CULong
instance Real CULong
instance Bounded CULong
instance Integral CULong
instance Bits CULong
instance Eq CLLong
instance Ord CLLong
instance Num CLLong
instance Enum CLLong
instance Storable CLLong
instance Real CLLong
instance Bounded CLLong
instance Integral CLLong
instance Bits CLLong
instance Eq CULLong
instance Ord CULLong
instance Num CULLong
instance Enum CULLong
instance Storable CULLong
instance Real CULLong
instance Bounded CULLong
instance Integral CULLong
instance Bits CULLong
instance Eq CFloat
instance Ord CFloat
instance Num CFloat
instance Enum CFloat
instance Storable CFloat
instance Real CFloat
instance Fractional CFloat
instance Floating CFloat
instance RealFrac CFloat
instance RealFloat CFloat
instance Eq CDouble
instance Ord CDouble
instance Num CDouble
instance Enum CDouble
instance Storable CDouble
instance Real CDouble
instance Fractional CDouble
instance Floating CDouble
instance RealFrac CDouble
instance RealFloat CDouble
instance Eq CPtrdiff
instance Ord CPtrdiff
instance Num CPtrdiff
instance Enum CPtrdiff
instance Storable CPtrdiff
instance Real CPtrdiff
instance Bounded CPtrdiff
instance Integral CPtrdiff
instance Bits CPtrdiff
instance Eq CSize
instance Ord CSize
instance Num CSize
instance Enum CSize
instance Storable CSize
instance Real CSize
instance Bounded CSize
instance Integral CSize
instance Bits CSize
instance Eq CWchar
instance Ord CWchar
instance Num CWchar
instance Enum CWchar
instance Storable CWchar
instance Real CWchar
instance Bounded CWchar
instance Integral CWchar
instance Bits CWchar
instance Eq CSigAtomic
instance Ord CSigAtomic
instance Num CSigAtomic
instance Enum CSigAtomic
instance Storable CSigAtomic
instance Real CSigAtomic
instance Bounded CSigAtomic
instance Integral CSigAtomic
instance Bits CSigAtomic
instance Eq CClock
instance Ord CClock
instance Num CClock
instance Enum CClock
instance Storable CClock
instance Real CClock
instance Eq CTime
instance Ord CTime
instance Num CTime
instance Enum CTime
instance Storable CTime
instance Real CTime
instance Eq CUSeconds
instance Ord CUSeconds
instance Num CUSeconds
instance Enum CUSeconds
instance Storable CUSeconds
instance Real CUSeconds
instance Eq CSUSeconds
instance Ord CSUSeconds
instance Num CSUSeconds
instance Enum CSUSeconds
instance Storable CSUSeconds
instance Real CSUSeconds
instance Eq CIntPtr
instance Ord CIntPtr
instance Num CIntPtr
instance Enum CIntPtr
instance Storable CIntPtr
instance Real CIntPtr
instance Bounded CIntPtr
instance Integral CIntPtr
instance Bits CIntPtr
instance Eq CUIntPtr
instance Ord CUIntPtr
instance Num CUIntPtr
instance Enum CUIntPtr
instance Storable CUIntPtr
instance Real CUIntPtr
instance Bounded CUIntPtr
instance Integral CUIntPtr
instance Bits CUIntPtr
instance Eq CIntMax
instance Ord CIntMax
instance Num CIntMax
instance Enum CIntMax
instance Storable CIntMax
instance Real CIntMax
instance Bounded CIntMax
instance Integral CIntMax
instance Bits CIntMax
instance Eq CUIntMax
instance Ord CUIntMax
instance Num CUIntMax
instance Enum CUIntMax
instance Storable CUIntMax
instance Real CUIntMax
instance Bounded CUIntMax
instance Integral CUIntMax
instance Bits CUIntMax
instance Show CUIntMax
instance Read CUIntMax
instance Show CIntMax
instance Read CIntMax
instance Show CUIntPtr
instance Read CUIntPtr
instance Show CIntPtr
instance Read CIntPtr
instance Show CSUSeconds
instance Read CSUSeconds
instance Show CUSeconds
instance Read CUSeconds
instance Show CTime
instance Read CTime
instance Show CClock
instance Read CClock
instance Show CSigAtomic
instance Read CSigAtomic
instance Show CWchar
instance Read CWchar
instance Show CSize
instance Read CSize
instance Show CPtrdiff
instance Read CPtrdiff
instance Show CDouble
instance Read CDouble
instance Show CFloat
instance Read CFloat
instance Show CULLong
instance Read CULLong
instance Show CLLong
instance Read CLLong
instance Show CULong
instance Read CULong
instance Show CLong
instance Read CLong
instance Show CUInt
instance Read CUInt
instance Show CInt
instance Read CInt
instance Show CUShort
instance Read CUShort
instance Show CShort
instance Read CShort
instance Show CUChar
instance Read CUChar
instance Show CSChar
instance Read CSChar
instance Show CChar
instance Read CChar


-- | The Char type and associated operations.
module Data.Char

-- | The character type <a>Char</a> is an enumeration whose values
--   represent Unicode (or equivalently ISO/IEC 10646) characters (see
--   <a>http://www.unicode.org/</a> for details). This set extends the ISO
--   8859-1 (Latin-1) character set (the first 256 characters), which is
--   itself an extension of the ASCII character set (the first 128
--   characters). A character literal in Haskell has type <a>Char</a>.
--   
--   To convert a <a>Char</a> to or from the corresponding <a>Int</a> value
--   defined by Unicode, use <a>toEnum</a> and <a>fromEnum</a> from the
--   <a>Enum</a> class respectively (or equivalently <tt>ord</tt> and
--   <tt>chr</tt>).
data Char :: *

-- | Selects control characters, which are the non-printing characters of
--   the Latin-1 subset of Unicode.
isControl :: Char -> Bool

-- | Returns <a>True</a> for any Unicode space character, and the control
--   characters <tt>\t</tt>, <tt>\n</tt>, <tt>\r</tt>, <tt>\f</tt>,
--   <tt>\v</tt>.
isSpace :: Char -> Bool

-- | Selects lower-case alphabetic Unicode characters (letters).
isLower :: Char -> Bool

-- | Selects upper-case or title-case alphabetic Unicode characters
--   (letters). Title case is used by a small number of letter ligatures
--   like the single-character form of <i>Lj</i>.
isUpper :: Char -> Bool

-- | 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 <a>isLetter</a>.
isAlpha :: Char -> Bool

-- | Selects alphabetic or numeric digit Unicode characters.
--   
--   Note that numeric digits outside the ASCII range are selected by this
--   function but not by <a>isDigit</a>. Such digits may be part of
--   identifiers but are not used by the printer and reader to represent
--   numbers.
isAlphaNum :: Char -> Bool

-- | Selects printable Unicode characters (letters, numbers, marks,
--   punctuation, symbols and spaces).
isPrint :: Char -> Bool

-- | Selects ASCII digits, i.e. <tt>'0'</tt>..<tt>'9'</tt>.
isDigit :: Char -> Bool

-- | Selects ASCII octal digits, i.e. <tt>'0'</tt>..<tt>'7'</tt>.
isOctDigit :: Char -> Bool

-- | Selects ASCII hexadecimal digits, i.e. <tt>'0'</tt>..<tt>'9'</tt>,
--   <tt>'a'</tt>..<tt>'f'</tt>, <tt>'A'</tt>..<tt>'F'</tt>.
isHexDigit :: Char -> Bool

-- | 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 <a>isAlpha</a>.
isLetter :: Char -> Bool

-- | Selects Unicode mark characters, e.g. accents and the like, which
--   combine with preceding letters.
isMark :: Char -> Bool

-- | Selects Unicode numeric characters, including digits from various
--   scripts, Roman numerals, etc.
isNumber :: Char -> Bool

-- | Selects Unicode punctuation characters, including various kinds of
--   connectors, brackets and quotes.
isPunctuation :: Char -> Bool

-- | Selects Unicode symbol characters, including mathematical and currency
--   symbols.
isSymbol :: Char -> Bool

-- | Selects Unicode space and separator characters.
isSeparator :: Char -> Bool

-- | Selects the first 128 characters of the Unicode character set,
--   corresponding to the ASCII character set.
isAscii :: Char -> Bool

-- | Selects the first 256 characters of the Unicode character set,
--   corresponding to the ISO 8859-1 (Latin-1) character set.
isLatin1 :: Char -> Bool

-- | Selects ASCII upper-case letters, i.e. characters satisfying both
--   <a>isAscii</a> and <a>isUpper</a>.
isAsciiUpper :: Char -> Bool

-- | Selects ASCII lower-case letters, i.e. characters satisfying both
--   <a>isAscii</a> and <a>isLower</a>.
isAsciiLower :: Char -> Bool

-- | Unicode General Categories (column 2 of the UnicodeData table) in the
--   order they are listed in the Unicode standard.
data GeneralCategory

-- | Lu: Letter, Uppercase
UppercaseLetter :: GeneralCategory

-- | Ll: Letter, Lowercase
LowercaseLetter :: GeneralCategory

-- | Lt: Letter, Titlecase
TitlecaseLetter :: GeneralCategory

-- | Lm: Letter, Modifier
ModifierLetter :: GeneralCategory

-- | Lo: Letter, Other
OtherLetter :: GeneralCategory

-- | Mn: Mark, Non-Spacing
NonSpacingMark :: GeneralCategory

-- | Mc: Mark, Spacing Combining
SpacingCombiningMark :: GeneralCategory

-- | Me: Mark, Enclosing
EnclosingMark :: GeneralCategory

-- | Nd: Number, Decimal
DecimalNumber :: GeneralCategory

-- | Nl: Number, Letter
LetterNumber :: GeneralCategory

-- | No: Number, Other
OtherNumber :: GeneralCategory

-- | Pc: Punctuation, Connector
ConnectorPunctuation :: GeneralCategory

-- | Pd: Punctuation, Dash
DashPunctuation :: GeneralCategory

-- | Ps: Punctuation, Open
OpenPunctuation :: GeneralCategory

-- | Pe: Punctuation, Close
ClosePunctuation :: GeneralCategory

-- | Pi: Punctuation, Initial quote
InitialQuote :: GeneralCategory

-- | Pf: Punctuation, Final quote
FinalQuote :: GeneralCategory

-- | Po: Punctuation, Other
OtherPunctuation :: GeneralCategory

-- | Sm: Symbol, Math
MathSymbol :: GeneralCategory

-- | Sc: Symbol, Currency
CurrencySymbol :: GeneralCategory

-- | Sk: Symbol, Modifier
ModifierSymbol :: GeneralCategory

-- | So: Symbol, Other
OtherSymbol :: GeneralCategory

-- | Zs: Separator, Space
Space :: GeneralCategory

-- | Zl: Separator, Line
LineSeparator :: GeneralCategory

-- | Zp: Separator, Paragraph
ParagraphSeparator :: GeneralCategory

-- | Cc: Other, Control
Control :: GeneralCategory

-- | Cf: Other, Format
Format :: GeneralCategory

-- | Cs: Other, Surrogate
Surrogate :: GeneralCategory

-- | Co: Other, Private Use
PrivateUse :: GeneralCategory

-- | Cn: Other, Not Assigned
NotAssigned :: GeneralCategory

-- | The Unicode general category of the character.
generalCategory :: Char -> GeneralCategory

-- | Convert a letter to the corresponding upper-case letter, if any. Any
--   other character is returned unchanged.
toUpper :: Char -> Char

-- | Convert a letter to the corresponding lower-case letter, if any. Any
--   other character is returned unchanged.
toLower :: Char -> Char

-- | Convert a letter to the corresponding title-case or upper-case letter,
--   if any. (Title case differs from upper case only for a small number of
--   ligature letters.) Any other character is returned unchanged.
toTitle :: Char -> Char

-- | Convert a single digit <a>Char</a> to the corresponding <a>Int</a>.
--   This function fails unless its argument satisfies <a>isHexDigit</a>,
--   but recognises both upper and lower-case hexadecimal digits (i.e.
--   <tt>'0'</tt>..<tt>'9'</tt>, <tt>'a'</tt>..<tt>'f'</tt>,
--   <tt>'A'</tt>..<tt>'F'</tt>).
digitToInt :: Char -> Int

-- | Convert an <a>Int</a> in the range <tt>0</tt>..<tt>15</tt> to the
--   corresponding single digit <a>Char</a>. This function fails on other
--   inputs, and generates lower-case hexadecimal digits.
intToDigit :: Int -> Char

-- | The <a>fromEnum</a> method restricted to the type <a>Char</a>.
ord :: Char -> Int

-- | The <a>toEnum</a> method restricted to the type <a>Char</a>.
chr :: Int -> Char

-- | Convert a character to a string using only printable characters, using
--   Haskell source-language escape conventions. For example:
--   
--   <pre>
--   showLitChar '\n' s  =  "\\n" ++ s
--   </pre>
showLitChar :: Char -> ShowS

-- | Read a string representation of a character, using Haskell
--   source-language escape conventions. For example:
--   
--   <pre>
--   lexLitChar  "\\nHello"  =  [("\\n", "Hello")]
--   </pre>
lexLitChar :: ReadS String

-- | Read a string representation of a character, using Haskell
--   source-language escape conventions, and convert it to the character
--   that it encodes. For example:
--   
--   <pre>
--   readLitChar "\\nHello"  =  [('\n', "Hello")]
--   </pre>
readLitChar :: ReadS Char
instance Eq GeneralCategory
instance Ord GeneralCategory
instance Enum GeneralCategory
instance Read GeneralCategory
instance Show GeneralCategory
instance Bounded GeneralCategory
instance Ix GeneralCategory


-- | Operations on lists.
module Data.List

-- | Append two lists, i.e.,
--   
--   <pre>
--   [x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn]
--   [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]
--   </pre>
--   
--   If the first list is not finite, the result is the first list.
(++) :: [a] -> [a] -> [a]

-- | Extract the first element of a list, which must be non-empty.
head :: [a] -> a

-- | Extract the last element of a list, which must be finite and
--   non-empty.
last :: [a] -> a

-- | Extract the elements after the head of a list, which must be
--   non-empty.
tail :: [a] -> [a]

-- | Return all the elements of a list except the last one. The list must
--   be non-empty.
init :: [a] -> [a]

-- | Test whether a list is empty.
null :: [a] -> Bool

-- | <i>O(n)</i>. <a>length</a> returns the length of a finite list as an
--   <a>Int</a>. It is an instance of the more general
--   <a>genericLength</a>, the result type of which may be any kind of
--   number.
length :: [a] -> Int

-- | <a>map</a> <tt>f xs</tt> is the list obtained by applying <tt>f</tt>
--   to each element of <tt>xs</tt>, i.e.,
--   
--   <pre>
--   map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn]
--   map f [x1, x2, ...] == [f x1, f x2, ...]
--   </pre>
map :: (a -> b) -> [a] -> [b]

-- | <a>reverse</a> <tt>xs</tt> returns the elements of <tt>xs</tt> in
--   reverse order. <tt>xs</tt> must be finite.
reverse :: [a] -> [a]

-- | The <a>intersperse</a> function takes an element and a list and
--   `intersperses' that element between the elements of the list. For
--   example,
--   
--   <pre>
--   intersperse ',' "abcde" == "a,b,c,d,e"
--   </pre>
intersperse :: a -> [a] -> [a]

-- | <a>intercalate</a> <tt>xs xss</tt> is equivalent to <tt>(<a>concat</a>
--   (<a>intersperse</a> xs xss))</tt>. It inserts the list <tt>xs</tt> in
--   between the lists in <tt>xss</tt> and concatenates the result.
intercalate :: [a] -> [[a]] -> [a]

-- | The <a>transpose</a> function transposes the rows and columns of its
--   argument. For example,
--   
--   <pre>
--   transpose [[1,2,3],[4,5,6]] == [[1,4],[2,5],[3,6]]
--   </pre>
transpose :: [[a]] -> [[a]]

-- | The <a>subsequences</a> function returns the list of all subsequences
--   of the argument.
--   
--   <pre>
--   subsequences "abc" == ["","a","b","ab","c","ac","bc","abc"]
--   </pre>
subsequences :: [a] -> [[a]]

-- | The <a>permutations</a> function returns the list of all permutations
--   of the argument.
--   
--   <pre>
--   permutations "abc" == ["abc","bac","cba","bca","cab","acb"]
--   </pre>
permutations :: [a] -> [[a]]

-- | <a>foldl</a>, applied to a binary operator, a starting value
--   (typically the left-identity of the operator), and a list, reduces the
--   list using the binary operator, from left to right:
--   
--   <pre>
--   foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
--   </pre>
--   
--   The list must be finite.
foldl :: (a -> b -> a) -> a -> [b] -> a

-- | A strict version of <a>foldl</a>.
foldl' :: (a -> b -> a) -> a -> [b] -> a

-- | <a>foldl1</a> is a variant of <a>foldl</a> that has no starting value
--   argument, and thus must be applied to non-empty lists.
foldl1 :: (a -> a -> a) -> [a] -> a

-- | A strict version of <a>foldl1</a>
foldl1' :: (a -> a -> a) -> [a] -> a

-- | <a>foldr</a>, applied to a binary operator, a starting value
--   (typically the right-identity of the operator), and a list, reduces
--   the list using the binary operator, from right to left:
--   
--   <pre>
--   foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)
--   </pre>
foldr :: (a -> b -> b) -> b -> [a] -> b

-- | <a>foldr1</a> is a variant of <a>foldr</a> that has no starting value
--   argument, and thus must be applied to non-empty lists.
foldr1 :: (a -> a -> a) -> [a] -> a

-- | Concatenate a list of lists.
concat :: [[a]] -> [a]

-- | Map a function over a list and concatenate the results.
concatMap :: (a -> [b]) -> [a] -> [b]

-- | <a>and</a> returns the conjunction of a Boolean list. For the result
--   to be <a>True</a>, the list must be finite; <a>False</a>, however,
--   results from a <a>False</a> value at a finite index of a finite or
--   infinite list.
and :: [Bool] -> Bool

-- | <a>or</a> returns the disjunction of a Boolean list. For the result to
--   be <a>False</a>, the list must be finite; <a>True</a>, however,
--   results from a <a>True</a> value at a finite index of a finite or
--   infinite list.
or :: [Bool] -> Bool

-- | Applied to a predicate and a list, <a>any</a> determines if any
--   element of the list satisfies the predicate. For the result to be
--   <a>False</a>, the list must be finite; <a>True</a>, however, results
--   from a <a>True</a> value for the predicate applied to an element at a
--   finite index of a finite or infinite list.
any :: (a -> Bool) -> [a] -> Bool

-- | Applied to a predicate and a list, <a>all</a> determines if all
--   elements of the list satisfy the predicate. For the result to be
--   <a>True</a>, the list must be finite; <a>False</a>, however, results
--   from a <a>False</a> value for the predicate applied to an element at a
--   finite index of a finite or infinite list.
all :: (a -> Bool) -> [a] -> Bool

-- | The <a>sum</a> function computes the sum of a finite list of numbers.
sum :: Num a => [a] -> a

-- | The <a>product</a> function computes the product of a finite list of
--   numbers.
product :: Num a => [a] -> a

-- | <a>maximum</a> returns the maximum value from a list, which must be
--   non-empty, finite, and of an ordered type. It is a special case of
--   <a>maximumBy</a>, which allows the programmer to supply their own
--   comparison function.
maximum :: Ord a => [a] -> a

-- | <a>minimum</a> returns the minimum value from a list, which must be
--   non-empty, finite, and of an ordered type. It is a special case of
--   <a>minimumBy</a>, which allows the programmer to supply their own
--   comparison function.
minimum :: Ord a => [a] -> a

-- | <a>scanl</a> is similar to <a>foldl</a>, but returns a list of
--   successive reduced values from the left:
--   
--   <pre>
--   scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
--   </pre>
--   
--   Note that
--   
--   <pre>
--   last (scanl f z xs) == foldl f z xs.
--   </pre>
scanl :: (a -> b -> a) -> a -> [b] -> [a]

-- | <a>scanl1</a> is a variant of <a>scanl</a> that has no starting value
--   argument:
--   
--   <pre>
--   scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
--   </pre>
scanl1 :: (a -> a -> a) -> [a] -> [a]

-- | <a>scanr</a> is the right-to-left dual of <a>scanl</a>. Note that
--   
--   <pre>
--   head (scanr f z xs) == foldr f z xs.
--   </pre>
scanr :: (a -> b -> b) -> b -> [a] -> [b]

-- | <a>scanr1</a> is a variant of <a>scanr</a> that has no starting value
--   argument.
scanr1 :: (a -> a -> a) -> [a] -> [a]

-- | The <a>mapAccumL</a> function behaves like a combination of <a>map</a>
--   and <a>foldl</a>; it applies a function to each element of a list,
--   passing an accumulating parameter from left to right, and returning a
--   final value of this accumulator together with the new list.
mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])

-- | The <a>mapAccumR</a> function behaves like a combination of <a>map</a>
--   and <a>foldr</a>; it applies a function to each element of a list,
--   passing an accumulating parameter from right to left, and returning a
--   final value of this accumulator together with the new list.
mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])

-- | <a>iterate</a> <tt>f x</tt> returns an infinite list of repeated
--   applications of <tt>f</tt> to <tt>x</tt>:
--   
--   <pre>
--   iterate f x == [x, f x, f (f x), ...]
--   </pre>
iterate :: (a -> a) -> a -> [a]

-- | <a>repeat</a> <tt>x</tt> is an infinite list, with <tt>x</tt> the
--   value of every element.
repeat :: a -> [a]

-- | <a>replicate</a> <tt>n x</tt> is a list of length <tt>n</tt> with
--   <tt>x</tt> the value of every element. It is an instance of the more
--   general <a>genericReplicate</a>, in which <tt>n</tt> may be of any
--   integral type.
replicate :: Int -> a -> [a]

-- | <a>cycle</a> ties a finite list into a circular one, or equivalently,
--   the infinite repetition of the original list. It is the identity on
--   infinite lists.
cycle :: [a] -> [a]

-- | The <a>unfoldr</a> function is a `dual' to <a>foldr</a>: while
--   <a>foldr</a> reduces a list to a summary value, <a>unfoldr</a> builds
--   a list from a seed value. The function takes the element and returns
--   <a>Nothing</a> if it is done producing the list or returns <a>Just</a>
--   <tt>(a,b)</tt>, in which case, <tt>a</tt> is a prepended to the list
--   and <tt>b</tt> is used as the next element in a recursive call. For
--   example,
--   
--   <pre>
--   iterate f == unfoldr (\x -&gt; Just (x, f x))
--   </pre>
--   
--   In some cases, <a>unfoldr</a> can undo a <a>foldr</a> operation:
--   
--   <pre>
--   unfoldr f' (foldr f z xs) == xs
--   </pre>
--   
--   if the following holds:
--   
--   <pre>
--   f' (f x y) = Just (x,y)
--   f' z       = Nothing
--   </pre>
--   
--   A simple use of unfoldr:
--   
--   <pre>
--   unfoldr (\b -&gt; if b == 0 then Nothing else Just (b, b-1)) 10
--    [10,9,8,7,6,5,4,3,2,1]
--   </pre>
unfoldr :: (b -> Maybe (a, b)) -> b -> [a]

-- | <a>take</a> <tt>n</tt>, applied to a list <tt>xs</tt>, returns the
--   prefix of <tt>xs</tt> of length <tt>n</tt>, or <tt>xs</tt> itself if
--   <tt>n &gt; <a>length</a> xs</tt>:
--   
--   <pre>
--   take 5 "Hello World!" == "Hello"
--   take 3 [1,2,3,4,5] == [1,2,3]
--   take 3 [1,2] == [1,2]
--   take 3 [] == []
--   take (-1) [1,2] == []
--   take 0 [1,2] == []
--   </pre>
--   
--   It is an instance of the more general <a>genericTake</a>, in which
--   <tt>n</tt> may be of any integral type.
take :: Int -> [a] -> [a]

-- | <a>drop</a> <tt>n xs</tt> returns the suffix of <tt>xs</tt> after the
--   first <tt>n</tt> elements, or <tt>[]</tt> if <tt>n &gt; <a>length</a>
--   xs</tt>:
--   
--   <pre>
--   drop 6 "Hello World!" == "World!"
--   drop 3 [1,2,3,4,5] == [4,5]
--   drop 3 [1,2] == []
--   drop 3 [] == []
--   drop (-1) [1,2] == [1,2]
--   drop 0 [1,2] == [1,2]
--   </pre>
--   
--   It is an instance of the more general <a>genericDrop</a>, in which
--   <tt>n</tt> may be of any integral type.
drop :: Int -> [a] -> [a]

-- | <a>splitAt</a> <tt>n xs</tt> returns a tuple where first element is
--   <tt>xs</tt> prefix of length <tt>n</tt> and second element is the
--   remainder of the list:
--   
--   <pre>
--   splitAt 6 "Hello World!" == ("Hello ","World!")
--   splitAt 3 [1,2,3,4,5] == ([1,2,3],[4,5])
--   splitAt 1 [1,2,3] == ([1],[2,3])
--   splitAt 3 [1,2,3] == ([1,2,3],[])
--   splitAt 4 [1,2,3] == ([1,2,3],[])
--   splitAt 0 [1,2,3] == ([],[1,2,3])
--   splitAt (-1) [1,2,3] == ([],[1,2,3])
--   </pre>
--   
--   It is equivalent to <tt>(<a>take</a> n xs, <a>drop</a> n xs)</tt> when
--   <tt>n</tt> is not <tt>_|_</tt> (<tt>splitAt _|_ xs = _|_</tt>).
--   <a>splitAt</a> is an instance of the more general
--   <a>genericSplitAt</a>, in which <tt>n</tt> may be of any integral
--   type.
splitAt :: Int -> [a] -> ([a], [a])

-- | <a>takeWhile</a>, applied to a predicate <tt>p</tt> and a list
--   <tt>xs</tt>, returns the longest prefix (possibly empty) of
--   <tt>xs</tt> of elements that satisfy <tt>p</tt>:
--   
--   <pre>
--   takeWhile (&lt; 3) [1,2,3,4,1,2,3,4] == [1,2]
--   takeWhile (&lt; 9) [1,2,3] == [1,2,3]
--   takeWhile (&lt; 0) [1,2,3] == []
--   </pre>
takeWhile :: (a -> Bool) -> [a] -> [a]

-- | <a>dropWhile</a> <tt>p xs</tt> returns the suffix remaining after
--   <a>takeWhile</a> <tt>p xs</tt>:
--   
--   <pre>
--   dropWhile (&lt; 3) [1,2,3,4,5,1,2,3] == [3,4,5,1,2,3]
--   dropWhile (&lt; 9) [1,2,3] == []
--   dropWhile (&lt; 0) [1,2,3] == [1,2,3]
--   </pre>
dropWhile :: (a -> Bool) -> [a] -> [a]

-- | The <a>dropWhileEnd</a> function drops the largest suffix of a list in
--   which the given predicate holds for all elements. For example:
--   
--   <pre>
--   dropWhileEnd isSpace "foo\n" == "foo"
--   dropWhileEnd isSpace "foo bar" == "foo bar"
--   dropWhileEnd isSpace ("foo\n" ++ undefined) == "foo" ++ undefined
--   </pre>
dropWhileEnd :: (a -> Bool) -> [a] -> [a]

-- | <a>span</a>, applied to a predicate <tt>p</tt> and a list <tt>xs</tt>,
--   returns a tuple where first element is longest prefix (possibly empty)
--   of <tt>xs</tt> of elements that satisfy <tt>p</tt> and second element
--   is the remainder of the list:
--   
--   <pre>
--   span (&lt; 3) [1,2,3,4,1,2,3,4] == ([1,2],[3,4,1,2,3,4])
--   span (&lt; 9) [1,2,3] == ([1,2,3],[])
--   span (&lt; 0) [1,2,3] == ([],[1,2,3])
--   </pre>
--   
--   <a>span</a> <tt>p xs</tt> is equivalent to <tt>(<a>takeWhile</a> p xs,
--   <a>dropWhile</a> p xs)</tt>
span :: (a -> Bool) -> [a] -> ([a], [a])

-- | <a>break</a>, applied to a predicate <tt>p</tt> and a list
--   <tt>xs</tt>, returns a tuple where first element is longest prefix
--   (possibly empty) of <tt>xs</tt> of elements that <i>do not satisfy</i>
--   <tt>p</tt> and second element is the remainder of the list:
--   
--   <pre>
--   break (&gt; 3) [1,2,3,4,1,2,3,4] == ([1,2,3],[4,1,2,3,4])
--   break (&lt; 9) [1,2,3] == ([],[1,2,3])
--   break (&gt; 9) [1,2,3] == ([1,2,3],[])
--   </pre>
--   
--   <a>break</a> <tt>p</tt> is equivalent to <tt><a>span</a> (<a>not</a> .
--   p)</tt>.
break :: (a -> Bool) -> [a] -> ([a], [a])

-- | The <a>stripPrefix</a> function drops the given prefix from a list. It
--   returns <a>Nothing</a> if the list did not start with the prefix
--   given, or <a>Just</a> the list after the prefix, if it does.
--   
--   <pre>
--   stripPrefix "foo" "foobar" == Just "bar"
--   stripPrefix "foo" "foo" == Just ""
--   stripPrefix "foo" "barfoo" == Nothing
--   stripPrefix "foo" "barfoobaz" == Nothing
--   </pre>
stripPrefix :: Eq a => [a] -> [a] -> Maybe [a]

-- | The <a>group</a> function takes a list and returns a list of lists
--   such that the concatenation of the result is equal to the argument.
--   Moreover, each sublist in the result contains only equal elements. For
--   example,
--   
--   <pre>
--   group "Mississippi" = ["M","i","ss","i","ss","i","pp","i"]
--   </pre>
--   
--   It is a special case of <a>groupBy</a>, which allows the programmer to
--   supply their own equality test.
group :: Eq a => [a] -> [[a]]

-- | The <a>inits</a> function returns all initial segments of the
--   argument, shortest first. For example,
--   
--   <pre>
--   inits "abc" == ["","a","ab","abc"]
--   </pre>
--   
--   Note that <a>inits</a> has the following strictness property:
--   <tt>inits _|_ = [] : _|_</tt>
inits :: [a] -> [[a]]

-- | The <a>tails</a> function returns all final segments of the argument,
--   longest first. For example,
--   
--   <pre>
--   tails "abc" == ["abc", "bc", "c",""]
--   </pre>
--   
--   Note that <a>tails</a> has the following strictness property:
--   <tt>tails _|_ = _|_ : _|_</tt>
tails :: [a] -> [[a]]

-- | The <a>isPrefixOf</a> function takes two lists and returns <a>True</a>
--   iff the first list is a prefix of the second.
isPrefixOf :: Eq a => [a] -> [a] -> Bool

-- | The <a>isSuffixOf</a> function takes two lists and returns <a>True</a>
--   iff the first list is a suffix of the second. Both lists must be
--   finite.
isSuffixOf :: Eq a => [a] -> [a] -> Bool

-- | The <a>isInfixOf</a> function takes two lists and returns <a>True</a>
--   iff the first list is contained, wholly and intact, anywhere within
--   the second.
--   
--   Example:
--   
--   <pre>
--   isInfixOf "Haskell" "I really like Haskell." == True
--   isInfixOf "Ial" "I really like Haskell." == False
--   </pre>
isInfixOf :: Eq a => [a] -> [a] -> Bool

-- | <a>elem</a> is the list membership predicate, usually written in infix
--   form, e.g., <tt>x `elem` xs</tt>. For the result to be <a>False</a>,
--   the list must be finite; <a>True</a>, however, results from an element
--   equal to <tt>x</tt> found at a finite index of a finite or infinite
--   list.
elem :: Eq a => a -> [a] -> Bool

-- | <a>notElem</a> is the negation of <a>elem</a>.
notElem :: Eq a => a -> [a] -> Bool

-- | <a>lookup</a> <tt>key assocs</tt> looks up a key in an association
--   list.
lookup :: Eq a => a -> [(a, b)] -> Maybe b

-- | The <a>find</a> function takes a predicate and a list and returns the
--   first element in the list matching the predicate, or <a>Nothing</a> if
--   there is no such element.
find :: (a -> Bool) -> [a] -> Maybe a

-- | <a>filter</a>, applied to a predicate and a list, returns the list of
--   those elements that satisfy the predicate; i.e.,
--   
--   <pre>
--   filter p xs = [ x | x &lt;- xs, p x]
--   </pre>
filter :: (a -> Bool) -> [a] -> [a]

-- | The <a>partition</a> function takes a predicate a list and returns the
--   pair of lists of elements which do and do not satisfy the predicate,
--   respectively; i.e.,
--   
--   <pre>
--   partition p xs == (filter p xs, filter (not . p) xs)
--   </pre>
partition :: (a -> Bool) -> [a] -> ([a], [a])

-- | List index (subscript) operator, starting from 0. It is an instance of
--   the more general <a>genericIndex</a>, which takes an index of any
--   integral type.
(!!) :: [a] -> Int -> a

-- | The <a>elemIndex</a> function returns the index of the first element
--   in the given list which is equal (by <a>==</a>) to the query element,
--   or <a>Nothing</a> if there is no such element.
elemIndex :: Eq a => a -> [a] -> Maybe Int

-- | The <a>elemIndices</a> function extends <a>elemIndex</a>, by returning
--   the indices of all elements equal to the query element, in ascending
--   order.
elemIndices :: Eq a => a -> [a] -> [Int]

-- | The <a>findIndex</a> function takes a predicate and a list and returns
--   the index of the first element in the list satisfying the predicate,
--   or <a>Nothing</a> if there is no such element.
findIndex :: (a -> Bool) -> [a] -> Maybe Int

-- | The <a>findIndices</a> function extends <a>findIndex</a>, by returning
--   the indices of all elements satisfying the predicate, in ascending
--   order.
findIndices :: (a -> Bool) -> [a] -> [Int]

-- | <a>zip</a> takes two lists and returns a list of corresponding pairs.
--   If one input list is short, excess elements of the longer list are
--   discarded.
zip :: [a] -> [b] -> [(a, b)]

-- | <a>zip3</a> takes three lists and returns a list of triples, analogous
--   to <a>zip</a>.
zip3 :: [a] -> [b] -> [c] -> [(a, b, c)]

-- | The <a>zip4</a> function takes four lists and returns a list of
--   quadruples, analogous to <a>zip</a>.
zip4 :: [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)]

-- | The <a>zip5</a> function takes five lists and returns a list of
--   five-tuples, analogous to <a>zip</a>.
zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a, b, c, d, e)]

-- | The <a>zip6</a> function takes six lists and returns a list of
--   six-tuples, analogous to <a>zip</a>.
zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a, b, c, d, e, f)]

-- | The <a>zip7</a> function takes seven lists and returns a list of
--   seven-tuples, analogous to <a>zip</a>.
zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a, b, c, d, e, f, g)]

-- | <a>zipWith</a> generalises <a>zip</a> by zipping with the function
--   given as the first argument, instead of a tupling function. For
--   example, <tt><a>zipWith</a> (+)</tt> is applied to two lists to
--   produce the list of corresponding sums.
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]

-- | The <a>zipWith3</a> function takes a function which combines three
--   elements, as well as three lists and returns a list of their
--   point-wise combination, analogous to <a>zipWith</a>.
zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]

-- | The <a>zipWith4</a> function takes a function which combines four
--   elements, as well as four lists and returns a list of their point-wise
--   combination, analogous to <a>zipWith</a>.
zipWith4 :: (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e]

-- | The <a>zipWith5</a> function takes a function which combines five
--   elements, as well as five lists and returns a list of their point-wise
--   combination, analogous to <a>zipWith</a>.
zipWith5 :: (a -> b -> c -> d -> e -> f) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f]

-- | The <a>zipWith6</a> function takes a function which combines six
--   elements, as well as six lists and returns a list of their point-wise
--   combination, analogous to <a>zipWith</a>.
zipWith6 :: (a -> b -> c -> d -> e -> f -> g) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g]

-- | The <a>zipWith7</a> function takes a function which combines seven
--   elements, as well as seven lists and returns a list of their
--   point-wise combination, analogous to <a>zipWith</a>.
zipWith7 :: (a -> b -> c -> d -> e -> f -> g -> h) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [h]

-- | <a>unzip</a> transforms a list of pairs into a list of first
--   components and a list of second components.
unzip :: [(a, b)] -> ([a], [b])

-- | The <a>unzip3</a> function takes a list of triples and returns three
--   lists, analogous to <a>unzip</a>.
unzip3 :: [(a, b, c)] -> ([a], [b], [c])

-- | The <a>unzip4</a> function takes a list of quadruples and returns four
--   lists, analogous to <a>unzip</a>.
unzip4 :: [(a, b, c, d)] -> ([a], [b], [c], [d])

-- | The <a>unzip5</a> function takes a list of five-tuples and returns
--   five lists, analogous to <a>unzip</a>.
unzip5 :: [(a, b, c, d, e)] -> ([a], [b], [c], [d], [e])

-- | The <a>unzip6</a> function takes a list of six-tuples and returns six
--   lists, analogous to <a>unzip</a>.
unzip6 :: [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f])

-- | The <a>unzip7</a> function takes a list of seven-tuples and returns
--   seven lists, analogous to <a>unzip</a>.
unzip7 :: [(a, b, c, d, e, f, g)] -> ([a], [b], [c], [d], [e], [f], [g])

-- | <a>lines</a> breaks a string up into a list of strings at newline
--   characters. The resulting strings do not contain newlines.
lines :: String -> [String]

-- | <a>words</a> breaks a string up into a list of words, which were
--   delimited by white space.
words :: String -> [String]

-- | <a>unlines</a> is an inverse operation to <a>lines</a>. It joins
--   lines, after appending a terminating newline to each.
unlines :: [String] -> String

-- | <a>unwords</a> is an inverse operation to <a>words</a>. It joins words
--   with separating spaces.
unwords :: [String] -> String

-- | <i>O(n^2)</i>. The <a>nub</a> function removes duplicate elements from
--   a list. In particular, it keeps only the first occurrence of each
--   element. (The name <a>nub</a> means `essence'.) It is a special case
--   of <a>nubBy</a>, which allows the programmer to supply their own
--   equality test.
nub :: Eq a => [a] -> [a]

-- | <a>delete</a> <tt>x</tt> removes the first occurrence of <tt>x</tt>
--   from its list argument. For example,
--   
--   <pre>
--   delete 'a' "banana" == "bnana"
--   </pre>
--   
--   It is a special case of <a>deleteBy</a>, which allows the programmer
--   to supply their own equality test.
delete :: Eq a => a -> [a] -> [a]

-- | The <a>\\</a> function is list difference (non-associative). In the
--   result of <tt>xs</tt> <a>\\</a> <tt>ys</tt>, the first occurrence of
--   each element of <tt>ys</tt> in turn (if any) has been removed from
--   <tt>xs</tt>. Thus
--   
--   <pre>
--   (xs ++ ys) \\ xs == ys.
--   </pre>
--   
--   It is a special case of <a>deleteFirstsBy</a>, which allows the
--   programmer to supply their own equality test.
(\\) :: Eq a => [a] -> [a] -> [a]

-- | The <a>union</a> function returns the list union of the two lists. For
--   example,
--   
--   <pre>
--   "dog" `union` "cow" == "dogcw"
--   </pre>
--   
--   Duplicates, and elements of the first list, are removed from the the
--   second list, but if the first list contains duplicates, so will the
--   result. It is a special case of <a>unionBy</a>, which allows the
--   programmer to supply their own equality test.
union :: Eq a => [a] -> [a] -> [a]

-- | The <a>intersect</a> function takes the list intersection of two
--   lists. For example,
--   
--   <pre>
--   [1,2,3,4] `intersect` [2,4,6,8] == [2,4]
--   </pre>
--   
--   If the first list contains duplicates, so will the result.
--   
--   <pre>
--   [1,2,2,3,4] `intersect` [6,4,4,2] == [2,2,4]
--   </pre>
--   
--   It is a special case of <a>intersectBy</a>, which allows the
--   programmer to supply their own equality test. If the element is found
--   in both the first and the second list, the element from the first list
--   will be used.
intersect :: Eq a => [a] -> [a] -> [a]

-- | The <a>sort</a> function implements a stable sorting algorithm. It is
--   a special case of <a>sortBy</a>, which allows the programmer to supply
--   their own comparison function.
sort :: Ord a => [a] -> [a]

-- | The <a>insert</a> function takes an element and a list and inserts the
--   element into the list at the first position where it is less than or
--   equal to the next element. In particular, if the list is sorted before
--   the call, the result will also be sorted. It is a special case of
--   <a>insertBy</a>, which allows the programmer to supply their own
--   comparison function.
insert :: Ord a => a -> [a] -> [a]

-- | The <a>nubBy</a> function behaves just like <a>nub</a>, except it uses
--   a user-supplied equality predicate instead of the overloaded <a>==</a>
--   function.
nubBy :: (a -> a -> Bool) -> [a] -> [a]

-- | The <a>deleteBy</a> function behaves like <a>delete</a>, but takes a
--   user-supplied equality predicate.
deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]

-- | The <a>deleteFirstsBy</a> function takes a predicate and two lists and
--   returns the first list with the first occurrence of each element of
--   the second list removed.
deleteFirstsBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]

-- | The <a>unionBy</a> function is the non-overloaded version of
--   <a>union</a>.
unionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]

-- | The <a>intersectBy</a> function is the non-overloaded version of
--   <a>intersect</a>.
intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]

-- | The <a>groupBy</a> function is the non-overloaded version of
--   <a>group</a>.
groupBy :: (a -> a -> Bool) -> [a] -> [[a]]

-- | The <a>sortBy</a> function is the non-overloaded version of
--   <a>sort</a>.
sortBy :: (a -> a -> Ordering) -> [a] -> [a]

-- | The non-overloaded version of <a>insert</a>.
insertBy :: (a -> a -> Ordering) -> a -> [a] -> [a]

-- | The <a>maximumBy</a> function takes a comparison function and a list
--   and returns the greatest element of the list by the comparison
--   function. The list must be finite and non-empty.
maximumBy :: (a -> a -> Ordering) -> [a] -> a

-- | The <a>minimumBy</a> function takes a comparison function and a list
--   and returns the least element of the list by the comparison function.
--   The list must be finite and non-empty.
minimumBy :: (a -> a -> Ordering) -> [a] -> a

-- | The <a>genericLength</a> function is an overloaded version of
--   <a>length</a>. In particular, instead of returning an <a>Int</a>, it
--   returns any type which is an instance of <a>Num</a>. It is, however,
--   less efficient than <a>length</a>.
genericLength :: Num i => [b] -> i

-- | The <a>genericTake</a> function is an overloaded version of
--   <a>take</a>, which accepts any <a>Integral</a> value as the number of
--   elements to take.
genericTake :: Integral i => i -> [a] -> [a]

-- | The <a>genericDrop</a> function is an overloaded version of
--   <a>drop</a>, which accepts any <a>Integral</a> value as the number of
--   elements to drop.
genericDrop :: Integral i => i -> [a] -> [a]

-- | The <a>genericSplitAt</a> function is an overloaded version of
--   <a>splitAt</a>, which accepts any <a>Integral</a> value as the
--   position at which to split.
genericSplitAt :: Integral i => i -> [b] -> ([b], [b])

-- | The <a>genericIndex</a> function is an overloaded version of
--   <a>!!</a>, which accepts any <a>Integral</a> value as the index.
genericIndex :: Integral a => [b] -> a -> b

-- | The <a>genericReplicate</a> function is an overloaded version of
--   <a>replicate</a>, which accepts any <a>Integral</a> value as the
--   number of repetitions to make.
genericReplicate :: Integral i => i -> a -> [a]


-- | The representations of the types TyCon and TypeRep, and the function
--   mkTyCon which is used by derived instances of Typeable to construct a
--   TyCon.
module Data.Typeable.Internal

-- | A concrete representation of a (monomorphic) type. <a>TypeRep</a>
--   supports reasonably efficient equality.
data TypeRep
TypeRep :: {-# UNPACK #-} !Fingerprint -> TyCon -> [TypeRep] -> TypeRep
data Fingerprint
Fingerprint :: {-# UNPACK #-} !Word64 -> {-# UNPACK #-} !Word64 -> Fingerprint

-- | An abstract representation of a type constructor. <a>TyCon</a> objects
--   can be built using <a>mkTyCon</a>.
data TyCon
TyCon :: {-# UNPACK #-} !Fingerprint -> String -> String -> String -> TyCon
tyConHash :: TyCon -> {-# UNPACK #-} !Fingerprint
tyConPackage :: TyCon -> String
tyConModule :: TyCon -> String
tyConName :: TyCon -> String
mkTyCon :: Word64# -> Word64# -> String -> String -> String -> TyCon

-- | Builds a <a>TyCon</a> object representing a type constructor. An
--   implementation of <a>Data.Typeable</a> should ensure that the
--   following holds:
--   
--   <pre>
--   A==A' ^ B==B' ^ C==C' ==&gt; mkTyCon A B C == mkTyCon A' B' C'
--   </pre>
mkTyCon3 :: String -> String -> String -> TyCon

-- | Applies a type constructor to a sequence of types
mkTyConApp :: TyCon -> [TypeRep] -> TypeRep

-- | Adds a TypeRep argument to a TypeRep.
mkAppTy :: TypeRep -> TypeRep -> TypeRep

-- | Observe the type constructor of a type representation
typeRepTyCon :: TypeRep -> TyCon

-- | For defining a <a>Typeable</a> instance from any <a>Typeable1</a>
--   instance.
typeOfDefault :: (Typeable1 t, Typeable a) => t a -> TypeRep

-- | For defining a <a>Typeable1</a> instance from any <a>Typeable2</a>
--   instance.
typeOf1Default :: (Typeable2 t, Typeable a) => t a b -> TypeRep

-- | For defining a <a>Typeable2</a> instance from any <a>Typeable3</a>
--   instance.
typeOf2Default :: (Typeable3 t, Typeable a) => t a b c -> TypeRep

-- | For defining a <a>Typeable3</a> instance from any <a>Typeable4</a>
--   instance.
typeOf3Default :: (Typeable4 t, Typeable a) => t a b c d -> TypeRep

-- | For defining a <a>Typeable4</a> instance from any <a>Typeable5</a>
--   instance.
typeOf4Default :: (Typeable5 t, Typeable a) => t a b c d e -> TypeRep

-- | For defining a <a>Typeable5</a> instance from any <a>Typeable6</a>
--   instance.
typeOf5Default :: (Typeable6 t, Typeable a) => t a b c d e f -> TypeRep

-- | For defining a <a>Typeable6</a> instance from any <a>Typeable7</a>
--   instance.
typeOf6Default :: (Typeable7 t, Typeable a) => t a b c d e f g -> TypeRep

-- | The class <a>Typeable</a> allows a concrete representation of a type
--   to be calculated.
class Typeable a
typeOf :: Typeable a => a -> TypeRep

-- | Variant for unary type constructors
class Typeable1 t
typeOf1 :: Typeable1 t => t a -> TypeRep

-- | Variant for binary type constructors
class Typeable2 t
typeOf2 :: Typeable2 t => t a b -> TypeRep

-- | Variant for 3-ary type constructors
class Typeable3 t
typeOf3 :: Typeable3 t => t a b c -> TypeRep

-- | Variant for 4-ary type constructors
class Typeable4 t
typeOf4 :: Typeable4 t => t a b c d -> TypeRep

-- | Variant for 5-ary type constructors
class Typeable5 t
typeOf5 :: Typeable5 t => t a b c d e -> TypeRep

-- | Variant for 6-ary type constructors
class Typeable6 t
typeOf6 :: Typeable6 t => t a b c d e f -> TypeRep

-- | Variant for 7-ary type constructors
class Typeable7 t
typeOf7 :: Typeable7 t => t a b c d e f g -> TypeRep

-- | A special case of <a>mkTyConApp</a>, which applies the function type
--   constructor to a pair of types.
mkFunTy :: TypeRep -> TypeRep -> TypeRep

-- | Splits a type constructor application
splitTyConApp :: TypeRep -> (TyCon, [TypeRep])

-- | Applies a type to a function type. Returns: <tt><a>Just</a> u</tt> if
--   the first argument represents a function of type <tt>t -&gt; u</tt>
--   and the second argument represents a function of type <tt>t</tt>.
--   Otherwise, returns <a>Nothing</a>.
funResultTy :: TypeRep -> TypeRep -> Maybe TypeRep

-- | Observe the argument types of a type representation
typeRepArgs :: TypeRep -> [TypeRep]
showsTypeRep :: TypeRep -> ShowS

-- | Observe string encoding of a type representation

-- | <i>Deprecated: renamed to tyConName; tyConModule and tyConPackage are
--   also available. </i>
tyConString :: TyCon -> String
listTc :: TyCon
funTc :: TyCon
instance [overlap ok] Typeable TypeRep
instance [overlap ok] Typeable TyCon
instance [overlap ok] Typeable Word64
instance [overlap ok] Typeable Word32
instance [overlap ok] Typeable Word16
instance [overlap ok] Typeable Word8
instance [overlap ok] Typeable Int64
instance [overlap ok] Typeable Int32
instance [overlap ok] Typeable Int16
instance [overlap ok] Typeable Int8
instance [overlap ok] Typeable Ordering
instance [overlap ok] Typeable Integer
instance [overlap ok] Typeable Word
instance [overlap ok] Typeable Int
instance [overlap ok] Typeable Double
instance [overlap ok] Typeable Float
instance [overlap ok] Typeable Char
instance [overlap ok] Typeable Bool
instance [overlap ok] Typeable1 IORef
instance [overlap ok] Typeable1 StablePtr
instance [overlap ok] Typeable1 FunPtr
instance [overlap ok] Typeable1 Ptr
instance [overlap ok] Typeable7 (,,,,,,)
instance [overlap ok] Typeable6 (,,,,,)
instance [overlap ok] Typeable5 (,,,,)
instance [overlap ok] Typeable4 (,,,)
instance [overlap ok] Typeable3 (,,)
instance [overlap ok] Typeable2 (,)
instance [overlap ok] Typeable3 STArray
instance [overlap ok] Typeable2 STRef
instance [overlap ok] Typeable2 ST
instance [overlap ok] Typeable2 IOArray
instance [overlap ok] Typeable2 Array
instance [overlap ok] Typeable1 MVar
instance [overlap ok] Typeable1 IO
instance [overlap ok] Typeable1 Ratio
instance [overlap ok] Typeable1 Maybe
instance [overlap ok] Typeable1 []
instance [overlap ok] Typeable ()
instance [overlap ok] Typeable RealWorld
instance [overlap ok] Typeable2 (->)
instance [overlap ok] Show TyCon
instance [overlap ok] Show TypeRep
instance [overlap ok] (Typeable7 s, Typeable a) => Typeable6 (s a)
instance [overlap ok] (Typeable6 s, Typeable a) => Typeable5 (s a)
instance [overlap ok] (Typeable5 s, Typeable a) => Typeable4 (s a)
instance [overlap ok] (Typeable4 s, Typeable a) => Typeable3 (s a)
instance [overlap ok] (Typeable3 s, Typeable a) => Typeable2 (s a)
instance [overlap ok] (Typeable2 s, Typeable a) => Typeable1 (s a)
instance [overlap ok] (Typeable1 s, Typeable a) => Typeable (s a)
instance [overlap ok] Ord TyCon
instance [overlap ok] Eq TyCon
instance [overlap ok] Ord TypeRep
instance [overlap ok] Eq TypeRep


-- | The <a>Typeable</a> class reifies types to some extent by associating
--   type representations to types. These type representations can be
--   compared, and one can in turn define a type-safe cast operation. To
--   this end, an unsafe cast is guarded by a test for type
--   (representation) equivalence. The module <a>Data.Dynamic</a> uses
--   Typeable for an implementation of dynamics. The module
--   <a>Data.Data</a> uses Typeable and type-safe cast (but not dynamics)
--   to support the "Scrap your boilerplate" style of generic programming.
module Data.Typeable

-- | The class <a>Typeable</a> allows a concrete representation of a type
--   to be calculated.
class Typeable a
typeOf :: Typeable a => a -> TypeRep

-- | The type-safe cast operation
cast :: (Typeable a, Typeable b) => a -> Maybe b

-- | A flexible variation parameterised in a type constructor
gcast :: (Typeable a, Typeable b) => c a -> Maybe (c b)

-- | A concrete representation of a (monomorphic) type. <a>TypeRep</a>
--   supports reasonably efficient equality.
data TypeRep
showsTypeRep :: TypeRep -> ShowS

-- | An abstract representation of a type constructor. <a>TyCon</a> objects
--   can be built using <a>mkTyCon</a>.
data TyCon

-- | Observe string encoding of a type representation

-- | <i>Deprecated: renamed to tyConName; tyConModule and tyConPackage are
--   also available. </i>
tyConString :: TyCon -> String
tyConPackage :: TyCon -> String
tyConModule :: TyCon -> String
tyConName :: TyCon -> String

-- | Backwards-compatible API

-- | <i>Deprecated: either derive Typeable, or use mkTyCon3 instead </i>
mkTyCon :: String -> TyCon

-- | Builds a <a>TyCon</a> object representing a type constructor. An
--   implementation of <a>Data.Typeable</a> should ensure that the
--   following holds:
--   
--   <pre>
--   A==A' ^ B==B' ^ C==C' ==&gt; mkTyCon A B C == mkTyCon A' B' C'
--   </pre>
mkTyCon3 :: String -> String -> String -> TyCon

-- | Applies a type constructor to a sequence of types
mkTyConApp :: TyCon -> [TypeRep] -> TypeRep

-- | Adds a TypeRep argument to a TypeRep.
mkAppTy :: TypeRep -> TypeRep -> TypeRep

-- | A special case of <a>mkTyConApp</a>, which applies the function type
--   constructor to a pair of types.
mkFunTy :: TypeRep -> TypeRep -> TypeRep

-- | Splits a type constructor application
splitTyConApp :: TypeRep -> (TyCon, [TypeRep])

-- | Applies a type to a function type. Returns: <tt><a>Just</a> u</tt> if
--   the first argument represents a function of type <tt>t -&gt; u</tt>
--   and the second argument represents a function of type <tt>t</tt>.
--   Otherwise, returns <a>Nothing</a>.
funResultTy :: TypeRep -> TypeRep -> Maybe TypeRep

-- | Observe the type constructor of a type representation
typeRepTyCon :: TypeRep -> TyCon

-- | Observe the argument types of a type representation
typeRepArgs :: TypeRep -> [TypeRep]

-- | (DEPRECATED) Returns a unique key associated with a <a>TypeRep</a>.
--   This function is deprecated because <a>TypeRep</a> itself is now an
--   instance of <a>Ord</a>, so mappings can be made directly with
--   <a>TypeRep</a> as the key.

-- | <i>Deprecated: TypeRep itself is now an instance of Ord </i>
typeRepKey :: TypeRep -> IO TypeRepKey
data TypeRepKey

-- | Variant for unary type constructors
class Typeable1 t
typeOf1 :: Typeable1 t => t a -> TypeRep

-- | Variant for binary type constructors
class Typeable2 t
typeOf2 :: Typeable2 t => t a b -> TypeRep

-- | Variant for 3-ary type constructors
class Typeable3 t
typeOf3 :: Typeable3 t => t a b c -> TypeRep

-- | Variant for 4-ary type constructors
class Typeable4 t
typeOf4 :: Typeable4 t => t a b c d -> TypeRep

-- | Variant for 5-ary type constructors
class Typeable5 t
typeOf5 :: Typeable5 t => t a b c d e -> TypeRep

-- | Variant for 6-ary type constructors
class Typeable6 t
typeOf6 :: Typeable6 t => t a b c d e f -> TypeRep

-- | Variant for 7-ary type constructors
class Typeable7 t
typeOf7 :: Typeable7 t => t a b c d e f g -> TypeRep

-- | Cast for * -&gt; *
gcast1 :: (Typeable1 t, Typeable1 t') => c (t a) -> Maybe (c (t' a))

-- | Cast for * -&gt; * -&gt; *
gcast2 :: (Typeable2 t, Typeable2 t') => c (t a b) -> Maybe (c (t' a b))

-- | For defining a <a>Typeable</a> instance from any <a>Typeable1</a>
--   instance.
typeOfDefault :: (Typeable1 t, Typeable a) => t a -> TypeRep

-- | For defining a <a>Typeable1</a> instance from any <a>Typeable2</a>
--   instance.
typeOf1Default :: (Typeable2 t, Typeable a) => t a b -> TypeRep

-- | For defining a <a>Typeable2</a> instance from any <a>Typeable3</a>
--   instance.
typeOf2Default :: (Typeable3 t, Typeable a) => t a b c -> TypeRep

-- | For defining a <a>Typeable3</a> instance from any <a>Typeable4</a>
--   instance.
typeOf3Default :: (Typeable4 t, Typeable a) => t a b c d -> TypeRep

-- | For defining a <a>Typeable4</a> instance from any <a>Typeable5</a>
--   instance.
typeOf4Default :: (Typeable5 t, Typeable a) => t a b c d e -> TypeRep

-- | For defining a <a>Typeable5</a> instance from any <a>Typeable6</a>
--   instance.
typeOf5Default :: (Typeable6 t, Typeable a) => t a b c d e f -> TypeRep

-- | For defining a <a>Typeable6</a> instance from any <a>Typeable7</a>
--   instance.
typeOf6Default :: (Typeable7 t, Typeable a) => t a b c d e f g -> TypeRep
instance [overlap ok] Eq TypeRepKey
instance [overlap ok] Ord TypeRepKey


-- | The Either type, and associated operations.
module Data.Either

-- | The <a>Either</a> type represents values with two possibilities: a
--   value of type <tt><a>Either</a> a b</tt> is either <tt><a>Left</a>
--   a</tt> or <tt><a>Right</a> b</tt>.
--   
--   The <a>Either</a> type is sometimes used to represent a value which is
--   either correct or an error; by convention, the <a>Left</a> constructor
--   is used to hold an error value and the <a>Right</a> constructor is
--   used to hold a correct value (mnemonic: "right" also means "correct").
data Either a b
Left :: a -> Either a b
Right :: b -> Either a b

-- | Case analysis for the <a>Either</a> type. If the value is
--   <tt><a>Left</a> a</tt>, apply the first function to <tt>a</tt>; if it
--   is <tt><a>Right</a> b</tt>, apply the second function to <tt>b</tt>.
either :: (a -> c) -> (b -> c) -> Either a b -> c

-- | Extracts from a list of <a>Either</a> all the <a>Left</a> elements All
--   the <a>Left</a> elements are extracted in order.
lefts :: [Either a b] -> [a]

-- | Extracts from a list of <a>Either</a> all the <a>Right</a> elements
--   All the <a>Right</a> elements are extracted in order.
rights :: [Either a b] -> [b]

-- | Partitions a list of <a>Either</a> into two lists All the <a>Left</a>
--   elements are extracted, in order, to the first component of the
--   output. Similarly the <a>Right</a> elements are extracted to the
--   second component of the output.
partitionEithers :: [Either a b] -> ([a], [b])
instance Typeable2 Either
instance (Eq a, Eq b) => Eq (Either a b)
instance (Ord a, Ord b) => Ord (Either a b)
instance (Read a, Read b) => Read (Either a b)
instance (Show a, Show b) => Show (Either a b)
instance Monad (Either e)
instance Functor (Either a)

module GHC.Generics

-- | Void: used for datatypes without constructors
data V1 p

-- | Unit: used for constructors without arguments
data U1 p
U1 :: U1 p

-- | Used for marking occurrences of the parameter
newtype Par1 p
Par1 :: p -> Par1 p
unPar1 :: Par1 p -> p

-- | Recursive calls of kind * -&gt; *
newtype Rec1 f p
Rec1 :: f p -> Rec1 f p
unRec1 :: Rec1 f p -> f p

-- | Constants, additional parameters and recursion of kind *
newtype K1 i c p
K1 :: c -> K1 i c p
unK1 :: K1 i c p -> c

-- | Meta-information (constructor names, etc.)
newtype M1 i c f p
M1 :: f p -> M1 i c f p
unM1 :: M1 i c f p -> f p

-- | Sums: encode choice between constructors
data (:+:) f g p
L1 :: (f p) -> :+: f g p
R1 :: (g p) -> :+: f g p

-- | Products: encode multiple arguments to constructors
data (:*:) f g p
(:*:) :: f p -> g p -> :*: f g p

-- | Composition of functors
newtype (:.:) f g p
Comp1 :: f (g p) -> :.: f g p
unComp1 :: :.: f g p -> f (g p)

-- | Type synonym for encoding recursion (of kind *)
type Rec0 = K1 R

-- | Type synonym for encoding parameters (other than the last)

-- | <i>Deprecated: Par0 is no longer used; use Rec0 instead </i>
type Par0 = K1 P

-- | Tag for K1: recursion (of kind *)
data R

-- | Tag for K1: parameters (other than the last)

-- | <i>Deprecated: P is no longer used; use R instead </i>
data P

-- | Type synonym for encoding meta-information for datatypes
type D1 = M1 D

-- | Type synonym for encoding meta-information for constructors
type C1 = M1 C

-- | Type synonym for encoding meta-information for record selectors
type S1 = M1 S

-- | Tag for M1: datatype
data D

-- | Tag for M1: constructor
data C

-- | Tag for M1: record selector
data S

-- | Class for datatypes that represent datatypes
class Datatype d
datatypeName :: Datatype d => t d (f :: * -> *) a -> [Char]
moduleName :: Datatype d => t d (f :: * -> *) a -> [Char]

-- | Class for datatypes that represent data constructors
class Constructor c where conFixity _ = Prefix conIsRecord _ = False
conName :: Constructor c => t c (f :: * -> *) a -> [Char]
conFixity :: Constructor c => t c (f :: * -> *) a -> Fixity
conIsRecord :: Constructor c => t c (f :: * -> *) a -> Bool

-- | Class for datatypes that represent records
class Selector s
selName :: Selector s => t s (f :: * -> *) a -> [Char]

-- | Used for constructor fields without a name
data NoSelector

-- | Datatype to represent the fixity of a constructor. An infix |
--   declaration directly corresponds to an application of <a>Infix</a>.
data Fixity
Prefix :: Fixity
Infix :: Associativity -> Int -> Fixity

-- | Datatype to represent the associativity of a constructor
data Associativity
LeftAssociative :: Associativity
RightAssociative :: Associativity
NotAssociative :: Associativity

-- | Datatype to represent the arity of a tuple.
data Arity
NoArity :: Arity
Arity :: Int -> Arity

-- | Get the precedence of a fixity value.
prec :: Fixity -> Int

-- | Representable types of kind *. This class is derivable in GHC with the
--   DeriveGeneric flag on.
class Generic a where type family Rep a :: * -> *
from :: Generic a => a -> (Rep a) x
to :: Generic a => (Rep a) x -> a

-- | Representable types of kind * -&gt; *. This class is derivable in GHC
--   with the DeriveGeneric flag on.
class Generic1 f where type family Rep1 f :: * -> *
from1 :: Generic1 f => f a -> (Rep1 f) a
to1 :: Generic1 f => (Rep1 f) a -> f a
instance Generic1 ((,,,,,,) a b c d e f)
instance Generic1 ((,,,,,) a b c d e)
instance Generic1 ((,,,,) a b c d)
instance Generic1 ((,,,) a b c)
instance Generic1 ((,,) a b)
instance Generic1 ((,) a)
instance Generic1 (Either a)
instance Generic1 Maybe
instance Generic1 []
instance Generic (a, b, c, d, e, f, g)
instance Generic (a, b, c, d, e, f)
instance Generic (a, b, c, d, e)
instance Generic (a, b, c, d)
instance Generic (a, b, c)
instance Generic (a, b)
instance Generic ()
instance Generic Ordering
instance Generic Bool
instance Generic (Either a b)
instance Generic (Maybe a)
instance Generic [a]
instance Eq Arity
instance Show Arity
instance Ord Arity
instance Read Arity
instance Eq Associativity
instance Show Associativity
instance Ord Associativity
instance Read Associativity
instance Eq Fixity
instance Show Fixity
instance Ord Fixity
instance Read Fixity
instance Datatype D1(,,,,,,)
instance Constructor C1_0(,,,,,,)
instance Datatype D1(,,,,,)
instance Constructor C1_0(,,,,,)
instance Datatype D1(,,,,)
instance Constructor C1_0(,,,,)
instance Datatype D1(,,,)
instance Constructor C1_0(,,,)
instance Datatype D1(,,)
instance Constructor C1_0(,,)
instance Datatype D1(,)
instance Constructor C1_0(,)
instance Datatype D1Either
instance Constructor C1_0Either
instance Constructor C1_1Either
instance Datatype D1Maybe
instance Constructor C1_0Maybe
instance Constructor C1_1Maybe
instance Datatype D1[]
instance Constructor C1_0[]
instance Constructor C1_1[]
instance Datatype D1()
instance Constructor C1_0()
instance Datatype D1Ordering
instance Constructor C1_0Ordering
instance Constructor C1_1Ordering
instance Constructor C1_2Ordering
instance Datatype D1Bool
instance Constructor C1_0Bool
instance Constructor C1_1Bool
instance Generic Char
instance Constructor C_Char
instance Datatype D_Char
instance Generic Double
instance Constructor C_Double
instance Datatype D_Double
instance Generic Float
instance Constructor C_Float
instance Datatype D_Float
instance Generic Int
instance Constructor C_Int
instance Datatype D_Int
instance Selector NoSelector


-- | Converting strings to values.
--   
--   The <a>Text.Read</a> library is the canonical library to import for
--   <a>Read</a>-class facilities. For GHC only, it offers an extended and
--   much improved <a>Read</a> class, which constitutes a proposed
--   alternative to the Haskell 98 <a>Read</a>. In particular, writing
--   parsers is easier, and the parsers are much more efficient.
module Text.Read

-- | Parsing of <a>String</a>s, producing values.
--   
--   Minimal complete definition: <a>readsPrec</a> (or, for GHC only,
--   <a>readPrec</a>)
--   
--   Derived instances of <a>Read</a> make the following assumptions, which
--   derived instances of <a>Show</a> obey:
--   
--   <ul>
--   <li>If the constructor is defined to be an infix operator, then the
--   derived <a>Read</a> instance will parse only infix applications of the
--   constructor (not the prefix form).</li>
--   <li>Associativity is not used to reduce the occurrence of parentheses,
--   although precedence may be.</li>
--   <li>If the constructor is defined using record syntax, the derived
--   <a>Read</a> will parse only the record-syntax form, and furthermore,
--   the fields must be given in the same order as the original
--   declaration.</li>
--   <li>The derived <a>Read</a> instance allows arbitrary Haskell
--   whitespace between tokens of the input string. Extra parentheses are
--   also allowed.</li>
--   </ul>
--   
--   For example, given the declarations
--   
--   <pre>
--   infixr 5 :^:
--   data Tree a =  Leaf a  |  Tree a :^: Tree a
--   </pre>
--   
--   the derived instance of <a>Read</a> in Haskell 98 is equivalent to
--   
--   <pre>
--   instance (Read a) =&gt; Read (Tree a) where
--   
--           readsPrec d r =  readParen (d &gt; app_prec)
--                            (\r -&gt; [(Leaf m,t) |
--                                    ("Leaf",s) &lt;- lex r,
--                                    (m,t) &lt;- readsPrec (app_prec+1) s]) r
--   
--                         ++ readParen (d &gt; up_prec)
--                            (\r -&gt; [(u:^:v,w) |
--                                    (u,s) &lt;- readsPrec (up_prec+1) r,
--                                    (":^:",t) &lt;- lex s,
--                                    (v,w) &lt;- readsPrec (up_prec+1) t]) r
--   
--             where app_prec = 10
--                   up_prec = 5
--   </pre>
--   
--   Note that right-associativity of <tt>:^:</tt> is unused.
--   
--   The derived instance in GHC is equivalent to
--   
--   <pre>
--   instance (Read a) =&gt; Read (Tree a) where
--   
--           readPrec = parens $ (prec app_prec $ do
--                                    Ident "Leaf" &lt;- lexP
--                                    m &lt;- step readPrec
--                                    return (Leaf m))
--   
--                        +++ (prec up_prec $ do
--                                    u &lt;- step readPrec
--                                    Symbol ":^:" &lt;- lexP
--                                    v &lt;- step readPrec
--                                    return (u :^: v))
--   
--             where app_prec = 10
--                   up_prec = 5
--   
--           readListPrec = readListPrecDefault
--   </pre>
class Read a where readsPrec = readPrec_to_S readPrec readList = readPrec_to_S (list readPrec) 0 readPrec = readS_to_Prec readsPrec readListPrec = readS_to_Prec (\ _ -> readList)
readsPrec :: Read a => Int -> ReadS a
readList :: Read a => ReadS [a]
readPrec :: Read a => ReadPrec a
readListPrec :: Read a => ReadPrec [a]

-- | A parser for a type <tt>a</tt>, represented as a function that takes a
--   <a>String</a> and returns a list of possible parses as
--   <tt>(a,<a>String</a>)</tt> pairs.
--   
--   Note that this kind of backtracking parser is very inefficient;
--   reading a large structure may be quite slow (cf <a>ReadP</a>).
type ReadS a = String -> [(a, String)]

-- | equivalent to <a>readsPrec</a> with a precedence of 0.
reads :: Read a => ReadS a

-- | The <a>read</a> function reads input from a string, which must be
--   completely consumed by the input process.
read :: Read a => String -> a

-- | <tt><a>readParen</a> <a>True</a> p</tt> parses what <tt>p</tt> parses,
--   but surrounded with parentheses.
--   
--   <tt><a>readParen</a> <a>False</a> p</tt> parses what <tt>p</tt>
--   parses, but optionally surrounded with parentheses.
readParen :: Bool -> ReadS a -> ReadS a

-- | The <a>lex</a> function reads a single lexeme from the input,
--   discarding initial white space, and returning the characters that
--   constitute the lexeme. If the input string contains only white space,
--   <a>lex</a> returns a single successful `lexeme' consisting of the
--   empty string. (Thus <tt><a>lex</a> "" = [("","")]</tt>.) If there is
--   no legal lexeme at the beginning of the input string, <a>lex</a> fails
--   (i.e. returns <tt>[]</tt>).
--   
--   This lexer is not completely faithful to the Haskell lexical syntax in
--   the following respects:
--   
--   <ul>
--   <li>Qualified names are not handled properly</li>
--   <li>Octal and hexadecimal numerics are not recognized as a single
--   token</li>
--   <li>Comments are not treated properly</li>
--   </ul>
lex :: ReadS String

-- | Haskell lexemes.
data Lexeme

-- | Character literal
Char :: Char -> Lexeme

-- | String literal, with escapes interpreted
String :: String -> Lexeme

-- | Punctuation or reserved symbol, e.g. <tt>(</tt>, <tt>::</tt>
Punc :: String -> Lexeme

-- | Haskell identifier, e.g. <tt>foo</tt>, <tt>Baz</tt>
Ident :: String -> Lexeme

-- | Haskell symbol, e.g. <tt>&gt;&gt;</tt>, <tt>:%</tt>
Symbol :: String -> Lexeme
Number :: Number -> Lexeme
EOF :: Lexeme

-- | Parse a single lexeme
lexP :: ReadPrec Lexeme

-- | <tt>(parens p)</tt> parses "P", "(P0)", "((P0))", etc, where
--   <tt>p</tt> parses "P" in the current precedence context and parses
--   "P0" in precedence context zero
parens :: ReadPrec a -> ReadPrec a

-- | A possible replacement definition for the <a>readList</a> method (GHC
--   only). This is only needed for GHC, and even then only for <a>Read</a>
--   instances where <a>readListPrec</a> isn't defined as
--   <a>readListPrecDefault</a>.
readListDefault :: Read a => ReadS [a]

-- | A possible replacement definition for the <a>readListPrec</a> method,
--   defined using <a>readPrec</a> (GHC only).
readListPrecDefault :: Read a => ReadPrec [a]

-- | Parse a string using the <a>Read</a> instance. Succeeds if there is
--   exactly one valid result. A <a>Left</a> value indicates a parse error.
readEither :: Read a => String -> Either String a

-- | Parse a string using the <a>Read</a> instance. Succeeds if there is
--   exactly one valid result.
readMaybe :: Read a => String -> Maybe a


-- | FFI datatypes and operations that use or require concurrency (GHC
--   only).
module Foreign.Concurrent

-- | Turns a plain memory reference into a foreign object by associating a
--   finalizer - given by the monadic operation - with the reference. The
--   finalizer will be executed after the last reference to the foreign
--   object is dropped. There is no guarantee of promptness, and in fact
--   there is no guarantee that the finalizer will eventually run at all.
newForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)

-- | This function adds a finalizer to the given <a>ForeignPtr</a>. The
--   finalizer will run after the last reference to the foreign object is
--   dropped, but <i>before</i> all previously registered finalizers for
--   the same object.
addForeignPtrFinalizer :: ForeignPtr a -> IO () -> IO ()


-- | The Dynamic interface provides basic support for dynamic types.
--   
--   Operations for injecting values of arbitrary type into a dynamically
--   typed value, Dynamic, are provided, together with operations for
--   converting dynamic values into a concrete (monomorphic) type.
module Data.Dynamic

-- | A value of type <a>Dynamic</a> is an object encapsulated together with
--   its type.
--   
--   A <a>Dynamic</a> may only represent a monomorphic value; an attempt to
--   create a value of type <a>Dynamic</a> from a polymorphically-typed
--   expression will result in an ambiguity error (see <a>toDyn</a>).
--   
--   <a>Show</a>ing a value of type <a>Dynamic</a> returns a pretty-printed
--   representation of the object's type; useful for debugging.
data Dynamic

-- | Converts an arbitrary value into an object of type <a>Dynamic</a>.
--   
--   The type of the object must be an instance of <a>Typeable</a>, which
--   ensures that only monomorphically-typed objects may be converted to
--   <a>Dynamic</a>. To convert a polymorphic object into <a>Dynamic</a>,
--   give it a monomorphic type signature. For example:
--   
--   <pre>
--   toDyn (id :: Int -&gt; Int)
--   </pre>
toDyn :: Typeable a => a -> Dynamic

-- | Converts a <a>Dynamic</a> object back into an ordinary Haskell value
--   of the correct type. See also <a>fromDynamic</a>.
fromDyn :: Typeable a => Dynamic -> a -> a

-- | Converts a <a>Dynamic</a> object back into an ordinary Haskell value
--   of the correct type. See also <a>fromDyn</a>.
fromDynamic :: Typeable a => Dynamic -> Maybe a
dynApply :: Dynamic -> Dynamic -> Maybe Dynamic
dynApp :: Dynamic -> Dynamic -> Dynamic
dynTypeRep :: Dynamic -> TypeRep
instance Typeable Dynamic
instance Exception Dynamic
instance Show Dynamic


-- | Mutable references in the IO monad.
module Data.IORef

-- | A mutable variable in the <a>IO</a> monad
data IORef a

-- | Build a new <a>IORef</a>
newIORef :: a -> IO (IORef a)

-- | Read the value of an <a>IORef</a>
readIORef :: IORef a -> IO a

-- | Write a new value into an <a>IORef</a>
writeIORef :: IORef a -> a -> IO ()

-- | Mutate the contents of an <a>IORef</a>.
--   
--   Be warned that <a>modifyIORef</a> does not apply the function
--   strictly. This means if the program calls <a>modifyIORef</a> many
--   times, but seldomly uses the value, thunks will pile up in memory
--   resulting in a space leak. This is a common mistake made when using an
--   IORef as a counter. For example, the following will likely produce a
--   stack overflow:
--   
--   <pre>
--   ref &lt;- newIORef 0
--   replicateM_ 1000000 $ modifyIORef ref (+1)
--   readIORef ref &gt;&gt;= print
--   </pre>
--   
--   To avoid this problem, use <a>modifyIORef'</a> instead.
modifyIORef :: IORef a -> (a -> a) -> IO ()

-- | Strict version of <a>modifyIORef</a>
modifyIORef' :: IORef a -> (a -> a) -> IO ()

-- | Atomically modifies the contents of an <a>IORef</a>.
--   
--   This function is useful for using <a>IORef</a> in a safe way in a
--   multithreaded program. If you only have one <a>IORef</a>, then using
--   <a>atomicModifyIORef</a> to access and modify it will prevent race
--   conditions.
--   
--   Extending the atomicity to multiple <a>IORef</a>s is problematic, so
--   it is recommended that if you need to do anything more complicated
--   then using <a>MVar</a> instead is a good idea.
--   
--   <a>atomicModifyIORef</a> does not apply the function strictly. This is
--   important to know even if all you are doing is replacing the value.
--   For example, this will leak memory:
--   
--   <pre>
--   ref &lt;- newIORef '1'
--   forever $ atomicModifyIORef ref (\_ -&gt; ('2', ()))
--   </pre>
--   
--   Use <a>atomicModifyIORef'</a> or <a>atomicWriteIORef</a> to avoid this
--   problem.
atomicModifyIORef :: IORef a -> (a -> (a, b)) -> IO b

-- | Strict version of <a>atomicModifyIORef</a>. This forces both the value
--   stored in the <a>IORef</a> as well as the value returned.
atomicModifyIORef' :: IORef a -> (a -> (a, b)) -> IO b

-- | Variant of <a>writeIORef</a> with the "barrier to reordering" property
--   that <a>atomicModifyIORef</a> has.
atomicWriteIORef :: IORef a -> a -> IO ()

-- | Make a <a>Weak</a> pointer to an <a>IORef</a>, using the second
--   argument as a finalizer to run when <a>IORef</a> is garbage-collected
mkWeakIORef :: IORef a -> IO () -> IO (Weak (IORef a))


-- | The <tt>String</tt> type and associated operations.
module Data.String

-- | A <a>String</a> is a list of characters. String constants in Haskell
--   are values of type <a>String</a>.
type String = [Char]

-- | Class for string-like datastructures; used by the overloaded string
--   extension (-foverloaded-strings in GHC).
class IsString a
fromString :: IsString a => String -> a

-- | <a>lines</a> breaks a string up into a list of strings at newline
--   characters. The resulting strings do not contain newlines.
lines :: String -> [String]

-- | <a>words</a> breaks a string up into a list of words, which were
--   delimited by white space.
words :: String -> [String]

-- | <a>unlines</a> is an inverse operation to <a>lines</a>. It joins
--   lines, after appending a terminating newline to each.
unlines :: [String] -> String

-- | <a>unwords</a> is an inverse operation to <a>words</a>. It joins words
--   with separating spaces.
unwords :: [String] -> String
instance IsString [Char]


-- | This module is an internal GHC module. It declares the constants used
--   in the implementation of type-level natural numbers. The programmer
--   interface for workin with type-level naturals should be defined in a
--   separate library.
module GHC.TypeLits

-- | This is the *kind* of type-level natural numbers.
data Nat

-- | This is the *kind* of type-level symbols.
data Symbol

-- | The class <a>SingI</a> provides a "smart" constructor for singleton
--   types. There are built-in instances for the singleton types
--   corresponding to type literals.
class SingI a
sing :: SingI a => Sing a

-- | A class that converts singletons of a given kind into values of some
--   representation type (i.e., we <a>forget</a> the extra information
--   carried by the singletons, and convert them to ordinary values).
--   
--   Note that <a>fromSing</a> is overloaded based on the <i>kind</i> of
--   the values and not their type---all types of a given kind are
--   processed by the same instances.
class kparam ~ Kind => SingE (kparam :: k) rep | kparam -> rep
fromSing :: SingE kparam rep => Sing (a :: k) -> rep

-- | A convenience class, useful when we need to both introduce and
--   eliminate a given singleton value. Users should never need to define
--   instances of this classes.
class (SingI a, SingE (Kind :: k) rep) => SingRep (a :: k) rep | a -> rep
unsafeSingNat :: Integer -> Sing (n :: Nat)
unsafeSingSymbol :: String -> Sing (n :: Symbol)

-- | A type synonym useful for passing kinds as parameters.
type Kind = Any

-- | A convenience function useful when we need to name a singleton value
--   multiple times. Without this function, each use of <a>sing</a> could
--   potentially refer to a different singleton, and one has to use type
--   signatures to ensure that they are the same.
withSing :: SingI a => (Sing a -> b) -> b

-- | A convenience function that names a singleton satisfying a certain
--   property. If the singleton does not satisfy the property, then the
--   function returns <a>Nothing</a>. The property is expressed in terms of
--   the underlying representation of the singleton.
singThat :: SingRep a rep => (rep -> Bool) -> Maybe (Sing a)

-- | Comparsion of type-level naturals.
class (<=) (m :: Nat) (n :: Nat)

-- | Addition of type-level naturals.

-- | Multiplication of type-level naturals.

-- | Exponentiation of type-level naturals.
isZero :: Sing n -> IsZero n
data IsZero :: Nat -> *
IsZero :: IsZero 0
IsSucc :: !(Sing n) -> IsZero (n + 1)
isEven :: Sing n -> IsEven n
data IsEven :: Nat -> *
IsEvenZero :: IsEven 0
IsEven :: !(Sing (n + 1)) -> IsEven ((2 * n) + 2)
IsOdd :: !(Sing n) -> IsEven ((2 * n) + 1)
instance Show (IsEven n)
instance Show (IsZero n)
instance (SingRep k a rep, Read rep, Eq rep) => Read (Sing k a)
instance (SingE k (Kind k) rep, Show rep) => Show (Sing k a)
instance (SingI k a, SingE k (Kind k) rep) => SingRep k a rep
instance SingE Symbol (Kind Symbol) String
instance SingE Nat (Kind Nat) Integer

module GHC.IP

-- | The syntax <tt>?x :: a</tt> is desugared into <tt>IP <a>x</a> a</tt>
class IP (x :: Symbol) a | x -> a
ip :: IP x a => a


-- | This module provides typed pointers to foreign data. It is part of the
--   Foreign Function Interface (FFI) and will normally be imported via the
--   <a>Foreign</a> module.
module Foreign.Ptr

-- | A value of type <tt><a>Ptr</a> a</tt> represents a pointer to an
--   object, or an array of objects, which may be marshalled to or from
--   Haskell values of type <tt>a</tt>.
--   
--   The type <tt>a</tt> will often be an instance of class <a>Storable</a>
--   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 <tt>struct</tt>.
data Ptr a

-- | The constant <a>nullPtr</a> contains a distinguished value of
--   <a>Ptr</a> that is not associated with a valid memory location.
nullPtr :: Ptr a

-- | The <a>castPtr</a> function casts a pointer from one type to another.
castPtr :: Ptr a -> Ptr b

-- | Advances the given address by the given offset in bytes.
plusPtr :: Ptr a -> Int -> Ptr b

-- | Given an arbitrary address and an alignment constraint,
--   <a>alignPtr</a> yields the next higher address that fulfills the
--   alignment constraint. An alignment constraint <tt>x</tt> is fulfilled
--   by any address divisible by <tt>x</tt>. This operation is idempotent.
alignPtr :: Ptr a -> Int -> Ptr a

-- | Computes the offset required to get from the second to the first
--   argument. We have
--   
--   <pre>
--   p2 == p1 `plusPtr` (p2 `minusPtr` p1)
--   </pre>
minusPtr :: Ptr a -> Ptr b -> Int

-- | A value of type <tt><a>FunPtr</a> a</tt> is a pointer to a function
--   callable from foreign code. The type <tt>a</tt> will normally be a
--   <i>foreign type</i>, a function type with zero or more arguments where
--   
--   <ul>
--   <li>the argument types are <i>marshallable foreign types</i>, i.e.
--   <a>Char</a>, <a>Int</a>, <a>Double</a>, <a>Float</a>, <a>Bool</a>,
--   <a>Int8</a>, <a>Int16</a>, <a>Int32</a>, <a>Int64</a>, <a>Word8</a>,
--   <a>Word16</a>, <a>Word32</a>, <a>Word64</a>, <tt><a>Ptr</a> a</tt>,
--   <tt><a>FunPtr</a> a</tt>, <tt><a>StablePtr</a> a</tt> or a renaming of
--   any of these using <tt>newtype</tt>.</li>
--   <li>the return type is either a marshallable foreign type or has the
--   form <tt><a>IO</a> t</tt> where <tt>t</tt> is a marshallable foreign
--   type or <tt>()</tt>.</li>
--   </ul>
--   
--   A value of type <tt><a>FunPtr</a> a</tt> may be a pointer to a foreign
--   function, either returned by another foreign function or imported with
--   a a static address import like
--   
--   <pre>
--   foreign import ccall "stdlib.h &amp;free"
--     p_free :: FunPtr (Ptr a -&gt; IO ())
--   </pre>
--   
--   or a pointer to a Haskell function created using a <i>wrapper</i> stub
--   declared to produce a <a>FunPtr</a> of the correct type. For example:
--   
--   <pre>
--   type Compare = Int -&gt; Int -&gt; Bool
--   foreign import ccall "wrapper"
--     mkCompare :: Compare -&gt; IO (FunPtr Compare)
--   </pre>
--   
--   Calls to wrapper stubs like <tt>mkCompare</tt> allocate storage, which
--   should be released with <a>freeHaskellFunPtr</a> when no longer
--   required.
--   
--   To convert <a>FunPtr</a> values to corresponding Haskell functions,
--   one can define a <i>dynamic</i> stub for the specific foreign type,
--   e.g.
--   
--   <pre>
--   type IntFunction = CInt -&gt; IO ()
--   foreign import ccall "dynamic" 
--     mkFun :: FunPtr IntFunction -&gt; IntFunction
--   </pre>
data FunPtr a

-- | The constant <a>nullFunPtr</a> contains a distinguished value of
--   <a>FunPtr</a> that is not associated with a valid memory location.
nullFunPtr :: FunPtr a

-- | Casts a <a>FunPtr</a> to a <a>FunPtr</a> of a different type.
castFunPtr :: FunPtr a -> FunPtr b

-- | Casts a <a>FunPtr</a> to a <a>Ptr</a>.
--   
--   <i>Note:</i> this is valid only on architectures where data and
--   function pointers range over the same set of addresses, and should
--   only be used for bindings to external libraries whose interface
--   already relies on this assumption.
castFunPtrToPtr :: FunPtr a -> Ptr b

-- | Casts a <a>Ptr</a> to a <a>FunPtr</a>.
--   
--   <i>Note:</i> this is valid only on architectures where data and
--   function pointers range over the same set of addresses, and should
--   only be used for bindings to external libraries whose interface
--   already relies on this assumption.
castPtrToFunPtr :: Ptr a -> FunPtr b

-- | Release the storage associated with the given <a>FunPtr</a>, which
--   must have been obtained from a wrapper stub. This should be called
--   whenever the return value from a foreign import wrapper function is no
--   longer required; otherwise, the storage it uses will leak.
freeHaskellFunPtr :: FunPtr a -> IO ()

-- | A signed integral type that can be losslessly converted to and from
--   <tt>Ptr</tt>. This type is also compatible with the C99 type
--   <tt>intptr_t</tt>, and can be marshalled to and from that type safely.
data IntPtr

-- | casts a <tt>Ptr</tt> to an <tt>IntPtr</tt>
ptrToIntPtr :: Ptr a -> IntPtr

-- | casts an <tt>IntPtr</tt> to a <tt>Ptr</tt>
intPtrToPtr :: IntPtr -> Ptr a

-- | An unsigned integral type that can be losslessly converted to and from
--   <tt>Ptr</tt>. This type is also compatible with the C99 type
--   <tt>uintptr_t</tt>, and can be marshalled to and from that type
--   safely.
data WordPtr

-- | casts a <tt>Ptr</tt> to a <tt>WordPtr</tt>
ptrToWordPtr :: Ptr a -> WordPtr

-- | casts a <tt>WordPtr</tt> to a <tt>Ptr</tt>
wordPtrToPtr :: WordPtr -> Ptr a
instance Typeable IntPtr
instance Typeable WordPtr
instance Eq WordPtr
instance Ord WordPtr
instance Num WordPtr
instance Enum WordPtr
instance Storable WordPtr
instance Real WordPtr
instance Bounded WordPtr
instance Integral WordPtr
instance Bits WordPtr
instance Eq IntPtr
instance Ord IntPtr
instance Num IntPtr
instance Enum IntPtr
instance Storable IntPtr
instance Real IntPtr
instance Bounded IntPtr
instance Integral IntPtr
instance Bits IntPtr
instance Show IntPtr
instance Read IntPtr
instance Show WordPtr
instance Read WordPtr


-- | A class for monoids (types with an associative binary operation that
--   has an identity) with various general-purpose instances.
module Data.Monoid

-- | The class of monoids (types with an associative binary operation that
--   has an identity). Instances should satisfy the following laws:
--   
--   <ul>
--   <li><pre>mappend mempty x = x</pre></li>
--   <li><pre>mappend x mempty = x</pre></li>
--   <li><pre>mappend x (mappend y z) = mappend (mappend x y) z</pre></li>
--   <li><pre>mconcat = <a>foldr</a> mappend mempty</pre></li>
--   </ul>
--   
--   The method names refer to the monoid of lists under concatenation, but
--   there are many other instances.
--   
--   Minimal complete definition: <a>mempty</a> and <a>mappend</a>.
--   
--   Some types can be viewed as a monoid in more than one way, e.g. both
--   addition and multiplication on numbers. In such cases we often define
--   <tt>newtype</tt>s and make those instances of <a>Monoid</a>, e.g.
--   <a>Sum</a> and <a>Product</a>.
class Monoid a where mconcat = foldr mappend mempty
mempty :: Monoid a => a
mappend :: Monoid a => a -> a -> a
mconcat :: Monoid a => [a] -> a

-- | An infix synonym for <a>mappend</a>.
(<>) :: Monoid m => m -> m -> m

-- | The dual of a monoid, obtained by swapping the arguments of
--   <a>mappend</a>.
newtype Dual a
Dual :: a -> Dual a
getDual :: Dual a -> a

-- | The monoid of endomorphisms under composition.
newtype Endo a
Endo :: (a -> a) -> Endo a
appEndo :: Endo a -> a -> a

-- | Boolean monoid under conjunction.
newtype All
All :: Bool -> All
getAll :: All -> Bool

-- | Boolean monoid under disjunction.
newtype Any
Any :: Bool -> Any
getAny :: Any -> Bool

-- | Monoid under addition.
newtype Sum a
Sum :: a -> Sum a
getSum :: Sum a -> a

-- | Monoid under multiplication.
newtype Product a
Product :: a -> Product a
getProduct :: Product a -> a

-- | Maybe monoid returning the leftmost non-Nothing value.
newtype First a
First :: Maybe a -> First a
getFirst :: First a -> Maybe a

-- | Maybe monoid returning the rightmost non-Nothing value.
newtype Last a
Last :: Maybe a -> Last a
getLast :: Last a -> Maybe a
instance Eq a => Eq (Dual a)
instance Ord a => Ord (Dual a)
instance Read a => Read (Dual a)
instance Show a => Show (Dual a)
instance Bounded a => Bounded (Dual a)
instance Eq All
instance Ord All
instance Read All
instance Show All
instance Bounded All
instance Eq Any
instance Ord Any
instance Read Any
instance Show Any
instance Bounded Any
instance Eq a => Eq (Sum a)
instance Ord a => Ord (Sum a)
instance Read a => Read (Sum a)
instance Show a => Show (Sum a)
instance Bounded a => Bounded (Sum a)
instance Eq a => Eq (Product a)
instance Ord a => Ord (Product a)
instance Read a => Read (Product a)
instance Show a => Show (Product a)
instance Bounded a => Bounded (Product a)
instance Eq a => Eq (First a)
instance Ord a => Ord (First a)
instance Read a => Read (First a)
instance Show a => Show (First a)
instance Eq a => Eq (Last a)
instance Ord a => Ord (Last a)
instance Read a => Read (Last a)
instance Show a => Show (Last a)
instance Monoid (Last a)
instance Monoid (First a)
instance Monoid a => Monoid (Maybe a)
instance Num a => Monoid (Product a)
instance Num a => Monoid (Sum a)
instance Monoid Any
instance Monoid All
instance Monoid (Endo a)
instance Monoid a => Monoid (Dual a)
instance Monoid Ordering
instance (Monoid a, Monoid b, Monoid c, Monoid d, Monoid e) => Monoid (a, b, c, d, e)
instance (Monoid a, Monoid b, Monoid c, Monoid d) => Monoid (a, b, c, d)
instance (Monoid a, Monoid b, Monoid c) => Monoid (a, b, c)
instance (Monoid a, Monoid b) => Monoid (a, b)
instance Monoid ()
instance Monoid b => Monoid (a -> b)
instance Monoid [a]


-- | The <a>Bool</a> type and related functions.
module Data.Bool
data Bool :: *
False :: Bool
True :: Bool

-- | Boolean "and"
(&&) :: Bool -> Bool -> Bool

-- | Boolean "or"
(||) :: Bool -> Bool -> Bool

-- | Boolean "not"
not :: Bool -> Bool

-- | <a>otherwise</a> is defined as the value <a>True</a>. It helps to make
--   guards more readable. eg.
--   
--   <pre>
--   f x | x &lt; 0     = ...
--       | otherwise = ...
--   </pre>
otherwise :: Bool


-- | Equality
module Data.Eq

-- | The <a>Eq</a> class defines equality (<a>==</a>) and inequality
--   (<a>/=</a>). All the basic datatypes exported by the <a>Prelude</a>
--   are instances of <a>Eq</a>, and <a>Eq</a> may be derived for any
--   datatype whose constituents are also instances of <a>Eq</a>.
--   
--   Minimal complete definition: either <a>==</a> or <a>/=</a>.
class Eq a
(==) :: Eq a => a -> a -> Bool
(/=) :: Eq a => a -> a -> Bool


-- | An implementation of extensible hash tables, as described in Per-Ake
--   Larson, <i>Dynamic Hash Tables</i>, CACM 31(4), April 1988, pp.
--   446--457. The implementation is also derived from the one in GHC's
--   runtime system (<tt>ghc/rts/Hash.{c,h}</tt>).

-- | <i>Deprecated: Data.HashTable will be removed in GHC 7.8. Please use
--   an alternative, e.g. the hashtables package, instead. </i>
module Data.HashTable
data HashTable key val

-- | Creates a new hash table. The following property should hold for the
--   <tt>eq</tt> and <tt>hash</tt> functions passed to <a>new</a>:
--   
--   <pre>
--   eq A B  =&gt;  hash A == hash B
--   </pre>
new :: (key -> key -> Bool) -> (key -> Int32) -> IO (HashTable key val)

-- | Creates a new hash table with the given minimum size.
newHint :: (key -> key -> Bool) -> (key -> Int32) -> Int -> IO (HashTable key val)

-- | Inserts a key/value mapping into the hash table.
--   
--   Note that <a>insert</a> doesn't remove the old entry from the table -
--   the behaviour is like an association list, where <a>lookup</a> returns
--   the most-recently-inserted mapping for a key in the table. The reason
--   for this is to keep <a>insert</a> as efficient as possible. If you
--   need to update a mapping, then we provide <a>update</a>.
insert :: HashTable key val -> key -> val -> IO ()

-- | Remove an entry from the hash table.
delete :: HashTable key val -> key -> IO ()

-- | Looks up the value of a key in the hash table.
lookup :: HashTable key val -> key -> IO (Maybe val)

-- | Updates an entry in the hash table, returning <a>True</a> if there was
--   already an entry for this key, or <a>False</a> otherwise. After
--   <a>update</a> there will always be exactly one entry for the given key
--   in the table.
--   
--   <a>insert</a> is more efficient than <a>update</a> if you don't care
--   about multiple entries, or you know for sure that multiple entries
--   can't occur. However, <a>update</a> is more efficient than
--   <a>delete</a> followed by <a>insert</a>.
update :: HashTable key val -> key -> val -> IO Bool

-- | Convert a list of key/value pairs into a hash table. Equality on keys
--   is taken from the Eq instance for the key type.
fromList :: Eq key => (key -> Int32) -> [(key, val)] -> IO (HashTable key val)

-- | Converts a hash table to a list of key/value pairs.
toList :: HashTable key val -> IO [(key, val)]

-- | A sample (and useful) hash function for Int and Int32, implemented by
--   extracting the uppermost 32 bits of the 64-bit result of multiplying
--   by a 33-bit constant. The constant is from Knuth, derived from the
--   golden ratio:
--   
--   <pre>
--   golden = round ((sqrt 5 - 1) * 2^32)
--   </pre>
--   
--   We get good key uniqueness on small inputs (a problem with previous
--   versions): (length $ group $ sort $ map hashInt [-32767..65536]) ==
--   65536 + 32768
hashInt :: Int -> Int32

-- | A sample hash function for Strings. We keep multiplying by the golden
--   ratio and adding. The implementation is:
--   
--   <pre>
--   hashString = foldl' f golden
--     where f m c = fromIntegral (ord c) * magic + hashInt32 m
--           magic = 0xdeadbeef
--   </pre>
--   
--   Where hashInt32 works just as hashInt shown above.
--   
--   Knuth argues that repeated multiplication by the golden ratio will
--   minimize gaps in the hash space, and thus it's a good choice for
--   combining together multiple keys to form one.
--   
--   Here we know that individual characters c are often small, and this
--   produces frequent collisions if we use ord c alone. A particular
--   problem are the shorter low ASCII and ISO-8859-1 character strings. We
--   pre-multiply by a magic twiddle factor to obtain a good distribution.
--   In fact, given the following test:
--   
--   <pre>
--   testp :: Int32 -&gt; Int
--   testp k = (n - ) . length . group . sort . map hs . take n $ ls
--     where ls = [] : [c : l | l &lt;- ls, c &lt;- ['\0'..'\xff']]
--           hs = foldl' f golden
--           f m c = fromIntegral (ord c) * k + hashInt32 m
--           n = 100000
--   </pre>
--   
--   We discover that testp magic = 0.
hashString :: String -> Int32

-- | A prime larger than the maximum hash table size
prime :: Int32

-- | This function is useful for determining whether your hash function is
--   working well for your data set. It returns the longest chain of
--   key/value pairs in the hash table for which all the keys hash to the
--   same bucket. If this chain is particularly long (say, longer than 14
--   elements or so), then it might be a good idea to try a different hash
--   function.
longestChain :: HashTable key val -> IO [(key, val)]
instance Eq HashData
instance Show HashData
instance Eq Inserts


-- | The <a>ForeignPtr</a> type and operations. This module is part of the
--   Foreign Function Interface (FFI) and will usually be imported via the
--   <a>Foreign</a> module.
--   
--   Safe API Only.
module Foreign.ForeignPtr.Safe

-- | The type <a>ForeignPtr</a> represents references to objects that are
--   maintained in a foreign language, i.e., that are not part of the data
--   structures usually managed by the Haskell storage manager. The
--   essential difference between <a>ForeignPtr</a>s and vanilla memory
--   references of type <tt>Ptr a</tt> is that the former may be associated
--   with <i>finalizers</i>. A finalizer is a routine that is invoked when
--   the Haskell storage manager detects that - within the Haskell heap and
--   stack - there are no more references left that are pointing to the
--   <a>ForeignPtr</a>. Typically, the finalizer will, then, invoke
--   routines in the foreign language that free the resources bound by the
--   foreign object.
--   
--   The <a>ForeignPtr</a> is parameterised in the same way as <a>Ptr</a>.
--   The type argument of <a>ForeignPtr</a> should normally be an instance
--   of class <a>Storable</a>.
data ForeignPtr a

-- | A finalizer is represented as a pointer to a foreign function that, at
--   finalisation time, gets as an argument a plain pointer variant of the
--   foreign pointer that the finalizer is associated with.
type FinalizerPtr a = FunPtr (Ptr a -> IO ())
type FinalizerEnvPtr env a = FunPtr (Ptr env -> Ptr a -> IO ())

-- | Turns a plain memory reference into a foreign pointer, and associates
--   a finalizer with the reference. The finalizer will be executed after
--   the last reference to the foreign object is dropped. There is no
--   guarantee of promptness, however the finalizer will be executed before
--   the program exits.
newForeignPtr :: FinalizerPtr a -> Ptr a -> IO (ForeignPtr a)

-- | Turns a plain memory reference into a foreign pointer that may be
--   associated with finalizers by using <a>addForeignPtrFinalizer</a>.
newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)

-- | This function adds a finalizer to the given foreign object. The
--   finalizer will run <i>before</i> all other finalizers for the same
--   object which have already been registered.
addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()

-- | This variant of <a>newForeignPtr</a> adds a finalizer that expects an
--   environment in addition to the finalized pointer. The environment that
--   will be passed to the finalizer is fixed by the second argument to
--   <a>newForeignPtrEnv</a>.
newForeignPtrEnv :: FinalizerEnvPtr env a -> Ptr env -> Ptr a -> IO (ForeignPtr a)

-- | Like <a>addForeignPtrFinalizerEnv</a> but allows the finalizer to be
--   passed an additional environment parameter to be passed to the
--   finalizer. The environment passed to the finalizer is fixed by the
--   second argument to <a>addForeignPtrFinalizerEnv</a>
addForeignPtrFinalizerEnv :: FinalizerEnvPtr env a -> Ptr env -> ForeignPtr a -> IO ()

-- | This is a way to look at the pointer living inside a foreign object.
--   This function takes a function which is applied to that pointer. The
--   resulting <a>IO</a> action is then executed. The foreign object is
--   kept alive at least during the whole action, even if it is not used
--   directly inside. Note that it is not safe to return the pointer from
--   the action and use it after the action completes. All uses of the
--   pointer should be inside the <a>withForeignPtr</a> bracket. The reason
--   for this unsafeness is the same as for <a>unsafeForeignPtrToPtr</a>
--   below: the finalizer may run earlier than expected, because the
--   compiler can only track usage of the <a>ForeignPtr</a> object, not a
--   <a>Ptr</a> object made from it.
--   
--   This function is normally used for marshalling data to or from the
--   object pointed to by the <a>ForeignPtr</a>, using the operations from
--   the <a>Storable</a> class.
withForeignPtr :: ForeignPtr a -> (Ptr a -> IO b) -> IO b

-- | Causes the finalizers associated with a foreign pointer to be run
--   immediately.
finalizeForeignPtr :: ForeignPtr a -> IO ()

-- | This function ensures that the foreign object in question is alive at
--   the given place in the sequence of IO actions. In particular
--   <a>withForeignPtr</a> does a <a>touchForeignPtr</a> after it executes
--   the user action.
--   
--   Note that this function should not be used to express dependencies
--   between finalizers on <a>ForeignPtr</a>s. For example, if the
--   finalizer for a <a>ForeignPtr</a> <tt>F1</tt> calls
--   <a>touchForeignPtr</a> on a second <a>ForeignPtr</a> <tt>F2</tt>, then
--   the only guarantee is that the finalizer for <tt>F2</tt> is never
--   started before the finalizer for <tt>F1</tt>. They might be started
--   together if for example both <tt>F1</tt> and <tt>F2</tt> are otherwise
--   unreachable, and in that case the scheduler might end up running the
--   finalizer for <tt>F2</tt> first.
--   
--   In general, it is not recommended to use finalizers on separate
--   objects with ordering constraints between them. To express the
--   ordering robustly requires explicit synchronisation using
--   <tt>MVar</tt>s between the finalizers, but even then the runtime
--   sometimes runs multiple finalizers sequentially in a single thread
--   (for performance reasons), so synchronisation between finalizers could
--   result in artificial deadlock. Another alternative is to use explicit
--   reference counting.
touchForeignPtr :: ForeignPtr a -> IO ()

-- | This function casts a <a>ForeignPtr</a> parameterised by one type into
--   another type.
castForeignPtr :: ForeignPtr a -> ForeignPtr b

-- | Allocate some memory and return a <a>ForeignPtr</a> to it. The memory
--   will be released automatically when the <a>ForeignPtr</a> is
--   discarded.
--   
--   <a>mallocForeignPtr</a> is equivalent to
--   
--   <pre>
--   do { p &lt;- malloc; newForeignPtr finalizerFree p }
--   </pre>
--   
--   although it may be implemented differently internally: you may not
--   assume that the memory returned by <a>mallocForeignPtr</a> has been
--   allocated with <a>malloc</a>.
--   
--   GHC notes: <a>mallocForeignPtr</a> has a heavily optimised
--   implementation in GHC. It uses pinned memory in the garbage collected
--   heap, so the <a>ForeignPtr</a> does not require a finalizer to free
--   the memory. Use of <a>mallocForeignPtr</a> and associated functions is
--   strongly recommended in preference to <tt>newForeignPtr</tt> with a
--   finalizer.
mallocForeignPtr :: Storable a => IO (ForeignPtr a)

-- | This function is similar to <a>mallocForeignPtr</a>, except that the
--   size of the memory required is given explicitly as a number of bytes.
mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)

-- | This function is similar to <a>mallocArray</a>, but yields a memory
--   area that has a finalizer attached that releases the memory area. As
--   with <a>mallocForeignPtr</a>, it is not guaranteed that the block of
--   memory was allocated by <a>malloc</a>.
mallocForeignPtrArray :: Storable a => Int -> IO (ForeignPtr a)

-- | This function is similar to <a>mallocArray0</a>, but yields a memory
--   area that has a finalizer attached that releases the memory area. As
--   with <a>mallocForeignPtr</a>, it is not guaranteed that the block of
--   memory was allocated by <a>malloc</a>.
mallocForeignPtrArray0 :: Storable a => Int -> IO (ForeignPtr a)


-- | The <a>ForeignPtr</a> type and operations. This module is part of the
--   Foreign Function Interface (FFI) and will usually be imported via the
--   <a>Foreign</a> module.
--   
--   Unsafe API Only.
module Foreign.ForeignPtr.Unsafe

-- | This function extracts the pointer component of a foreign pointer.
--   This is a potentially dangerous operations, as if the argument to
--   <a>unsafeForeignPtrToPtr</a> is the last usage occurrence of the given
--   foreign pointer, then its finalizer(s) will be run, which potentially
--   invalidates the plain pointer just obtained. Hence,
--   <a>touchForeignPtr</a> must be used wherever it has to be guaranteed
--   that the pointer lives on - i.e., has another usage occurrence.
--   
--   To avoid subtle coding errors, hand written marshalling code should
--   preferably use <a>withForeignPtr</a> rather than combinations of
--   <a>unsafeForeignPtrToPtr</a> and <a>touchForeignPtr</a>. However, the
--   latter routines are occasionally preferred in tool generated
--   marshalling code.
unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a


-- | Buffers used in the IO system
module GHC.IO.Buffer

-- | A mutable array of bytes that can be passed to foreign functions.
--   
--   The buffer is represented by a record, where the record contains the
--   raw buffer and the start/end points of the filled portion. The buffer
--   contents itself is mutable, but the rest of the record is immutable.
--   This is a slightly odd mix, but it turns out to be quite practical: by
--   making all the buffer metadata immutable, we can have operations on
--   buffer metadata outside of the IO monad.
--   
--   The <a>live</a> elements of the buffer are those between the
--   <a>bufL</a> and <a>bufR</a> offsets. In an empty buffer, <a>bufL</a>
--   is equal to <a>bufR</a>, but they might not be zero: for exmaple, the
--   buffer might correspond to a memory-mapped file and in which case
--   <a>bufL</a> will point to the next location to be written, which is
--   not necessarily the beginning of the file.
data Buffer e
Buffer :: !(RawBuffer e) -> BufferState -> !Int -> !Int -> !Int -> Buffer e
bufRaw :: Buffer e -> !(RawBuffer e)
bufState :: Buffer e -> BufferState
bufSize :: Buffer e -> !Int
bufL :: Buffer e -> !Int
bufR :: Buffer e -> !Int
data BufferState
ReadBuffer :: BufferState
WriteBuffer :: BufferState
type CharBuffer = Buffer Char
type CharBufElem = Char
newByteBuffer :: Int -> BufferState -> IO (Buffer Word8)
newCharBuffer :: Int -> BufferState -> IO CharBuffer
newBuffer :: Int -> Int -> BufferState -> IO (Buffer e)
emptyBuffer :: RawBuffer e -> Int -> BufferState -> Buffer e
bufferRemove :: Int -> Buffer e -> Buffer e
bufferAdd :: Int -> Buffer e -> Buffer e

-- | slides the contents of the buffer to the beginning
slideContents :: Buffer Word8 -> IO (Buffer Word8)
bufferAdjustL :: Int -> Buffer e -> Buffer e
isEmptyBuffer :: Buffer e -> Bool
isFullBuffer :: Buffer e -> Bool
isFullCharBuffer :: Buffer e -> Bool
isWriteBuffer :: Buffer e -> Bool
bufferElems :: Buffer e -> Int
bufferAvailable :: Buffer e -> Int
summaryBuffer :: Buffer a -> String
withBuffer :: Buffer e -> (Ptr e -> IO a) -> IO a
withRawBuffer :: RawBuffer e -> (Ptr e -> IO a) -> IO a
checkBuffer :: Buffer a -> IO ()
type RawBuffer e = ForeignPtr e
readWord8Buf :: RawBuffer Word8 -> Int -> IO Word8
writeWord8Buf :: RawBuffer Word8 -> Int -> Word8 -> IO ()
type RawCharBuffer = RawBuffer CharBufElem
peekCharBuf :: RawCharBuffer -> Int -> IO Char
readCharBuf :: RawCharBuffer -> Int -> IO (Char, Int)
writeCharBuf :: RawCharBuffer -> Int -> Char -> IO Int
readCharBufPtr :: Ptr CharBufElem -> Int -> IO (Char, Int)
writeCharBufPtr :: Ptr CharBufElem -> Int -> Char -> IO Int
charSize :: Int
instance Eq BufferState


-- | Types for text encoding/decoding
module GHC.IO.Encoding.Types
data BufferCodec from to state
BufferCodec :: (Buffer from -> Buffer to -> IO (CodingProgress, Buffer from, Buffer to)) -> (Buffer from -> Buffer to -> IO (Buffer from, Buffer to)) -> IO () -> IO state -> (state -> IO ()) -> BufferCodec from to state

-- | The <tt>encode</tt> function translates elements of the buffer
--   <tt>from</tt> to the buffer <tt>to</tt>. It should translate as many
--   elements as possible given the sizes of the buffers, including
--   translating zero elements if there is either not enough room in
--   <tt>to</tt>, or <tt>from</tt> does not contain a complete multibyte
--   sequence.
--   
--   The fact that as many elements as possible are translated is used by
--   the IO library in order to report translation errors at the point they
--   actually occur, rather than when the buffer is translated.
--   
--   To allow us to use iconv as a BufferCode efficiently, character
--   buffers are defined to contain lone surrogates instead of those
--   private use characters that are used for roundtripping. Thus, Chars
--   poked and peeked from a character buffer must undergo
--   surrogatifyRoundtripCharacter and desurrogatifyRoundtripCharacter
--   respectively.
--   
--   For more information on this, see Note [Roundtripping] in
--   GHC.IO.Encoding.Failure.
encode :: BufferCodec from to state -> Buffer from -> Buffer to -> IO (CodingProgress, Buffer from, Buffer to)

-- | The <tt>recover</tt> function is used to continue decoding in the
--   presence of invalid or unrepresentable sequences. This includes both
--   those detected by <tt>encode</tt> returning <tt>InvalidSequence</tt>
--   and those that occur because the input byte sequence appears to be
--   truncated.
--   
--   Progress will usually be made by skipping the first element of the
--   <tt>from</tt> buffer. This function should only be called if you are
--   certain that you wish to do this skipping and if the <tt>to</tt>
--   buffer has at least one element of free space. Because this function
--   deals with decoding failure, it assumes that the from buffer has at
--   least one element.
--   
--   <tt>recover</tt> may raise an exception rather than skipping anything.
--   
--   Currently, some implementations of <tt>recover</tt> may mutate the
--   input buffer. In particular, this feature is used to implement
--   transliteration.
recover :: BufferCodec from to state -> Buffer from -> Buffer to -> IO (Buffer from, Buffer to)

-- | Resources associated with the encoding may now be released. The
--   <tt>encode</tt> function may not be called again after calling
--   <tt>close</tt>.
close :: BufferCodec from to state -> IO ()

-- | Return the current state of the codec.
--   
--   Many codecs are not stateful, and in these case the state can be
--   represented as '()'. Other codecs maintain a state. For example,
--   UTF-16 recognises a BOM (byte-order-mark) character at the beginning
--   of the input, and remembers thereafter whether to use big-endian or
--   little-endian mode. In this case, the state of the codec would include
--   two pieces of information: whether we are at the beginning of the
--   stream (the BOM only occurs at the beginning), and if not, whether to
--   use the big or little-endian encoding.
getState :: BufferCodec from to state -> IO state
setState :: BufferCodec from to state -> state -> IO ()

-- | A <a>TextEncoding</a> is a specification of a conversion scheme
--   between sequences of bytes and sequences of Unicode characters.
--   
--   For example, UTF-8 is an encoding of Unicode characters into a
--   sequence of bytes. The <a>TextEncoding</a> for UTF-8 is <tt>utf8</tt>.
data TextEncoding
TextEncoding :: String -> IO (TextDecoder dstate) -> IO (TextEncoder estate) -> TextEncoding

-- | a string that can be passed to <tt>mkTextEncoding</tt> to create an
--   equivalent <a>TextEncoding</a>.
textEncodingName :: TextEncoding -> String

-- | Creates a means of decoding bytes into characters: the result must not
--   be shared between several byte sequences or simultaneously across
--   threads
mkTextDecoder :: TextEncoding -> IO (TextDecoder dstate)

-- | Creates a means of encode characters into bytes: the result must not
--   be shared between several character sequences or simultaneously across
--   threads
mkTextEncoder :: TextEncoding -> IO (TextEncoder estate)
type TextEncoder state = BufferCodec CharBufElem Word8 state
type TextDecoder state = BufferCodec Word8 CharBufElem state
type EncodeBuffer = Buffer Char -> Buffer Word8 -> IO (CodingProgress, Buffer Char, Buffer Word8)
type DecodeBuffer = Buffer Word8 -> Buffer Char -> IO (CodingProgress, Buffer Word8, Buffer Char)
data CodingProgress

-- | Stopped because the input contains insufficient available elements, or
--   all of the input sequence has been sucessfully translated.
InputUnderflow :: CodingProgress

-- | Stopped because the output contains insufficient free elements
OutputUnderflow :: CodingProgress

-- | Stopped because there are sufficient free elements in the output to
--   output at least one encoded ASCII character, but the input contains an
--   invalid or unrepresentable sequence
InvalidSequence :: CodingProgress
instance Eq CodingProgress
instance Show CodingProgress
instance Show TextEncoding


-- | Class of buffered IO devices
module GHC.IO.BufferedIO

-- | The purpose of <a>BufferedIO</a> is to provide a common interface for
--   I/O devices that can read and write data through a buffer. Devices
--   that implement <a>BufferedIO</a> include ordinary files, memory-mapped
--   files, and bytestrings. The underlying device implementing a
--   <tt>Handle</tt> must provide <a>BufferedIO</a>.
class BufferedIO dev where emptyWriteBuffer _dev buf = return (buf {bufL = 0, bufR = 0, bufState = WriteBuffer})
newBuffer :: BufferedIO dev => dev -> BufferState -> IO (Buffer Word8)
fillReadBuffer :: BufferedIO dev => dev -> Buffer Word8 -> IO (Int, Buffer Word8)
fillReadBuffer0 :: BufferedIO dev => dev -> Buffer Word8 -> IO (Maybe Int, Buffer Word8)
emptyWriteBuffer :: BufferedIO dev => dev -> Buffer Word8 -> IO (Buffer Word8)
flushWriteBuffer :: BufferedIO dev => dev -> Buffer Word8 -> IO (Buffer Word8)
flushWriteBuffer0 :: BufferedIO dev => dev -> Buffer Word8 -> IO (Int, Buffer Word8)
readBuf :: RawIO dev => dev -> Buffer Word8 -> IO (Int, Buffer Word8)
readBufNonBlocking :: RawIO dev => dev -> Buffer Word8 -> IO (Maybe Int, Buffer Word8)
writeBuf :: RawIO dev => dev -> Buffer Word8 -> IO (Buffer Word8)
writeBufNonBlocking :: RawIO dev => dev -> Buffer Word8 -> IO (Int, Buffer Word8)


-- | The module <a>Foreign.Marshal.Alloc</a> provides operations to
--   allocate and deallocate blocks of raw memory (i.e., unstructured
--   chunks of memory outside of the area maintained by the Haskell storage
--   manager). These memory blocks are commonly used to pass compound data
--   structures to foreign functions or to provide space in which compound
--   result values are obtained from foreign functions.
--   
--   If any of the allocation functions fails, an exception is thrown. In
--   some cases, memory exhaustion may mean the process is terminated. If
--   <a>free</a> or <a>reallocBytes</a> is applied to a memory area that
--   has been allocated with <a>alloca</a> or <a>allocaBytes</a>, the
--   behaviour is undefined. Any further access to memory areas allocated
--   with <a>alloca</a> or <a>allocaBytes</a>, after the computation that
--   was passed to the allocation function has terminated, leads to
--   undefined behaviour. Any further access to the memory area referenced
--   by a pointer passed to <a>realloc</a>, <a>reallocBytes</a>, or
--   <a>free</a> entails undefined behaviour.
--   
--   All storage allocated by functions that allocate based on a <i>size in
--   bytes</i> must be sufficiently aligned for any of the basic foreign
--   types that fits into the newly allocated storage. All storage
--   allocated by functions that allocate based on a specific type must be
--   sufficiently aligned for that type. Array allocation routines need to
--   obey the same alignment constraints for each array element.
module Foreign.Marshal.Alloc

-- | <tt><a>alloca</a> f</tt> executes the computation <tt>f</tt>, passing
--   as argument a pointer to a temporarily allocated block of memory
--   sufficient to hold values of type <tt>a</tt>.
--   
--   The memory is freed when <tt>f</tt> terminates (either normally or via
--   an exception), so the pointer passed to <tt>f</tt> must <i>not</i> be
--   used after this.
alloca :: Storable a => (Ptr a -> IO b) -> IO b

-- | <tt><a>allocaBytes</a> n f</tt> executes the computation <tt>f</tt>,
--   passing as argument a pointer to a temporarily allocated block of
--   memory of <tt>n</tt> 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 <tt>f</tt> terminates (either normally or via
--   an exception), so the pointer passed to <tt>f</tt> must <i>not</i> be
--   used after this.
allocaBytes :: Int -> (Ptr a -> IO b) -> IO b
allocaBytesAligned :: Int -> Int -> (Ptr a -> IO b) -> IO b

-- | Allocate a block of memory that is sufficient to hold values of type
--   <tt>a</tt>. The size of the area allocated is determined by the
--   <a>sizeOf</a> method from the instance of <a>Storable</a> for the
--   appropriate type.
--   
--   The memory may be deallocated using <a>free</a> or
--   <a>finalizerFree</a> when no longer required.
malloc :: Storable a => IO (Ptr a)

-- | Allocate a block of memory of the given number of 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 may be deallocated using <a>free</a> or
--   <a>finalizerFree</a> when no longer required.
mallocBytes :: Int -> IO (Ptr a)

-- | Resize a memory area that was allocated with <a>malloc</a> or
--   <a>mallocBytes</a> to the size needed to store values of type
--   <tt>b</tt>. The returned pointer may refer to an entirely different
--   memory area, but will be suitably aligned to hold values of type
--   <tt>b</tt>. The contents of the referenced memory area will be the
--   same as of the original pointer up to the minimum of the original size
--   and the size of values of type <tt>b</tt>.
--   
--   If the argument to <a>realloc</a> is <a>nullPtr</a>, <a>realloc</a>
--   behaves like <a>malloc</a>.
realloc :: Storable b => Ptr a -> IO (Ptr b)

-- | Resize a memory area that was allocated with <a>malloc</a> or
--   <a>mallocBytes</a> to the given size. The returned pointer may refer
--   to an entirely different memory area, but will be sufficiently aligned
--   for any of the basic foreign types that fits into a memory block of
--   the given size. The contents of the referenced memory area will be the
--   same as of the original pointer up to the minimum of the original size
--   and the given size.
--   
--   If the pointer argument to <a>reallocBytes</a> is <a>nullPtr</a>,
--   <a>reallocBytes</a> behaves like <a>malloc</a>. If the requested size
--   is 0, <a>reallocBytes</a> behaves like <a>free</a>.
reallocBytes :: Ptr a -> Int -> IO (Ptr a)

-- | Free a block of memory that was allocated with <a>malloc</a>,
--   <a>mallocBytes</a>, <a>realloc</a>, <a>reallocBytes</a>, <a>new</a> or
--   any of the <tt>new</tt><i>X</i> functions in
--   <a>Foreign.Marshal.Array</a> or <a>Foreign.C.String</a>.
free :: Ptr a -> IO ()

-- | A pointer to a foreign function equivalent to <a>free</a>, which may
--   be used as a finalizer (cf <a>ForeignPtr</a>) for storage allocated
--   with <a>malloc</a>, <a>mallocBytes</a>, <a>realloc</a> or
--   <a>reallocBytes</a>.
finalizerFree :: FinalizerPtr a


-- | Types for specifying how text encoding/decoding fails
module GHC.IO.Encoding.Failure

-- | The <a>CodingFailureMode</a> is used to construct
--   <tt>TextEncoding</tt>s, and specifies how they handle illegal
--   sequences.
data CodingFailureMode

-- | Throw an error when an illegal sequence is encountered
ErrorOnCodingFailure :: CodingFailureMode

-- | Attempt to ignore and recover if an illegal sequence is encountered
IgnoreCodingFailure :: CodingFailureMode

-- | Replace with the closest visual match upon an illegal sequence
TransliterateCodingFailure :: CodingFailureMode

-- | Use the private-use escape mechanism to attempt to allow illegal
--   sequences to be roundtripped.
RoundtripFailure :: CodingFailureMode
codingFailureModeSuffix :: CodingFailureMode -> String

-- | Some characters are actually <a>surrogate</a> codepoints defined for
--   use in UTF-16. We need to signal an invalid character if we detect
--   them when encoding a sequence of <a>Char</a>s into <a>Word8</a>s
--   because they won't give valid Unicode.
--   
--   We may also need to signal an invalid character if we detect them when
--   encoding a sequence of <a>Char</a>s into <a>Word8</a>s because the
--   <a>RoundtripFailure</a> mode creates these to round-trip bytes through
--   our internal UTF-16 encoding.
isSurrogate :: Char -> Bool
recoverDecode :: CodingFailureMode -> Buffer Word8 -> Buffer Char -> IO (Buffer Word8, Buffer Char)
recoverEncode :: CodingFailureMode -> Buffer Char -> Buffer Word8 -> IO (Buffer Char, Buffer Word8)
instance Show CodingFailureMode


-- | UTF-8 Codec for the IO library
--   
--   Portions Copyright : (c) Tom Harper 2008-2009, (c) Bryan O'Sullivan
--   2009, (c) Duncan Coutts 2009
module GHC.IO.Encoding.UTF8
utf8 :: TextEncoding
mkUTF8 :: CodingFailureMode -> TextEncoding
utf8_bom :: TextEncoding
mkUTF8_bom :: CodingFailureMode -> TextEncoding


-- | UTF-32 Codecs for the IO library
--   
--   Portions Copyright : (c) Tom Harper 2008-2009, (c) Bryan O'Sullivan
--   2009, (c) Duncan Coutts 2009
module GHC.IO.Encoding.Latin1
latin1 :: TextEncoding
mkLatin1 :: CodingFailureMode -> TextEncoding
latin1_checked :: TextEncoding
mkLatin1_checked :: CodingFailureMode -> TextEncoding
latin1_decode :: DecodeBuffer
latin1_encode :: EncodeBuffer
latin1_checked_encode :: EncodeBuffer


-- | UTF-16 Codecs for the IO library
--   
--   Portions Copyright : (c) Tom Harper 2008-2009, (c) Bryan O'Sullivan
--   2009, (c) Duncan Coutts 2009
module GHC.IO.Encoding.UTF16
utf16 :: TextEncoding
mkUTF16 :: CodingFailureMode -> TextEncoding
utf16_decode :: IORef (Maybe DecodeBuffer) -> DecodeBuffer
utf16_encode :: IORef Bool -> EncodeBuffer
utf16be :: TextEncoding
mkUTF16be :: CodingFailureMode -> TextEncoding
utf16be_decode :: DecodeBuffer
utf16be_encode :: EncodeBuffer
utf16le :: TextEncoding
mkUTF16le :: CodingFailureMode -> TextEncoding
utf16le_decode :: DecodeBuffer
utf16le_encode :: EncodeBuffer


-- | UTF-32 Codecs for the IO library
--   
--   Portions Copyright : (c) Tom Harper 2008-2009, (c) Bryan O'Sullivan
--   2009, (c) Duncan Coutts 2009
module GHC.IO.Encoding.UTF32
utf32 :: TextEncoding
mkUTF32 :: CodingFailureMode -> TextEncoding
utf32_decode :: IORef (Maybe DecodeBuffer) -> DecodeBuffer
utf32_encode :: IORef Bool -> EncodeBuffer
utf32be :: TextEncoding
mkUTF32be :: CodingFailureMode -> TextEncoding
utf32be_decode :: DecodeBuffer
utf32be_encode :: EncodeBuffer
utf32le :: TextEncoding
mkUTF32le :: CodingFailureMode -> TextEncoding
utf32le_decode :: DecodeBuffer
utf32le_encode :: EncodeBuffer


-- | Utilities for primitive marshaling
module Foreign.Marshal.Utils

-- | <tt><a>with</a> val f</tt> executes the computation <tt>f</tt>,
--   passing as argument a pointer to a temporarily allocated block of
--   memory into which <tt>val</tt> has been marshalled (the combination of
--   <a>alloca</a> and <a>poke</a>).
--   
--   The memory is freed when <tt>f</tt> terminates (either normally or via
--   an exception), so the pointer passed to <tt>f</tt> must <i>not</i> be
--   used after this.
with :: Storable a => a -> (Ptr a -> IO b) -> IO b

-- | Allocate a block of memory and marshal a value into it (the
--   combination of <a>malloc</a> and <a>poke</a>). The size of the area
--   allocated is determined by the <a>sizeOf</a> method from the instance
--   of <a>Storable</a> for the appropriate type.
--   
--   The memory may be deallocated using <a>free</a> or
--   <a>finalizerFree</a> when no longer required.
new :: Storable a => a -> IO (Ptr a)

-- | Convert a Haskell <a>Bool</a> to its numeric representation
fromBool :: Num a => Bool -> a

-- | Convert a Boolean in numeric representation to a Haskell value
toBool :: (Eq a, Num a) => a -> Bool

-- | Allocate storage and marshal a storable value wrapped into a
--   <a>Maybe</a>
--   
--   <ul>
--   <li>the <a>nullPtr</a> is used to represent <a>Nothing</a></li>
--   </ul>
maybeNew :: (a -> IO (Ptr b)) -> (Maybe a -> IO (Ptr b))

-- | Converts a <tt>withXXX</tt> combinator into one marshalling a value
--   wrapped into a <a>Maybe</a>, using <a>nullPtr</a> to represent
--   <a>Nothing</a>.
maybeWith :: (a -> (Ptr b -> IO c) -> IO c) -> (Maybe a -> (Ptr b -> IO c) -> IO c)

-- | Convert a peek combinator into a one returning <a>Nothing</a> if
--   applied to a <a>nullPtr</a>
maybePeek :: (Ptr a -> IO b) -> Ptr a -> IO (Maybe b)

-- | Replicates a <tt>withXXX</tt> combinator over a list of objects,
--   yielding a list of marshalled objects
withMany :: (a -> (b -> res) -> res) -> [a] -> ([b] -> res) -> res

-- | Copies the given number of bytes from the second area (source) into
--   the first (destination); the copied areas may <i>not</i> overlap
copyBytes :: Ptr a -> Ptr a -> Int -> IO ()

-- | Copies the given number of bytes from the second area (source) into
--   the first (destination); the copied areas <i>may</i> overlap
moveBytes :: Ptr a -> Ptr a -> Int -> IO ()


-- | Marshalling support: routines allocating, storing, and retrieving
--   Haskell lists that are represented as arrays in the foreign language
module Foreign.Marshal.Array

-- | Allocate storage for the given number of elements of a storable type
--   (like <a>malloc</a>, but for multiple elements).
mallocArray :: Storable a => Int -> IO (Ptr a)

-- | Like <a>mallocArray</a>, but add an extra position to hold a special
--   termination element.
mallocArray0 :: Storable a => Int -> IO (Ptr a)

-- | Temporarily allocate space for the given number of elements (like
--   <a>alloca</a>, but for multiple elements).
allocaArray :: Storable a => Int -> (Ptr a -> IO b) -> IO b

-- | Like <a>allocaArray</a>, but add an extra position to hold a special
--   termination element.
allocaArray0 :: Storable a => Int -> (Ptr a -> IO b) -> IO b

-- | Adjust the size of an array
reallocArray :: Storable a => Ptr a -> Int -> IO (Ptr a)

-- | Adjust the size of an array including an extra position for the end
--   marker.
reallocArray0 :: Storable a => Ptr a -> Int -> IO (Ptr a)

-- | Convert an array of given length into a Haskell list. The
--   implementation is tail-recursive and so uses constant stack space.
peekArray :: Storable a => Int -> Ptr a -> IO [a]

-- | Convert an array terminated by the given end marker into a Haskell
--   list
peekArray0 :: (Storable a, Eq a) => a -> Ptr a -> IO [a]

-- | Write the list elements consecutive into memory
pokeArray :: Storable a => Ptr a -> [a] -> IO ()

-- | Write the list elements consecutive into memory and terminate them
--   with the given marker element
pokeArray0 :: Storable a => a -> Ptr a -> [a] -> IO ()

-- | Write a list of storable elements into a newly allocated, consecutive
--   sequence of storable values (like <a>new</a>, but for multiple
--   elements).
newArray :: Storable a => [a] -> IO (Ptr a)

-- | Write a list of storable elements into a newly allocated, consecutive
--   sequence of storable values, where the end is fixed by the given end
--   marker
newArray0 :: Storable a => a -> [a] -> IO (Ptr a)

-- | Temporarily store a list of storable values in memory (like
--   <a>with</a>, but for multiple elements).
withArray :: Storable a => [a] -> (Ptr a -> IO b) -> IO b

-- | Like <a>withArray</a>, but a terminator indicates where the array ends
withArray0 :: Storable a => a -> [a] -> (Ptr a -> IO b) -> IO b

-- | Like <a>withArray</a>, but the action gets the number of values as an
--   additional parameter
withArrayLen :: Storable a => [a] -> (Int -> Ptr a -> IO b) -> IO b

-- | Like <a>withArrayLen</a>, but a terminator indicates where the array
--   ends
withArrayLen0 :: Storable a => a -> [a] -> (Int -> Ptr a -> IO b) -> IO b

-- | Copy the given number of elements from the second array (source) into
--   the first array (destination); the copied areas may <i>not</i> overlap
copyArray :: Storable a => Ptr a -> Ptr a -> Int -> IO ()

-- | Copy the given number of elements from the second array (source) into
--   the first array (destination); the copied areas <i>may</i> overlap
moveArray :: Storable a => Ptr a -> Ptr a -> Int -> IO ()

-- | Return the number of elements in an array, excluding the terminator
lengthArray0 :: (Storable a, Eq a) => a -> Ptr a -> IO Int

-- | Advance a pointer into an array by the given number of elements
advancePtr :: Storable a => Ptr a -> Int -> Ptr a


-- | Foreign marshalling support for CStrings with configurable encodings
module GHC.Foreign

-- | Marshal a NUL terminated C string into a Haskell string.
peekCString :: TextEncoding -> CString -> IO String

-- | Marshal a C string with explicit length into a Haskell string.
peekCStringLen :: TextEncoding -> CStringLen -> IO String

-- | Marshal a Haskell string into a NUL terminated C string.
--   
--   <ul>
--   <li>the Haskell string may <i>not</i> contain any NUL characters</li>
--   <li>new storage is allocated for the C string and must be explicitly
--   freed using <a>free</a> or <a>finalizerFree</a>.</li>
--   </ul>
newCString :: TextEncoding -> String -> IO CString

-- | Marshal a Haskell string into a C string (ie, character array) with
--   explicit length information.
--   
--   <ul>
--   <li>new storage is allocated for the C string and must be explicitly
--   freed using <a>free</a> or <a>finalizerFree</a>.</li>
--   </ul>
newCStringLen :: TextEncoding -> String -> IO CStringLen

-- | Marshal a Haskell string into a NUL terminated C string using
--   temporary storage.
--   
--   <ul>
--   <li>the Haskell string may <i>not</i> contain any NUL characters</li>
--   <li>the memory is freed when the subcomputation terminates (either
--   normally or via an exception), so the pointer to the temporary storage
--   must <i>not</i> be used after this.</li>
--   </ul>
withCString :: TextEncoding -> String -> (CString -> IO a) -> IO a

-- | Marshal a Haskell string into a C string (ie, character array) in
--   temporary storage, with explicit length information.
--   
--   <ul>
--   <li>the memory is freed when the subcomputation terminates (either
--   normally or via an exception), so the pointer to the temporary storage
--   must <i>not</i> be used after this.</li>
--   </ul>
withCStringLen :: TextEncoding -> String -> (CStringLen -> IO a) -> IO a

-- | Determines whether a character can be accurately encoded in a
--   <a>CString</a>.
--   
--   Pretty much anyone who uses this function is in a state of sin because
--   whether or not a character is encodable will, in general, depend on
--   the context in which it occurs.
charIsRepresentable :: TextEncoding -> Char -> IO Bool


-- | Utilities for primitive marshalling of C strings.
--   
--   The marshalling converts each Haskell character, representing a
--   Unicode code point, to one or more bytes in a manner that, by default,
--   is determined by the current locale. As a consequence, no guarantees
--   can be made about the relative length of a Haskell string and its
--   corresponding C string, and therefore all the marshalling routines
--   include memory allocation. The translation between Unicode and the
--   encoding of the current locale may be lossy.
module Foreign.C.String

-- | A C string is a reference to an array of C characters terminated by
--   NUL.
type CString = Ptr CChar

-- | A string with explicit length information in bytes instead of a
--   terminating NUL (allowing NUL characters in the middle of the string).
type CStringLen = (Ptr CChar, Int)

-- | Marshal a NUL terminated C string into a Haskell string.
peekCString :: CString -> IO String

-- | Marshal a C string with explicit length into a Haskell string.
peekCStringLen :: CStringLen -> IO String

-- | Marshal a Haskell string into a NUL terminated C string.
--   
--   <ul>
--   <li>the Haskell string may <i>not</i> contain any NUL characters</li>
--   <li>new storage is allocated for the C string and must be explicitly
--   freed using <a>free</a> or <a>finalizerFree</a>.</li>
--   </ul>
newCString :: String -> IO CString

-- | Marshal a Haskell string into a C string (ie, character array) with
--   explicit length information.
--   
--   <ul>
--   <li>new storage is allocated for the C string and must be explicitly
--   freed using <a>free</a> or <a>finalizerFree</a>.</li>
--   </ul>
newCStringLen :: String -> IO CStringLen

-- | Marshal a Haskell string into a NUL terminated C string using
--   temporary storage.
--   
--   <ul>
--   <li>the Haskell string may <i>not</i> contain any NUL characters</li>
--   <li>the memory is freed when the subcomputation terminates (either
--   normally or via an exception), so the pointer to the temporary storage
--   must <i>not</i> be used after this.</li>
--   </ul>
withCString :: String -> (CString -> IO a) -> IO a

-- | Marshal a Haskell string into a C string (ie, character array) in
--   temporary storage, with explicit length information.
--   
--   <ul>
--   <li>the memory is freed when the subcomputation terminates (either
--   normally or via an exception), so the pointer to the temporary storage
--   must <i>not</i> be used after this.</li>
--   </ul>
withCStringLen :: String -> (CStringLen -> IO a) -> IO a
charIsRepresentable :: Char -> IO Bool

-- | Convert a Haskell character to a C character. This function is only
--   safe on the first 256 characters.
castCharToCChar :: Char -> CChar

-- | Convert a C byte, representing a Latin-1 character, to the
--   corresponding Haskell character.
castCCharToChar :: CChar -> Char

-- | Convert a Haskell character to a C <tt>unsigned char</tt>. This
--   function is only safe on the first 256 characters.
castCharToCUChar :: Char -> CUChar

-- | Convert a C <tt>unsigned char</tt>, representing a Latin-1 character,
--   to the corresponding Haskell character.
castCUCharToChar :: CUChar -> Char

-- | Convert a Haskell character to a C <tt>signed char</tt>. This function
--   is only safe on the first 256 characters.
castCharToCSChar :: Char -> CSChar

-- | Convert a C <tt>signed char</tt>, representing a Latin-1 character, to
--   the corresponding Haskell character.
castCSCharToChar :: CSChar -> Char

-- | Marshal a NUL terminated C string into a Haskell string.
peekCAString :: CString -> IO String

-- | Marshal a C string with explicit length into a Haskell string.
peekCAStringLen :: CStringLen -> IO String

-- | Marshal a Haskell string into a NUL terminated C string.
--   
--   <ul>
--   <li>the Haskell string may <i>not</i> contain any NUL characters</li>
--   <li>new storage is allocated for the C string and must be explicitly
--   freed using <a>free</a> or <a>finalizerFree</a>.</li>
--   </ul>
newCAString :: String -> IO CString

-- | Marshal a Haskell string into a C string (ie, character array) with
--   explicit length information.
--   
--   <ul>
--   <li>new storage is allocated for the C string and must be explicitly
--   freed using <a>free</a> or <a>finalizerFree</a>.</li>
--   </ul>
newCAStringLen :: String -> IO CStringLen

-- | Marshal a Haskell string into a NUL terminated C string using
--   temporary storage.
--   
--   <ul>
--   <li>the Haskell string may <i>not</i> contain any NUL characters</li>
--   <li>the memory is freed when the subcomputation terminates (either
--   normally or via an exception), so the pointer to the temporary storage
--   must <i>not</i> be used after this.</li>
--   </ul>
withCAString :: String -> (CString -> IO a) -> IO a

-- | Marshal a Haskell string into a C string (ie, character array) in
--   temporary storage, with explicit length information.
--   
--   <ul>
--   <li>the memory is freed when the subcomputation terminates (either
--   normally or via an exception), so the pointer to the temporary storage
--   must <i>not</i> be used after this.</li>
--   </ul>
withCAStringLen :: String -> (CStringLen -> IO a) -> IO a

-- | A C wide string is a reference to an array of C wide characters
--   terminated by NUL.
type CWString = Ptr CWchar

-- | A wide character string with explicit length information in
--   <a>CWchar</a>s instead of a terminating NUL (allowing NUL characters
--   in the middle of the string).
type CWStringLen = (Ptr CWchar, Int)

-- | Marshal a NUL terminated C wide string into a Haskell string.
peekCWString :: CWString -> IO String

-- | Marshal a C wide string with explicit length into a Haskell string.
peekCWStringLen :: CWStringLen -> IO String

-- | Marshal a Haskell string into a NUL terminated C wide string.
--   
--   <ul>
--   <li>the Haskell string may <i>not</i> contain any NUL characters</li>
--   <li>new storage is allocated for the C wide string and must be
--   explicitly freed using <a>free</a> or <a>finalizerFree</a>.</li>
--   </ul>
newCWString :: String -> IO CWString

-- | Marshal a Haskell string into a C wide string (ie, wide character
--   array) with explicit length information.
--   
--   <ul>
--   <li>new storage is allocated for the C wide string and must be
--   explicitly freed using <a>free</a> or <a>finalizerFree</a>.</li>
--   </ul>
newCWStringLen :: String -> IO CWStringLen

-- | Marshal a Haskell string into a NUL terminated C wide string using
--   temporary storage.
--   
--   <ul>
--   <li>the Haskell string may <i>not</i> contain any NUL characters</li>
--   <li>the memory is freed when the subcomputation terminates (either
--   normally or via an exception), so the pointer to the temporary storage
--   must <i>not</i> be used after this.</li>
--   </ul>
withCWString :: String -> (CWString -> IO a) -> IO a

-- | Marshal a Haskell string into a C wide string (i.e. wide character
--   array) in temporary storage, with explicit length information.
--   
--   <ul>
--   <li>the memory is freed when the subcomputation terminates (either
--   normally or via an exception), so the pointer to the temporary storage
--   must <i>not</i> be used after this.</li>
--   </ul>
withCWStringLen :: String -> (CWStringLen -> IO a) -> IO a


-- | C-specific Marshalling support: Handling of C "errno" error codes.
module Foreign.C.Error

-- | Haskell representation for <tt>errno</tt> values. The implementation
--   is deliberately exposed, to allow users to add their own definitions
--   of <a>Errno</a> values.
newtype Errno
Errno :: CInt -> Errno
eOK :: Errno
e2BIG :: Errno
eACCES :: Errno
eADDRINUSE :: Errno
eADDRNOTAVAIL :: Errno
eADV :: Errno
eAFNOSUPPORT :: Errno
eAGAIN :: Errno
eALREADY :: Errno
eBADF :: Errno
eBADMSG :: Errno
eBADRPC :: Errno
eBUSY :: Errno
eCHILD :: Errno
eCOMM :: Errno
eCONNABORTED :: Errno
eCONNREFUSED :: Errno
eCONNRESET :: Errno
eDEADLK :: Errno
eDESTADDRREQ :: Errno
eDIRTY :: Errno
eDOM :: Errno
eDQUOT :: Errno
eEXIST :: Errno
eFAULT :: Errno
eFBIG :: Errno
eFTYPE :: Errno
eHOSTDOWN :: Errno
eHOSTUNREACH :: Errno
eIDRM :: Errno
eILSEQ :: Errno
eINPROGRESS :: Errno
eINTR :: Errno
eINVAL :: Errno
eIO :: Errno
eISCONN :: Errno
eISDIR :: Errno
eLOOP :: Errno
eMFILE :: Errno
eMLINK :: Errno
eMSGSIZE :: Errno
eMULTIHOP :: Errno
eNAMETOOLONG :: Errno
eNETDOWN :: Errno
eNETRESET :: Errno
eNETUNREACH :: Errno
eNFILE :: Errno
eNOBUFS :: Errno
eNODATA :: Errno
eNODEV :: Errno
eNOENT :: Errno
eNOEXEC :: Errno
eNOLCK :: Errno
eNOLINK :: Errno
eNOMEM :: Errno
eNOMSG :: Errno
eNONET :: Errno
eNOPROTOOPT :: Errno
eNOSPC :: Errno
eNOSR :: Errno
eNOSTR :: Errno
eNOSYS :: Errno
eNOTBLK :: Errno
eNOTCONN :: Errno
eNOTDIR :: Errno
eNOTEMPTY :: Errno
eNOTSOCK :: Errno
eNOTTY :: Errno
eNXIO :: Errno
eOPNOTSUPP :: Errno
ePERM :: Errno
ePFNOSUPPORT :: Errno
ePIPE :: Errno
ePROCLIM :: Errno
ePROCUNAVAIL :: Errno
ePROGMISMATCH :: Errno
ePROGUNAVAIL :: Errno
ePROTO :: Errno
ePROTONOSUPPORT :: Errno
ePROTOTYPE :: Errno
eRANGE :: Errno
eREMCHG :: Errno
eREMOTE :: Errno
eROFS :: Errno
eRPCMISMATCH :: Errno
eRREMOTE :: Errno
eSHUTDOWN :: Errno
eSOCKTNOSUPPORT :: Errno
eSPIPE :: Errno
eSRCH :: Errno
eSRMNT :: Errno
eSTALE :: Errno
eTIME :: Errno
eTIMEDOUT :: Errno
eTOOMANYREFS :: Errno
eTXTBSY :: Errno
eUSERS :: Errno
eWOULDBLOCK :: Errno
eXDEV :: Errno

-- | Yield <a>True</a> if the given <a>Errno</a> value is valid on the
--   system. This implies that the <a>Eq</a> instance of <a>Errno</a> is
--   also system dependent as it is only defined for valid values of
--   <a>Errno</a>.
isValidErrno :: Errno -> Bool

-- | Get the current value of <tt>errno</tt> in the current thread.
getErrno :: IO Errno

-- | Reset the current thread's <tt>errno</tt> value to <a>eOK</a>.
resetErrno :: IO ()

-- | Construct an <a>IOError</a> based on the given <a>Errno</a> value. The
--   optional information can be used to improve the accuracy of error
--   messages.
errnoToIOError :: String -> Errno -> Maybe Handle -> Maybe String -> IOError

-- | Throw an <a>IOError</a> corresponding to the current value of
--   <a>getErrno</a>.
throwErrno :: String -> IO a

-- | Throw an <a>IOError</a> corresponding to the current value of
--   <a>getErrno</a> if the result value of the <a>IO</a> action meets the
--   given predicate.
throwErrnoIf :: (a -> Bool) -> String -> IO a -> IO a

-- | as <a>throwErrnoIf</a>, but discards the result of the <a>IO</a>
--   action after error handling.
throwErrnoIf_ :: (a -> Bool) -> String -> IO a -> IO ()

-- | as <a>throwErrnoIf</a>, but retry the <a>IO</a> action when it yields
--   the error code <a>eINTR</a> - this amounts to the standard retry loop
--   for interrupted POSIX system calls.
throwErrnoIfRetry :: (a -> Bool) -> String -> IO a -> IO a

-- | as <a>throwErrnoIfRetry</a>, but discards the result.
throwErrnoIfRetry_ :: (a -> Bool) -> String -> IO a -> IO ()

-- | Throw an <a>IOError</a> corresponding to the current value of
--   <a>getErrno</a> if the <a>IO</a> action returns a result of
--   <tt>-1</tt>.
throwErrnoIfMinus1 :: (Eq a, Num a) => String -> IO a -> IO a

-- | as <a>throwErrnoIfMinus1</a>, but discards the result.
throwErrnoIfMinus1_ :: (Eq a, Num a) => String -> IO a -> IO ()

-- | Throw an <a>IOError</a> corresponding to the current value of
--   <a>getErrno</a> if the <a>IO</a> action returns a result of
--   <tt>-1</tt>, but retries in case of an interrupted operation.
throwErrnoIfMinus1Retry :: (Eq a, Num a) => String -> IO a -> IO a

-- | as <a>throwErrnoIfMinus1</a>, but discards the result.
throwErrnoIfMinus1Retry_ :: (Eq a, Num a) => String -> IO a -> IO ()

-- | Throw an <a>IOError</a> corresponding to the current value of
--   <a>getErrno</a> if the <a>IO</a> action returns <a>nullPtr</a>.
throwErrnoIfNull :: String -> IO (Ptr a) -> IO (Ptr a)

-- | Throw an <a>IOError</a> corresponding to the current value of
--   <a>getErrno</a> if the <a>IO</a> action returns <a>nullPtr</a>, but
--   retry in case of an interrupted operation.
throwErrnoIfNullRetry :: String -> IO (Ptr a) -> IO (Ptr a)

-- | as <a>throwErrnoIfRetry</a>, but additionally if the operation yields
--   the error code <a>eAGAIN</a> or <a>eWOULDBLOCK</a>, an alternative
--   action is executed before retrying.
throwErrnoIfRetryMayBlock :: (a -> Bool) -> String -> IO a -> IO b -> IO a

-- | as <a>throwErrnoIfRetryMayBlock</a>, but discards the result.
throwErrnoIfRetryMayBlock_ :: (a -> Bool) -> String -> IO a -> IO b -> IO ()

-- | as <a>throwErrnoIfMinus1Retry</a>, but checks for operations that
--   would block.
throwErrnoIfMinus1RetryMayBlock :: (Eq a, Num a) => String -> IO a -> IO b -> IO a

-- | as <a>throwErrnoIfMinus1RetryMayBlock</a>, but discards the result.
throwErrnoIfMinus1RetryMayBlock_ :: (Eq a, Num a) => String -> IO a -> IO b -> IO ()

-- | as <a>throwErrnoIfNullRetry</a>, but checks for operations that would
--   block.
throwErrnoIfNullRetryMayBlock :: String -> IO (Ptr a) -> IO b -> IO (Ptr a)

-- | as <a>throwErrno</a>, but exceptions include the given path when
--   appropriate.
throwErrnoPath :: String -> FilePath -> IO a

-- | as <a>throwErrnoIf</a>, but exceptions include the given path when
--   appropriate.
throwErrnoPathIf :: (a -> Bool) -> String -> FilePath -> IO a -> IO a

-- | as <a>throwErrnoIf_</a>, but exceptions include the given path when
--   appropriate.
throwErrnoPathIf_ :: (a -> Bool) -> String -> FilePath -> IO a -> IO ()

-- | as <a>throwErrnoIfNull</a>, but exceptions include the given path when
--   appropriate.
throwErrnoPathIfNull :: String -> FilePath -> IO (Ptr a) -> IO (Ptr a)

-- | as <a>throwErrnoIfMinus1</a>, but exceptions include the given path
--   when appropriate.
throwErrnoPathIfMinus1 :: (Eq a, Num a) => String -> FilePath -> IO a -> IO a

-- | as <a>throwErrnoIfMinus1_</a>, but exceptions include the given path
--   when appropriate.
throwErrnoPathIfMinus1_ :: (Eq a, Num a) => String -> FilePath -> IO a -> IO ()
instance Eq Errno


-- | Bundles the C specific FFI library functionality
module Foreign.C


-- | Routines for testing return values and raising a <a>userError</a>
--   exception in case of values indicating an error state.
module Foreign.Marshal.Error

-- | Execute an <a>IO</a> action, throwing a <a>userError</a> if the
--   predicate yields <a>True</a> when applied to the result returned by
--   the <a>IO</a> action. If no exception is raised, return the result of
--   the computation.
throwIf :: (a -> Bool) -> (a -> String) -> IO a -> IO a

-- | Like <a>throwIf</a>, but discarding the result
throwIf_ :: (a -> Bool) -> (a -> String) -> IO a -> IO ()

-- | Guards against negative result values
throwIfNeg :: (Ord a, Num a) => (a -> String) -> IO a -> IO a

-- | Like <a>throwIfNeg</a>, but discarding the result
throwIfNeg_ :: (Ord a, Num a) => (a -> String) -> IO a -> IO ()

-- | Guards against null pointers
throwIfNull :: String -> IO (Ptr a) -> IO (Ptr a)

-- | Discard the return value of an <a>IO</a> action

-- | <i>Deprecated: use Control.Monad.void instead </i>
void :: IO a -> IO ()


-- | This module contains support for pooled memory management. Under this
--   scheme, (re-)allocations belong to a given pool, and everything in a
--   pool is deallocated when the pool itself is deallocated. This is
--   useful when <a>alloca</a> with its implicit allocation and
--   deallocation is not flexible enough, but explicit uses of
--   <a>malloc</a> and <a>free</a> are too awkward.
module Foreign.Marshal.Pool

-- | A memory pool.
data Pool

-- | Allocate a fresh memory pool.
newPool :: IO Pool

-- | Deallocate a memory pool and everything which has been allocated in
--   the pool itself.
freePool :: Pool -> IO ()

-- | Execute an action with a fresh memory pool, which gets automatically
--   deallocated (including its contents) after the action has finished.
withPool :: (Pool -> IO b) -> IO b

-- | Allocate space for storable type in the given pool. The size of the
--   area allocated is determined by the <a>sizeOf</a> method from the
--   instance of <a>Storable</a> for the appropriate type.
pooledMalloc :: Storable a => Pool -> IO (Ptr a)

-- | Allocate the given number of bytes of storage in the pool.
pooledMallocBytes :: Pool -> Int -> IO (Ptr a)

-- | Adjust the storage area for an element in the pool to the given size
--   of the required type.
pooledRealloc :: Storable a => Pool -> Ptr a -> IO (Ptr a)

-- | Adjust the storage area for an element in the pool to the given size.
pooledReallocBytes :: Pool -> Ptr a -> Int -> IO (Ptr a)

-- | Allocate storage for the given number of elements of a storable type
--   in the pool.
pooledMallocArray :: Storable a => Pool -> Int -> IO (Ptr a)

-- | Allocate storage for the given number of elements of a storable type
--   in the pool, but leave room for an extra element to signal the end of
--   the array.
pooledMallocArray0 :: Storable a => Pool -> Int -> IO (Ptr a)

-- | Adjust the size of an array in the given pool.
pooledReallocArray :: Storable a => Pool -> Ptr a -> Int -> IO (Ptr a)

-- | Adjust the size of an array with an end marker in the given pool.
pooledReallocArray0 :: Storable a => Pool -> Ptr a -> Int -> IO (Ptr a)

-- | Allocate storage for a value in the given pool and marshal the value
--   into this storage.
pooledNew :: Storable a => Pool -> a -> IO (Ptr a)

-- | Allocate consecutive storage for a list of values in the given pool
--   and marshal these values into it.
pooledNewArray :: Storable a => Pool -> [a] -> IO (Ptr a)

-- | Allocate consecutive storage for a list of values in the given pool
--   and marshal these values into it, terminating the end with the given
--   marker.
pooledNewArray0 :: Storable a => Pool -> a -> [a] -> IO (Ptr a)


-- | Marshalling support
--   
--   Safe API Only.
module Foreign.Marshal.Safe


-- | Marshalling support
module Foreign.Marshal

-- | Sometimes an external entity is a pure function, except that it passes
--   arguments and/or results via pointers. The function
--   <tt>unsafeLocalState</tt> permits the packaging of such entities as
--   pure functions.
--   
--   The only IO operations allowed in the IO action passed to
--   <tt>unsafeLocalState</tt> are (a) local allocation (<tt>alloca</tt>,
--   <tt>allocaBytes</tt> and derived operations such as <tt>withArray</tt>
--   and <tt>withCString</tt>), and (b) pointer operations
--   (<tt>Foreign.Storable</tt> and <tt>Foreign.Ptr</tt>) on the pointers
--   to local storage, and (c) foreign functions whose only observable
--   effect is to read and/or write the locally allocated memory. Passing
--   an IO operation that does not obey these rules results in undefined
--   behaviour.
--   
--   It is expected that this operation will be replaced in a future
--   revision of Haskell.

-- | <i>Deprecated: Please import from Foreign.Marshall.Unsafe instead;
--   This will be removed in the next release </i>
unsafeLocalState :: IO a -> a


-- | A collection of data types, classes, and functions for interfacing
--   with another programming language.
module Foreign

-- | The type <a>ForeignPtr</a> represents references to objects that are
--   maintained in a foreign language, i.e., that are not part of the data
--   structures usually managed by the Haskell storage manager. The
--   essential difference between <a>ForeignPtr</a>s and vanilla memory
--   references of type <tt>Ptr a</tt> is that the former may be associated
--   with <i>finalizers</i>. A finalizer is a routine that is invoked when
--   the Haskell storage manager detects that - within the Haskell heap and
--   stack - there are no more references left that are pointing to the
--   <a>ForeignPtr</a>. Typically, the finalizer will, then, invoke
--   routines in the foreign language that free the resources bound by the
--   foreign object.
--   
--   The <a>ForeignPtr</a> is parameterised in the same way as <a>Ptr</a>.
--   The type argument of <a>ForeignPtr</a> should normally be an instance
--   of class <a>Storable</a>.
data ForeignPtr a

-- | A finalizer is represented as a pointer to a foreign function that, at
--   finalisation time, gets as an argument a plain pointer variant of the
--   foreign pointer that the finalizer is associated with.
type FinalizerPtr a = FunPtr (Ptr a -> IO ())
type FinalizerEnvPtr env a = FunPtr (Ptr env -> Ptr a -> IO ())

-- | Turns a plain memory reference into a foreign pointer, and associates
--   a finalizer with the reference. The finalizer will be executed after
--   the last reference to the foreign object is dropped. There is no
--   guarantee of promptness, however the finalizer will be executed before
--   the program exits.
newForeignPtr :: FinalizerPtr a -> Ptr a -> IO (ForeignPtr a)

-- | Turns a plain memory reference into a foreign pointer that may be
--   associated with finalizers by using <a>addForeignPtrFinalizer</a>.
newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)

-- | This function adds a finalizer to the given foreign object. The
--   finalizer will run <i>before</i> all other finalizers for the same
--   object which have already been registered.
addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()

-- | This variant of <a>newForeignPtr</a> adds a finalizer that expects an
--   environment in addition to the finalized pointer. The environment that
--   will be passed to the finalizer is fixed by the second argument to
--   <a>newForeignPtrEnv</a>.
newForeignPtrEnv :: FinalizerEnvPtr env a -> Ptr env -> Ptr a -> IO (ForeignPtr a)

-- | Like <a>addForeignPtrFinalizerEnv</a> but allows the finalizer to be
--   passed an additional environment parameter to be passed to the
--   finalizer. The environment passed to the finalizer is fixed by the
--   second argument to <a>addForeignPtrFinalizerEnv</a>
addForeignPtrFinalizerEnv :: FinalizerEnvPtr env a -> Ptr env -> ForeignPtr a -> IO ()

-- | This is a way to look at the pointer living inside a foreign object.
--   This function takes a function which is applied to that pointer. The
--   resulting <a>IO</a> action is then executed. The foreign object is
--   kept alive at least during the whole action, even if it is not used
--   directly inside. Note that it is not safe to return the pointer from
--   the action and use it after the action completes. All uses of the
--   pointer should be inside the <a>withForeignPtr</a> bracket. The reason
--   for this unsafeness is the same as for <a>unsafeForeignPtrToPtr</a>
--   below: the finalizer may run earlier than expected, because the
--   compiler can only track usage of the <a>ForeignPtr</a> object, not a
--   <a>Ptr</a> object made from it.
--   
--   This function is normally used for marshalling data to or from the
--   object pointed to by the <a>ForeignPtr</a>, using the operations from
--   the <a>Storable</a> class.
withForeignPtr :: ForeignPtr a -> (Ptr a -> IO b) -> IO b

-- | Causes the finalizers associated with a foreign pointer to be run
--   immediately.
finalizeForeignPtr :: ForeignPtr a -> IO ()

-- | This function ensures that the foreign object in question is alive at
--   the given place in the sequence of IO actions. In particular
--   <a>withForeignPtr</a> does a <a>touchForeignPtr</a> after it executes
--   the user action.
--   
--   Note that this function should not be used to express dependencies
--   between finalizers on <a>ForeignPtr</a>s. For example, if the
--   finalizer for a <a>ForeignPtr</a> <tt>F1</tt> calls
--   <a>touchForeignPtr</a> on a second <a>ForeignPtr</a> <tt>F2</tt>, then
--   the only guarantee is that the finalizer for <tt>F2</tt> is never
--   started before the finalizer for <tt>F1</tt>. They might be started
--   together if for example both <tt>F1</tt> and <tt>F2</tt> are otherwise
--   unreachable, and in that case the scheduler might end up running the
--   finalizer for <tt>F2</tt> first.
--   
--   In general, it is not recommended to use finalizers on separate
--   objects with ordering constraints between them. To express the
--   ordering robustly requires explicit synchronisation using
--   <tt>MVar</tt>s between the finalizers, but even then the runtime
--   sometimes runs multiple finalizers sequentially in a single thread
--   (for performance reasons), so synchronisation between finalizers could
--   result in artificial deadlock. Another alternative is to use explicit
--   reference counting.
touchForeignPtr :: ForeignPtr a -> IO ()

-- | This function casts a <a>ForeignPtr</a> parameterised by one type into
--   another type.
castForeignPtr :: ForeignPtr a -> ForeignPtr b

-- | Allocate some memory and return a <a>ForeignPtr</a> to it. The memory
--   will be released automatically when the <a>ForeignPtr</a> is
--   discarded.
--   
--   <a>mallocForeignPtr</a> is equivalent to
--   
--   <pre>
--   do { p &lt;- malloc; newForeignPtr finalizerFree p }
--   </pre>
--   
--   although it may be implemented differently internally: you may not
--   assume that the memory returned by <a>mallocForeignPtr</a> has been
--   allocated with <a>malloc</a>.
--   
--   GHC notes: <a>mallocForeignPtr</a> has a heavily optimised
--   implementation in GHC. It uses pinned memory in the garbage collected
--   heap, so the <a>ForeignPtr</a> does not require a finalizer to free
--   the memory. Use of <a>mallocForeignPtr</a> and associated functions is
--   strongly recommended in preference to <tt>newForeignPtr</tt> with a
--   finalizer.
mallocForeignPtr :: Storable a => IO (ForeignPtr a)

-- | This function is similar to <a>mallocForeignPtr</a>, except that the
--   size of the memory required is given explicitly as a number of bytes.
mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)

-- | This function is similar to <a>mallocArray</a>, but yields a memory
--   area that has a finalizer attached that releases the memory area. As
--   with <a>mallocForeignPtr</a>, it is not guaranteed that the block of
--   memory was allocated by <a>malloc</a>.
mallocForeignPtrArray :: Storable a => Int -> IO (ForeignPtr a)

-- | This function is similar to <a>mallocArray0</a>, but yields a memory
--   area that has a finalizer attached that releases the memory area. As
--   with <a>mallocForeignPtr</a>, it is not guaranteed that the block of
--   memory was allocated by <a>malloc</a>.
mallocForeignPtrArray0 :: Storable a => Int -> IO (ForeignPtr a)

-- | <i>Deprecated: Use Foreign.ForeignPtr.Unsafe.unsafeForeignPtrToPtr
--   instead; This function will be removed in the next release </i>
unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a

-- | <i>Deprecated: Use System.IO.Unsafe.unsafePerformIO instead; This
--   function will be removed in the next release </i>
unsafePerformIO :: IO a -> a


-- | Basic concurrency stuff.
module GHC.Conc.Sync

-- | A <a>ThreadId</a> is an abstract type representing a handle to a
--   thread. <a>ThreadId</a> is an instance of <a>Eq</a>, <a>Ord</a> and
--   <a>Show</a>, where the <a>Ord</a> instance implements an arbitrary
--   total ordering over <a>ThreadId</a>s. The <a>Show</a> instance lets
--   you convert an arbitrary-valued <a>ThreadId</a> to string form;
--   showing a <a>ThreadId</a> value is occasionally useful when debugging
--   or diagnosing the behaviour of a concurrent program.
--   
--   <i>Note</i>: in GHC, if you have a <a>ThreadId</a>, you essentially
--   have a pointer to the thread itself. This means the thread itself
--   can't be garbage collected until you drop the <a>ThreadId</a>. This
--   misfeature will hopefully be corrected at a later date.
--   
--   <i>Note</i>: Hugs does not provide any operations on other threads; it
--   defines <a>ThreadId</a> as a synonym for ().
data ThreadId
ThreadId :: ThreadId# -> ThreadId

-- | Sparks off a new thread to run the <a>IO</a> computation passed as the
--   first argument, and returns the <a>ThreadId</a> of the newly created
--   thread.
--   
--   The new thread will be a lightweight thread; if you want to use a
--   foreign library that uses thread-local storage, use <a>forkOS</a>
--   instead.
--   
--   GHC note: the new thread inherits the <i>masked</i> state of the
--   parent (see <a>mask</a>).
--   
--   The newly created thread has an exception handler that discards the
--   exceptions <a>BlockedIndefinitelyOnMVar</a>,
--   <a>BlockedIndefinitelyOnSTM</a>, and <a>ThreadKilled</a>, and passes
--   all other exceptions to the uncaught exception handler.
forkIO :: IO () -> IO ThreadId

-- | This function is deprecated; use <a>forkIOWithUnmask</a> instead

-- | <i>Deprecated: use forkIOWithUnmask instead </i>
forkIOUnmasked :: IO () -> IO ThreadId

-- | Like <a>forkIO</a>, but the child thread is passed a function that can
--   be used to unmask asynchronous exceptions. This function is typically
--   used in the following way
--   
--   <pre>
--   ... mask_ $ forkIOWithUnmask $ \unmask -&gt;
--                  catch (unmask ...) handler
--   </pre>
--   
--   so that the exception handler in the child thread is established with
--   asynchronous exceptions masked, meanwhile the main body of the child
--   thread is executed in the unmasked state.
--   
--   Note that the unmask function passed to the child thread should only
--   be used in that thread; the behaviour is undefined if it is invoked in
--   a different thread.
forkIOWithUnmask :: ((forall a. IO a -> IO a) -> IO ()) -> IO ThreadId

-- | Like <a>forkIO</a>, but lets you specify on which processor the thread
--   should run. Unlike a <a>forkIO</a> thread, a thread created by
--   <a>forkOn</a> will stay on the same processor for its entire lifetime
--   (<a>forkIO</a> threads can migrate between processors according to the
--   scheduling policy). <a>forkOn</a> is useful for overriding the
--   scheduling policy when you know in advance how best to distribute the
--   threads.
--   
--   The <a>Int</a> argument specifies a <i>capability number</i> (see
--   <a>getNumCapabilities</a>). Typically capabilities correspond to
--   physical processors, but the exact behaviour is
--   implementation-dependent. The value passed to <a>forkOn</a> is
--   interpreted modulo the total number of capabilities as returned by
--   <a>getNumCapabilities</a>.
--   
--   GHC note: the number of capabilities is specified by the <tt>+RTS
--   -N</tt> option when the program is started. Capabilities can be fixed
--   to actual processor cores with <tt>+RTS -qa</tt> if the underlying
--   operating system supports that, although in practice this is usually
--   unnecessary (and may actually degrade perforamnce in some cases -
--   experimentation is recommended).
forkOn :: Int -> IO () -> IO ThreadId

-- | This function is deprecated; use <a>forkOn</a> instead

-- | <i>Deprecated: renamed to forkOn </i>
forkOnIO :: Int -> IO () -> IO ThreadId

-- | This function is deprecated; use <tt>forkOnWIthUnmask</tt> instead

-- | <i>Deprecated: use forkOnWithUnmask instead </i>
forkOnIOUnmasked :: Int -> IO () -> IO ThreadId

-- | Like <a>forkIOWithUnmask</a>, but the child thread is pinned to the
--   given CPU, as with <a>forkOn</a>.
forkOnWithUnmask :: Int -> ((forall a. IO a -> IO a) -> IO ()) -> IO ThreadId

-- | the value passed to the <tt>+RTS -N</tt> flag. This is the number of
--   Haskell threads that can run truly simultaneously at any given time,
--   and is typically set to the number of physical processor cores on the
--   machine.
--   
--   Strictly speaking it is better to use <a>getNumCapabilities</a>,
--   because the number of capabilities might vary at runtime.
numCapabilities :: Int

-- | Returns the number of Haskell threads that can run truly
--   simultaneously (on separate physical processors) at any given time. To
--   change this value, use <a>setNumCapabilities</a>.
getNumCapabilities :: IO Int

-- | Set the number of Haskell threads that can run truly simultaneously
--   (on separate physical processors) at any given time. The number passed
--   to <a>forkOn</a> is interpreted modulo this value. The initial value
--   is given by the <tt>+RTS -N</tt> runtime flag.
--   
--   This is also the number of threads that will participate in parallel
--   garbage collection. It is strongly recommended that the number of
--   capabilities is not set larger than the number of physical processor
--   cores, and it may often be beneficial to leave one or more cores free
--   to avoid contention with other processes in the machine.
setNumCapabilities :: Int -> IO ()
getNumProcessors :: IO Int

-- | Returns the number of sparks currently in the local spark pool
numSparks :: IO Int
childHandler :: SomeException -> IO ()

-- | Returns the <a>ThreadId</a> of the calling thread (GHC only).
myThreadId :: IO ThreadId

-- | <a>killThread</a> raises the <a>ThreadKilled</a> exception in the
--   given thread (GHC only).
--   
--   <pre>
--   killThread tid = throwTo tid ThreadKilled
--   </pre>
killThread :: ThreadId -> IO ()

-- | <a>throwTo</a> raises an arbitrary exception in the target thread (GHC
--   only).
--   
--   <a>throwTo</a> does not return until the exception has been raised in
--   the target thread. The calling thread can thus be certain that the
--   target thread has received the exception. This is a useful property to
--   know when dealing with race conditions: eg. if there are two threads
--   that can kill each other, it is guaranteed that only one of the
--   threads will get to kill the other.
--   
--   Whatever work the target thread was doing when the exception was
--   raised is not lost: the computation is suspended until required by
--   another thread.
--   
--   If the target thread is currently making a foreign call, then the
--   exception will not be raised (and hence <a>throwTo</a> will not
--   return) until the call has completed. This is the case regardless of
--   whether the call is inside a <a>mask</a> or not. However, in GHC a
--   foreign call can be annotated as <tt>interruptible</tt>, in which case
--   a <a>throwTo</a> will cause the RTS to attempt to cause the call to
--   return; see the GHC documentation for more details.
--   
--   Important note: the behaviour of <a>throwTo</a> differs from that
--   described in the paper "Asynchronous exceptions in Haskell"
--   (<a>http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm</a>).
--   In the paper, <a>throwTo</a> is non-blocking; but the library
--   implementation adopts a more synchronous design in which
--   <a>throwTo</a> does not return until the exception is received by the
--   target thread. The trade-off is discussed in Section 9 of the paper.
--   Like any blocking operation, <a>throwTo</a> is therefore interruptible
--   (see Section 5.3 of the paper). Unlike other interruptible operations,
--   however, <a>throwTo</a> is <i>always</i> interruptible, even if it
--   does not actually block.
--   
--   There is no guarantee that the exception will be delivered promptly,
--   although the runtime will endeavour to ensure that arbitrary delays
--   don't occur. In GHC, an exception can only be raised when a thread
--   reaches a <i>safe point</i>, where a safe point is where memory
--   allocation occurs. Some loops do not perform any memory allocation
--   inside the loop and therefore cannot be interrupted by a
--   <a>throwTo</a>.
--   
--   If the target of <a>throwTo</a> is the calling thread, then the
--   behaviour is the same as <a>throwIO</a>, except that the exception is
--   thrown as an asynchronous exception. This means that if there is an
--   enclosing pure computation, which would be the case if the current IO
--   operation is inside <a>unsafePerformIO</a> or
--   <a>unsafeInterleaveIO</a>, that computation is not permanently
--   replaced by the exception, but is suspended as if it had received an
--   asynchronous exception.
--   
--   Note that if <a>throwTo</a> is called with the current thread as the
--   target, the exception will be thrown even if the thread is currently
--   inside <a>mask</a> or <a>uninterruptibleMask</a>.
throwTo :: Exception e => ThreadId -> e -> IO ()
par :: a -> b -> b
pseq :: a -> b -> b

-- | Internal function used by the RTS to run sparks.
runSparks :: IO ()

-- | The <a>yield</a> action allows (forces, in a co-operative multitasking
--   implementation) a context-switch to any other currently runnable
--   threads (if any), and is occasionally useful when implementing
--   concurrency abstractions.
yield :: IO ()

-- | <a>labelThread</a> stores a string as identifier for this thread if
--   you built a RTS with debugging support. This identifier will be used
--   in the debugging output to make distinction of different threads
--   easier (otherwise you only have the thread state object's address in
--   the heap).
--   
--   Other applications like the graphical Concurrent Haskell Debugger
--   (<a>http://www.informatik.uni-kiel.de/~fhu/chd/</a>) may choose to
--   overload <a>labelThread</a> for their purposes as well.
labelThread :: ThreadId -> String -> IO ()

-- | make a weak pointer to a <a>ThreadId</a>. It can be important to do
--   this if you want to hold a reference to a <a>ThreadId</a> while still
--   allowing the thread to receive the <tt>BlockedIndefinitely</tt> family
--   of exceptions (e.g. <a>BlockedIndefinitelyOnMVar</a>). Holding a
--   normal <a>ThreadId</a> reference will prevent the delivery of
--   <tt>BlockedIndefinitely</tt> exceptions because the reference could be
--   used as the target of <a>throwTo</a> at any time, which would unblock
--   the thread.
--   
--   Holding a <tt>Weak ThreadId</tt>, on the other hand, will not prevent
--   the thread from receiving <tt>BlockedIndefinitely</tt> exceptions. It
--   is still possible to throw an exception to a <tt>Weak ThreadId</tt>,
--   but the caller must use <tt>deRefWeak</tt> first to determine whether
--   the thread still exists.
mkWeakThreadId :: ThreadId -> IO (Weak ThreadId)

-- | The current status of a thread
data ThreadStatus

-- | the thread is currently runnable or running
ThreadRunning :: ThreadStatus

-- | the thread has finished
ThreadFinished :: ThreadStatus

-- | the thread is blocked on some resource
ThreadBlocked :: BlockReason -> ThreadStatus

-- | the thread received an uncaught exception
ThreadDied :: ThreadStatus
data BlockReason

-- | blocked on on <a>MVar</a>
BlockedOnMVar :: BlockReason

-- | blocked on a computation in progress by another thread
BlockedOnBlackHole :: BlockReason

-- | blocked in <a>throwTo</a>
BlockedOnException :: BlockReason

-- | blocked in <a>retry</a> in an STM transaction
BlockedOnSTM :: BlockReason

-- | currently in a foreign call
BlockedOnForeignCall :: BlockReason

-- | blocked on some other resource. Without <tt>-threaded</tt>, I/O and
--   <tt>threadDelay</tt> show up as <a>BlockedOnOther</a>, with
--   <tt>-threaded</tt> they show up as <a>BlockedOnMVar</a>.
BlockedOnOther :: BlockReason
threadStatus :: ThreadId -> IO ThreadStatus

-- | returns the number of the capability on which the thread is currently
--   running, and a boolean indicating whether the thread is locked to that
--   capability or not. A thread is locked to a capability if it was
--   created with <tt>forkOn</tt>.
threadCapability :: ThreadId -> IO (Int, Bool)

-- | A monad supporting atomic memory transactions.
newtype STM a
STM :: (State# RealWorld -> (# State# RealWorld, a #)) -> STM a

-- | Perform a series of STM actions atomically.
--   
--   You cannot use <a>atomically</a> inside an <a>unsafePerformIO</a> or
--   <a>unsafeInterleaveIO</a>. Any attempt to do so will result in a
--   runtime error. (Reason: allowing this would effectively allow a
--   transaction inside a transaction, depending on exactly when the thunk
--   is evaluated.)
--   
--   However, see <a>newTVarIO</a>, which can be called inside
--   <a>unsafePerformIO</a>, and which allows top-level TVars to be
--   allocated.
atomically :: STM a -> IO a

-- | Retry execution of the current memory transaction because it has seen
--   values in TVars which mean that it should not continue (e.g. the TVars
--   represent a shared buffer that is now empty). The implementation may
--   block the thread until one of the TVars that it has read from has been
--   udpated. (GHC only)
retry :: STM a

-- | Compose two alternative STM actions (GHC only). If the first action
--   completes without retrying then it forms the result of the orElse.
--   Otherwise, if the first action retries, then the second action is
--   tried in its place. If both actions retry then the orElse as a whole
--   retries.
orElse :: STM a -> STM a -> STM a

-- | A variant of <a>throw</a> that can only be used within the <a>STM</a>
--   monad.
--   
--   Throwing an exception in <tt>STM</tt> aborts the transaction and
--   propagates the exception.
--   
--   Although <a>throwSTM</a> has a type that is an instance of the type of
--   <a>throw</a>, the two functions are subtly different:
--   
--   <pre>
--   throw e    `seq` x  ===&gt; throw e
--   throwSTM e `seq` x  ===&gt; x
--   </pre>
--   
--   The first example will cause the exception <tt>e</tt> to be raised,
--   whereas the second one won't. In fact, <a>throwSTM</a> will only cause
--   an exception to be raised when it is used within the <a>STM</a> monad.
--   The <a>throwSTM</a> variant should be used in preference to
--   <a>throw</a> to raise an exception within the <a>STM</a> monad because
--   it guarantees ordering with respect to other <a>STM</a> operations,
--   whereas <a>throw</a> does not.
throwSTM :: Exception e => e -> STM a

-- | Exception handling within STM actions.
catchSTM :: Exception e => STM a -> (e -> STM a) -> STM a

-- | alwaysSucceeds adds a new invariant that must be true when passed to
--   alwaysSucceeds, at the end of the current transaction, and at the end
--   of every subsequent transaction. If it fails at any of those points
--   then the transaction violating it is aborted and the exception raised
--   by the invariant is propagated.
alwaysSucceeds :: STM a -> STM ()

-- | always is a variant of alwaysSucceeds in which the invariant is
--   expressed as an STM Bool action that must return True. Returning False
--   or raising an exception are both treated as invariant failures.
always :: STM Bool -> STM ()

-- | Shared memory locations that support atomic memory transactions.
data TVar a
TVar :: (TVar# RealWorld a) -> TVar a

-- | Create a new TVar holding a value supplied
newTVar :: a -> STM (TVar a)

-- | <tt>IO</tt> version of <a>newTVar</a>. This is useful for creating
--   top-level <a>TVar</a>s using <a>unsafePerformIO</a>, because using
--   <a>atomically</a> inside <a>unsafePerformIO</a> isn't possible.
newTVarIO :: a -> IO (TVar a)

-- | Return the current value stored in a TVar
readTVar :: TVar a -> STM a

-- | Return the current value stored in a TVar. This is equivalent to
--   
--   <pre>
--   readTVarIO = atomically . readTVar
--   </pre>
--   
--   but works much faster, because it doesn't perform a complete
--   transaction, it just reads the current value of the <a>TVar</a>.
readTVarIO :: TVar a -> IO a

-- | Write the supplied value into a TVar
writeTVar :: TVar a -> a -> STM ()

-- | Unsafely performs IO in the STM monad. Beware: this is a highly
--   dangerous thing to do.
--   
--   <ul>
--   <li>The STM implementation will often run transactions multiple times,
--   so you need to be prepared for this if your IO has any side
--   effects.</li>
--   <li>The STM implementation will abort transactions that are known to
--   be invalid and need to be restarted. This may happen in the middle of
--   <a>unsafeIOToSTM</a>, so make sure you don't acquire any resources
--   that need releasing (exception handlers are ignored when aborting the
--   transaction). That includes doing any IO using Handles, for example.
--   Getting this wrong will probably lead to random deadlocks.</li>
--   <li>The transaction may have seen an inconsistent view of memory when
--   the IO runs. Invariants that you expect to be true throughout your
--   program may not be true inside a transaction, due to the way
--   transactions are implemented. Normally this wouldn't be visible to the
--   programmer, but using <a>unsafeIOToSTM</a> can expose it.</li>
--   </ul>
unsafeIOToSTM :: IO a -> STM a
withMVar :: MVar a -> (a -> IO b) -> IO b
modifyMVar_ :: MVar a -> (a -> IO a) -> IO ()
setUncaughtExceptionHandler :: (SomeException -> IO ()) -> IO ()
getUncaughtExceptionHandler :: IO (SomeException -> IO ())
reportError :: SomeException -> IO ()
reportStackOverflow :: IO ()
sharedCAF :: a -> (Ptr a -> IO (Ptr a)) -> IO a
instance Typeable ThreadId
instance Typeable1 TVar
instance Typeable1 STM
instance Eq BlockReason
instance Ord BlockReason
instance Show BlockReason
instance Eq ThreadStatus
instance Ord ThreadStatus
instance Show ThreadStatus
instance Eq (TVar a)
instance MonadPlus STM
instance Monad STM
instance Functor STM
instance Ord ThreadId
instance Eq ThreadId
instance Show ThreadId


-- | Extensible exceptions, except for multiple handlers.
module Control.Exception.Base

-- | The <tt>SomeException</tt> type is the root of the exception type
--   hierarchy. When an exception of type <tt>e</tt> is thrown, behind the
--   scenes it is encapsulated in a <tt>SomeException</tt>.
data SomeException
SomeException :: e -> SomeException

-- | Any type that you wish to throw or catch as an exception must be an
--   instance of the <tt>Exception</tt> class. The simplest case is a new
--   exception type directly below the root:
--   
--   <pre>
--   data MyException = ThisException | ThatException
--       deriving (Show, Typeable)
--   
--   instance Exception MyException
--   </pre>
--   
--   The default method definitions in the <tt>Exception</tt> class do what
--   we need in this case. You can now throw and catch
--   <tt>ThisException</tt> and <tt>ThatException</tt> as exceptions:
--   
--   <pre>
--   *Main&gt; throw ThisException `catch` \e -&gt; putStrLn ("Caught " ++ show (e :: MyException))
--   Caught ThisException
--   </pre>
--   
--   In more complicated examples, you may wish to define a whole hierarchy
--   of exceptions:
--   
--   <pre>
--   ---------------------------------------------------------------------
--   -- Make the root exception type for all the exceptions in a compiler
--   
--   data SomeCompilerException = forall e . Exception e =&gt; SomeCompilerException e
--       deriving Typeable
--   
--   instance Show SomeCompilerException where
--       show (SomeCompilerException e) = show e
--   
--   instance Exception SomeCompilerException
--   
--   compilerExceptionToException :: Exception e =&gt; e -&gt; SomeException
--   compilerExceptionToException = toException . SomeCompilerException
--   
--   compilerExceptionFromException :: Exception e =&gt; SomeException -&gt; Maybe e
--   compilerExceptionFromException x = do
--       SomeCompilerException a &lt;- fromException x
--       cast a
--   
--   ---------------------------------------------------------------------
--   -- Make a subhierarchy for exceptions in the frontend of the compiler
--   
--   data SomeFrontendException = forall e . Exception e =&gt; SomeFrontendException e
--       deriving Typeable
--   
--   instance Show SomeFrontendException where
--       show (SomeFrontendException e) = show e
--   
--   instance Exception SomeFrontendException where
--       toException = compilerExceptionToException
--       fromException = compilerExceptionFromException
--   
--   frontendExceptionToException :: Exception e =&gt; e -&gt; SomeException
--   frontendExceptionToException = toException . SomeFrontendException
--   
--   frontendExceptionFromException :: Exception e =&gt; SomeException -&gt; Maybe e
--   frontendExceptionFromException x = do
--       SomeFrontendException a &lt;- fromException x
--       cast a
--   
--   ---------------------------------------------------------------------
--   -- Make an exception type for a particular frontend compiler exception
--   
--   data MismatchedParentheses = MismatchedParentheses
--       deriving (Typeable, Show)
--   
--   instance Exception MismatchedParentheses where
--       toException   = frontendExceptionToException
--       fromException = frontendExceptionFromException
--   </pre>
--   
--   We can now catch a <tt>MismatchedParentheses</tt> exception as
--   <tt>MismatchedParentheses</tt>, <tt>SomeFrontendException</tt> or
--   <tt>SomeCompilerException</tt>, but not other types, e.g.
--   <tt>IOException</tt>:
--   
--   <pre>
--   *Main&gt; throw MismatchedParentheses <tt>catch</tt> e -&gt; putStrLn ("Caught " ++ show (e :: MismatchedParentheses))
--   Caught MismatchedParentheses
--   *Main&gt; throw MismatchedParentheses <tt>catch</tt> e -&gt; putStrLn ("Caught " ++ show (e :: SomeFrontendException))
--   Caught MismatchedParentheses
--   *Main&gt; throw MismatchedParentheses <tt>catch</tt> e -&gt; putStrLn ("Caught " ++ show (e :: SomeCompilerException))
--   Caught MismatchedParentheses
--   *Main&gt; throw MismatchedParentheses <tt>catch</tt> e -&gt; putStrLn ("Caught " ++ show (e :: IOException))
--   *** Exception: MismatchedParentheses
--   </pre>
class (Typeable e, Show e) => Exception e where toException = SomeException fromException (SomeException e) = cast e
toException :: Exception e => e -> SomeException
fromException :: Exception e => SomeException -> Maybe e

-- | Exceptions that occur in the <tt>IO</tt> monad. An
--   <tt>IOException</tt> records a more specific error type, a descriptive
--   string and maybe the handle that was used when the error was flagged.
data IOException

-- | Arithmetic exceptions.
data ArithException
Overflow :: ArithException
Underflow :: ArithException
LossOfPrecision :: ArithException
DivideByZero :: ArithException
Denormal :: ArithException
RatioZeroDenominator :: ArithException

-- | Exceptions generated by array operations
data ArrayException

-- | An attempt was made to index an array outside its declared bounds.
IndexOutOfBounds :: String -> ArrayException

-- | An attempt was made to evaluate an element of an array that had not
--   been initialized.
UndefinedElement :: String -> ArrayException

-- | <a>assert</a> was applied to <a>False</a>.
data AssertionFailed
AssertionFailed :: String -> AssertionFailed

-- | Asynchronous exceptions.
data AsyncException

-- | The current thread's stack exceeded its limit. Since an exception has
--   been raised, the thread's stack will certainly be below its limit
--   again, but the programmer should take remedial action immediately.
StackOverflow :: AsyncException

-- | The program's heap is reaching its limit, and the program should take
--   action to reduce the amount of live data it has. Notes:
--   
--   <ul>
--   <li>It is undefined which thread receives this exception.</li>
--   <li>GHC currently does not throw <a>HeapOverflow</a> exceptions.</li>
--   </ul>
HeapOverflow :: AsyncException

-- | This exception is raised by another thread calling <a>killThread</a>,
--   or by the system if it needs to terminate the thread for some reason.
ThreadKilled :: AsyncException

-- | This exception is raised by default in the main thread of the program
--   when the user requests to terminate the program via the usual
--   mechanism(s) (e.g. Control-C in the console).
UserInterrupt :: AsyncException

-- | Thrown when the runtime system detects that the computation is
--   guaranteed not to terminate. Note that there is no guarantee that the
--   runtime system will notice whether any given computation is guaranteed
--   to terminate or not.
data NonTermination
NonTermination :: NonTermination

-- | Thrown when the program attempts to call <tt>atomically</tt>, from the
--   <tt>stm</tt> package, inside another call to <tt>atomically</tt>.
data NestedAtomically
NestedAtomically :: NestedAtomically

-- | The thread is blocked on an <tt>MVar</tt>, but there are no other
--   references to the <tt>MVar</tt> so it can't ever continue.
data BlockedIndefinitelyOnMVar
BlockedIndefinitelyOnMVar :: BlockedIndefinitelyOnMVar

-- | The thread is waiting to retry an STM transaction, but there are no
--   other references to any <tt>TVar</tt>s involved, so it can't ever
--   continue.
data BlockedIndefinitelyOnSTM
BlockedIndefinitelyOnSTM :: BlockedIndefinitelyOnSTM

-- | There are no runnable threads, so the program is deadlocked. The
--   <tt>Deadlock</tt> exception is raised in the main thread only.
data Deadlock
Deadlock :: Deadlock

-- | A class method without a definition (neither a default definition, nor
--   a definition in the appropriate instance) was called. The
--   <tt>String</tt> gives information about which method it was.
data NoMethodError
NoMethodError :: String -> NoMethodError

-- | A pattern match failed. The <tt>String</tt> gives information about
--   the source location of the pattern.
data PatternMatchFail
PatternMatchFail :: String -> PatternMatchFail

-- | An uninitialised record field was used. The <tt>String</tt> gives
--   information about the source location where the record was
--   constructed.
data RecConError
RecConError :: String -> RecConError

-- | A record selector was applied to a constructor without the appropriate
--   field. This can only happen with a datatype with multiple
--   constructors, where some fields are in one constructor but not
--   another. The <tt>String</tt> gives information about the source
--   location of the record selector.
data RecSelError
RecSelError :: String -> RecSelError

-- | A record update was performed on a constructor without the appropriate
--   field. This can only happen with a datatype with multiple
--   constructors, where some fields are in one constructor but not
--   another. The <tt>String</tt> gives information about the source
--   location of the record update.
data RecUpdError
RecUpdError :: String -> RecUpdError

-- | This is thrown when the user calls <a>error</a>. The <tt>String</tt>
--   is the argument given to <a>error</a>.
data ErrorCall
ErrorCall :: String -> ErrorCall

-- | A variant of <a>throw</a> that can only be used within the <a>IO</a>
--   monad.
--   
--   Although <a>throwIO</a> has a type that is an instance of the type of
--   <a>throw</a>, the two functions are subtly different:
--   
--   <pre>
--   throw e   `seq` x  ===&gt; throw e
--   throwIO e `seq` x  ===&gt; x
--   </pre>
--   
--   The first example will cause the exception <tt>e</tt> to be raised,
--   whereas the second one won't. In fact, <a>throwIO</a> will only cause
--   an exception to be raised when it is used within the <a>IO</a> monad.
--   The <a>throwIO</a> variant should be used in preference to
--   <a>throw</a> to raise an exception within the <a>IO</a> monad because
--   it guarantees ordering with respect to other <a>IO</a> operations,
--   whereas <a>throw</a> does not.
throwIO :: Exception e => e -> IO a

-- | Throw an exception. Exceptions may be thrown from purely functional
--   code, but may only be caught within the <a>IO</a> monad.
throw :: Exception e => e -> a

-- | Raise an <a>IOError</a> in the <a>IO</a> monad.
ioError :: IOError -> IO a

-- | <a>throwTo</a> raises an arbitrary exception in the target thread (GHC
--   only).
--   
--   <a>throwTo</a> does not return until the exception has been raised in
--   the target thread. The calling thread can thus be certain that the
--   target thread has received the exception. This is a useful property to
--   know when dealing with race conditions: eg. if there are two threads
--   that can kill each other, it is guaranteed that only one of the
--   threads will get to kill the other.
--   
--   Whatever work the target thread was doing when the exception was
--   raised is not lost: the computation is suspended until required by
--   another thread.
--   
--   If the target thread is currently making a foreign call, then the
--   exception will not be raised (and hence <a>throwTo</a> will not
--   return) until the call has completed. This is the case regardless of
--   whether the call is inside a <a>mask</a> or not. However, in GHC a
--   foreign call can be annotated as <tt>interruptible</tt>, in which case
--   a <a>throwTo</a> will cause the RTS to attempt to cause the call to
--   return; see the GHC documentation for more details.
--   
--   Important note: the behaviour of <a>throwTo</a> differs from that
--   described in the paper "Asynchronous exceptions in Haskell"
--   (<a>http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm</a>).
--   In the paper, <a>throwTo</a> is non-blocking; but the library
--   implementation adopts a more synchronous design in which
--   <a>throwTo</a> does not return until the exception is received by the
--   target thread. The trade-off is discussed in Section 9 of the paper.
--   Like any blocking operation, <a>throwTo</a> is therefore interruptible
--   (see Section 5.3 of the paper). Unlike other interruptible operations,
--   however, <a>throwTo</a> is <i>always</i> interruptible, even if it
--   does not actually block.
--   
--   There is no guarantee that the exception will be delivered promptly,
--   although the runtime will endeavour to ensure that arbitrary delays
--   don't occur. In GHC, an exception can only be raised when a thread
--   reaches a <i>safe point</i>, where a safe point is where memory
--   allocation occurs. Some loops do not perform any memory allocation
--   inside the loop and therefore cannot be interrupted by a
--   <a>throwTo</a>.
--   
--   If the target of <a>throwTo</a> is the calling thread, then the
--   behaviour is the same as <a>throwIO</a>, except that the exception is
--   thrown as an asynchronous exception. This means that if there is an
--   enclosing pure computation, which would be the case if the current IO
--   operation is inside <a>unsafePerformIO</a> or
--   <a>unsafeInterleaveIO</a>, that computation is not permanently
--   replaced by the exception, but is suspended as if it had received an
--   asynchronous exception.
--   
--   Note that if <a>throwTo</a> is called with the current thread as the
--   target, the exception will be thrown even if the thread is currently
--   inside <a>mask</a> or <a>uninterruptibleMask</a>.
throwTo :: Exception e => ThreadId -> e -> IO ()

-- | 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:
--   
--   <pre>
--   catch (readFile f)
--         (\e -&gt; do let err = show (e :: IOException)
--                   hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err)
--                   return "")
--   </pre>
--   
--   Note that we have to give a type signature to <tt>e</tt>, 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 <a>Control.Exception</a>) for an explanation of
--   the problems with doing so.
--   
--   For catching exceptions in pure (non-<a>IO</a>) expressions, see the
--   function <a>evaluate</a>.
--   
--   Note that due to Haskell's unspecified evaluation order, an expression
--   may throw one of several possible exceptions: consider the expression
--   <tt>(error "urk") + (1 `div` 0)</tt>. Does the expression throw
--   <tt>ErrorCall "urk"</tt>, or <tt>DivideByZero</tt>?
--   
--   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 <tt>catch</tt> with type <tt>IO
--   Int -&gt; (ArithException -&gt; IO Int) -&gt; IO Int</tt> then the
--   handler may get run with <tt>DivideByZero</tt> as an argument, or an
--   <tt>ErrorCall "urk"</tt> exception may be propogated further up. If
--   you call it again, you might get a the opposite behaviour. This is ok,
--   because <a>catch</a> is an <a>IO</a> computation.
catch :: Exception e => IO a -> (e -> IO a) -> IO a

-- | The function <a>catchJust</a> is like <a>catch</a>, but it takes an
--   extra argument which is an <i>exception predicate</i>, a function
--   which selects which type of exceptions we're interested in.
--   
--   <pre>
--   catchJust (\e -&gt; if isDoesNotExistErrorType (ioeGetErrorType e) then Just () else Nothing)
--             (readFile f)
--             (\_ -&gt; do hPutStrLn stderr ("No such file: " ++ show f)
--                       return "")
--   </pre>
--   
--   Any other exceptions which are not matched by the predicate are
--   re-raised, and may be caught by an enclosing <a>catch</a>,
--   <a>catchJust</a>, etc.
catchJust :: Exception e => (e -> Maybe b) -> IO a -> (b -> IO a) -> IO a

-- | A version of <a>catch</a> with the arguments swapped around; useful in
--   situations where the code for the handler is shorter. For example:
--   
--   <pre>
--   do handle (\NonTermination -&gt; exitWith (ExitFailure 1)) $
--      ...
--   </pre>
handle :: Exception e => (e -> IO a) -> IO a -> IO a

-- | A version of <a>catchJust</a> with the arguments swapped around (see
--   <a>handle</a>).
handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a

-- | Similar to <a>catch</a>, but returns an <a>Either</a> result which is
--   <tt>(<a>Right</a> a)</tt> if no exception of type <tt>e</tt> was
--   raised, or <tt>(<a>Left</a> ex)</tt> if an exception of type
--   <tt>e</tt> was raised and its value is <tt>ex</tt>. If any other type
--   of exception is raised than it will be propogated up to the next
--   enclosing exception handler.
--   
--   <pre>
--   try a = catch (Right `liftM` a) (return . Left)
--   </pre>
--   
--   Note that <a>System.IO.Error</a> also exports a function called
--   <a>try</a> with a similar type to <a>try</a>, except that it catches
--   only the IO and user families of exceptions (as required by the
--   Haskell 98 <tt>IO</tt> module).
try :: Exception e => IO a -> IO (Either e a)

-- | A variant of <a>try</a> that takes an exception predicate to select
--   which exceptions are caught (c.f. <a>catchJust</a>). If the exception
--   does not match the predicate, it is re-thrown.
tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)

-- | Like <a>finally</a>, but only performs the final action if there was
--   an exception raised by the computation.
onException :: IO a -> IO b -> IO a

-- | Forces its argument to be evaluated to weak head normal form when the
--   resultant <a>IO</a> action is executed. It can be used to order
--   evaluation with respect to other <a>IO</a> operations; its semantics
--   are given by
--   
--   <pre>
--   evaluate x `seq` y    ==&gt;  y
--   evaluate x `catch` f  ==&gt;  (return $! x) `catch` f
--   evaluate x &gt;&gt;= f      ==&gt;  (return $! x) &gt;&gt;= f
--   </pre>
--   
--   <i>Note:</i> the first equation implies that <tt>(evaluate x)</tt> is
--   <i>not</i> the same as <tt>(return $! x)</tt>. A correct definition is
--   
--   <pre>
--   evaluate x = (return $! x) &gt;&gt;= return
--   </pre>
evaluate :: a -> IO a

-- | This function maps one exception into another as proposed in the paper
--   "A semantics for imprecise exceptions".
mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a

-- | Executes an IO computation with asynchronous exceptions <i>masked</i>.
--   That is, any thread which attempts to raise an exception in the
--   current thread with <a>throwTo</a> will be blocked until asynchronous
--   exceptions are unmasked again.
--   
--   The argument passed to <a>mask</a> 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 <a>mask</a> is to protect the acquisition
--   of a resource:
--   
--   <pre>
--   mask $ \restore -&gt; do
--       x &lt;- acquire
--       restore (do_something_with x) `onException` release
--       release
--   </pre>
--   
--   This code guarantees that <tt>acquire</tt> is paired with
--   <tt>release</tt>, by masking asynchronous exceptions for the critical
--   parts. (Rather than write this code yourself, it would be better to
--   use <a>bracket</a> which abstracts the general pattern).
--   
--   Note that the <tt>restore</tt> action passed to the argument to
--   <a>mask</a> 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, <a>mask</a> 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 <a>forkIOWithUnmask</a>.
--   
--   Asynchronous exceptions may still be received while in the masked
--   state if the masked thread <i>blocks</i> in certain ways; see
--   <a>Control.Exception#interruptible</a>.
--   
--   Threads created by <a>forkIO</a> inherit the masked state from the
--   parent; that is, to start a thread in blocked mode, use <tt>mask_ $
--   forkIO ...</tt>. 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 a new thread in an unmasked state
--   use <a>forkIOUnmasked</a>.
mask :: ((forall a. IO a -> IO a) -> IO b) -> IO b

-- | Like <a>mask</a>, but does not pass a <tt>restore</tt> action to the
--   argument.
mask_ :: IO a -> IO a

-- | Like <a>mask</a>, but the masked computation is not interruptible (see
--   <a>Control.Exception#interruptible</a>). THIS SHOULD BE USED WITH
--   GREAT CARE, because if a thread executing in
--   <a>uninterruptibleMask</a> blocks for any reason, then the thread (and
--   possibly the program, if this is the main thread) will be unresponsive
--   and unkillable. This function should only be necessary if you need to
--   mask exceptions around an interruptible operation, and you can
--   guarantee that the interruptible operation will only block for a short
--   period of time.
uninterruptibleMask :: ((forall a. IO a -> IO a) -> IO b) -> IO b

-- | Like <a>uninterruptibleMask</a>, but does not pass a <tt>restore</tt>
--   action to the argument.
uninterruptibleMask_ :: IO a -> IO a

-- | Describes the behaviour of a thread when an asynchronous exception is
--   received.
data MaskingState

-- | asynchronous exceptions are unmasked (the normal state)
Unmasked :: MaskingState

-- | the state during <a>mask</a>: asynchronous exceptions are masked, but
--   blocking operations may still be interrupted
MaskedInterruptible :: MaskingState

-- | the state during <a>uninterruptibleMask</a>: asynchronous exceptions
--   are masked, and blocking operations may not be interrupted
MaskedUninterruptible :: MaskingState

-- | Returns the <a>MaskingState</a> for the current thread.
getMaskingState :: IO MaskingState

-- | Note: this function is deprecated, please use <a>mask</a> instead.
--   
--   Applying <a>block</a> to a computation will execute that computation
--   with asynchronous exceptions <i>blocked</i>. That is, any thread which
--   attempts to raise an exception in the current thread with
--   <a>throwTo</a> will be blocked until asynchronous exceptions are
--   unblocked again. There's no need to worry about re-enabling
--   asynchronous exceptions; that is done automatically on exiting the
--   scope of <a>block</a>.
--   
--   Threads created by <a>forkIO</a> inherit the blocked state from the
--   parent; that is, to start a thread in blocked mode, use <tt>block $
--   forkIO ...</tt>. This is particularly useful if you need to establish
--   an exception handler in the forked thread before any asynchronous
--   exceptions are received.

-- | <i>Deprecated: use Control.Exception.mask instead </i>
block :: IO a -> IO a

-- | Note: this function is deprecated, please use <a>mask</a> instead.
--   
--   To re-enable asynchronous exceptions inside the scope of <a>block</a>,
--   <a>unblock</a> can be used. It scopes in exactly the same way, so on
--   exit from <a>unblock</a> asynchronous exception delivery will be
--   disabled again.

-- | <i>Deprecated: use Control.Exception.mask instead </i>
unblock :: IO a -> IO a

-- | returns True if asynchronous exceptions are blocked in the current
--   thread.

-- | <i>Deprecated: use Control.Exception.getMaskingState instead </i>
blocked :: IO Bool

-- | If the first argument evaluates to <a>True</a>, then the result is the
--   second argument. Otherwise an <tt>AssertionFailed</tt> exception is
--   raised, containing a <a>String</a> with the source file and line
--   number of the call to <a>assert</a>.
--   
--   Assertions can normally be turned on or off with a compiler flag (for
--   GHC, assertions are normally on unless optimisation is turned on with
--   <tt>-O</tt> or the <tt>-fignore-asserts</tt> option is given). When
--   assertions are turned off, the first argument to <a>assert</a> is
--   ignored, and the second argument is returned as the result.
assert :: Bool -> a -> a

-- | When you want to acquire a resource, do some work with it, and then
--   release the resource, it is a good idea to use <a>bracket</a>, because
--   <a>bracket</a> 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 <a>bracket</a> will
--   re-raise the exception (after performing the release).
--   
--   A common example is opening a file:
--   
--   <pre>
--   bracket
--     (openFile "filename" ReadMode)
--     (hClose)
--     (\fileHandle -&gt; do { ... })
--   </pre>
--   
--   The arguments to <a>bracket</a> are in this order so that we can
--   partially apply it, e.g.:
--   
--   <pre>
--   withFile name mode = bracket (openFile name mode) hClose
--   </pre>
bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c

-- | A variant of <a>bracket</a> where the return value from the first
--   computation is not required.
bracket_ :: IO a -> IO b -> IO c -> IO c

-- | Like <a>bracket</a>, but only performs the final action if there was
--   an exception raised by the in-between computation.
bracketOnError :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c

-- | A specialised variant of <a>bracket</a> with just a computation to run
--   afterward.
finally :: IO a -> IO b -> IO a
recSelError :: Addr# -> a
recConError :: Addr# -> a
irrefutPatError :: Addr# -> a
runtimeError :: Addr# -> a
nonExhaustiveGuardsError :: Addr# -> a
patError :: Addr# -> a
noMethodBindingError :: Addr# -> a
absentError :: Addr# -> a
nonTermination :: SomeException
nestedAtomically :: SomeException
instance Typeable NestedAtomically
instance Typeable NonTermination
instance Typeable NoMethodError
instance Typeable RecUpdError
instance Typeable RecConError
instance Typeable RecSelError
instance Typeable PatternMatchFail
instance Exception NestedAtomically
instance Show NestedAtomically
instance Exception NonTermination
instance Show NonTermination
instance Exception NoMethodError
instance Show NoMethodError
instance Exception RecUpdError
instance Show RecUpdError
instance Exception RecConError
instance Show RecConError
instance Exception RecSelError
instance Show RecSelError
instance Exception PatternMatchFail
instance Show PatternMatchFail


-- | An <tt><a>MVar</a> t</tt> is mutable location that is either empty or
--   contains a value of type <tt>t</tt>. It has two fundamental
--   operations: <a>putMVar</a> which fills an <a>MVar</a> if it is empty
--   and blocks otherwise, and <a>takeMVar</a> which empties an <a>MVar</a>
--   if it is full and blocks otherwise. They can be used in multiple
--   different ways:
--   
--   <ol>
--   <li>As synchronized mutable variables, 2. As channels, with
--   <a>takeMVar</a> and <a>putMVar</a> as receive and send, and 3. As a
--   binary semaphore <tt><a>MVar</a> ()</tt>, with <a>takeMVar</a> and
--   <a>putMVar</a> as wait and signal.</li>
--   </ol>
--   
--   They were introduced in the paper <a>Concurrent Haskell</a> by Simon
--   Peyton Jones, Andrew Gordon and Sigbjorn Finne, though some details of
--   their implementation have since then changed (in particular, a put on
--   a full MVar used to error, but now merely blocks.)
--   
--   <ul>
--   <li>Applicability</li>
--   </ul>
--   
--   <a>MVar</a>s offer more flexibility than <tt>IORef</tt>s, but less
--   flexibility than <tt>STM</tt>. They are appropriate for building
--   synchronization primitives and performing simple interthread
--   communication; however they are very simple and susceptible to race
--   conditions, deadlocks or uncaught exceptions. Do not use them if you
--   need perform larger atomic operations such as reading from multiple
--   variables: use <tt>STM</tt> instead.
--   
--   In particular, the <a>bigger</a> functions in this module
--   (<a>readMVar</a>, <a>swapMVar</a>, <a>withMVar</a>, <a>modifyMVar_</a>
--   and <a>modifyMVar</a>) are simply the composition of a <a>takeMVar</a>
--   followed by a <a>putMVar</a> with exception safety. These only have
--   atomicity guarantees if all other threads perform a <a>takeMVar</a>
--   before a <a>putMVar</a> as well; otherwise, they may block.
--   
--   <ul>
--   <li>Fairness</li>
--   </ul>
--   
--   No thread can be blocked indefinitely on an <a>MVar</a> unless another
--   thread holds that <a>MVar</a> indefinitely. One usual implementation
--   of this fairness guarantee is that threads blocked on an <a>MVar</a>
--   are served in a first-in-first-out fashion, but this is not guaranteed
--   in the semantics.
--   
--   <ul>
--   <li>Gotchas</li>
--   </ul>
--   
--   Like many other Haskell data structures, <a>MVar</a>s are lazy. This
--   means that if you place an expensive unevaluated thunk inside an
--   <a>MVar</a>, it will be evaluated by the thread that consumes it, not
--   the thread that produced it. Be sure to <a>evaluate</a> values to be
--   placed in an <a>MVar</a> to the appropriate normal form, or utilize a
--   strict MVar provided by the strict-concurrency package.
--   
--   <ul>
--   <li>Ordering</li>
--   </ul>
--   
--   <a>MVar</a> operations are always observed to take place in the order
--   they are written in the program, regardless of the memory model of the
--   underlying machine. This is in contrast to <tt>IORef</tt> operations
--   which may appear out-of-order to another thread in some cases.
--   
--   <ul>
--   <li>Example</li>
--   </ul>
--   
--   Consider the following concurrent data structure, a skip channel. This
--   is a channel for an intermittent source of high bandwidth information
--   (for example, mouse movement events.) Writing to the channel never
--   blocks, and reading from the channel only returns the most recent
--   value, or blocks if there are no new values. Multiple readers are
--   supported with a <tt>dupSkipChan</tt> operation.
--   
--   A skip channel is a pair of <a>MVar</a>s. The first <a>MVar</a>
--   contains the current value, and a list of semaphores that need to be
--   notified when it changes. The second <a>MVar</a> is a semaphore for
--   this particular reader: it is full if there is a value in the channel
--   that this reader has not read yet, and empty otherwise.
--   
--   <pre>
--        data SkipChan a = SkipChan (MVar (a, [MVar ()])) (MVar ())
--   
--   newSkipChan :: IO (SkipChan a)
--        newSkipChan = do
--            sem &lt;- newEmptyMVar
--            main &lt;- newMVar (undefined, [sem])
--            return (SkipChan main sem)
--   
--   putSkipChan :: SkipChan a -&gt; a -&gt; IO ()
--        putSkipChan (SkipChan main _) v = do
--            (_, sems) &lt;- takeMVar main
--            putMVar main (v, [])
--            mapM_ (sem -&gt; putMVar sem ()) sems
--   
--   getSkipChan :: SkipChan a -&gt; IO a
--        getSkipChan (SkipChan main sem) = do
--            takeMVar sem
--            (v, sems) &lt;- takeMVar main
--            putMVar main (v, sem:sems)
--            return v
--   
--   dupSkipChan :: SkipChan a -&gt; IO (SkipChan a)
--        dupSkipChan (SkipChan main _) = do
--            sem &lt;- newEmptyMVar
--            (v, sems) &lt;- takeMVar main
--            putMVar main (v, sem:sems)
--            return (SkipChan main sem)
--   </pre>
--   
--   This example was adapted from the original Concurrent Haskell paper.
--   For more examples of <a>MVar</a>s being used to build higher-level
--   synchronization primitives, see <a>Chan</a> and <a>QSem</a>.
module Control.Concurrent.MVar

-- | An <a>MVar</a> (pronounced "em-var") is a synchronising variable, used
--   for communication between concurrent threads. It can be thought of as
--   a a box, which may be empty or full.
data MVar a

-- | Create an <a>MVar</a> which is initially empty.
newEmptyMVar :: IO (MVar a)

-- | Create an <a>MVar</a> which contains the supplied value.
newMVar :: a -> IO (MVar a)

-- | Return the contents of the <a>MVar</a>. If the <a>MVar</a> is
--   currently empty, <a>takeMVar</a> will wait until it is full. After a
--   <a>takeMVar</a>, the <a>MVar</a> is left empty.
--   
--   There are two further important properties of <a>takeMVar</a>:
--   
--   <ul>
--   <li><a>takeMVar</a> is single-wakeup. That is, if there are multiple
--   threads blocked in <a>takeMVar</a>, and the <a>MVar</a> becomes full,
--   only one thread will be woken up. The runtime guarantees that the
--   woken thread completes its <a>takeMVar</a> operation.</li>
--   <li>When multiple threads are blocked on an <a>MVar</a>, they are
--   woken up in FIFO order. This is useful for providing fairness
--   properties of abstractions built using <a>MVar</a>s.</li>
--   </ul>
takeMVar :: MVar a -> IO a

-- | Put a value into an <a>MVar</a>. If the <a>MVar</a> is currently full,
--   <a>putMVar</a> will wait until it becomes empty.
--   
--   There are two further important properties of <a>putMVar</a>:
--   
--   <ul>
--   <li><a>putMVar</a> is single-wakeup. That is, if there are multiple
--   threads blocked in <a>putMVar</a>, and the <a>MVar</a> becomes empty,
--   only one thread will be woken up. The runtime guarantees that the
--   woken thread completes its <a>putMVar</a> operation.</li>
--   <li>When multiple threads are blocked on an <a>MVar</a>, they are
--   woken up in FIFO order. This is useful for providing fairness
--   properties of abstractions built using <a>MVar</a>s.</li>
--   </ul>
putMVar :: MVar a -> a -> IO ()

-- | This is a combination of <a>takeMVar</a> and <a>putMVar</a>; ie. it
--   takes the value from the <a>MVar</a>, puts it back, and also returns
--   it. This function is atomic only if there are no other producers (i.e.
--   threads calling <a>putMVar</a>) for this <a>MVar</a>.
readMVar :: MVar a -> IO a

-- | Take a value from an <a>MVar</a>, put a new value into the <a>MVar</a>
--   and return the value taken. This function is atomic only if there are
--   no other producers for this <a>MVar</a>.
swapMVar :: MVar a -> a -> IO a

-- | A non-blocking version of <a>takeMVar</a>. The <a>tryTakeMVar</a>
--   function returns immediately, with <a>Nothing</a> if the <a>MVar</a>
--   was empty, or <tt><a>Just</a> a</tt> if the <a>MVar</a> was full with
--   contents <tt>a</tt>. After <a>tryTakeMVar</a>, the <a>MVar</a> is left
--   empty.
tryTakeMVar :: MVar a -> IO (Maybe a)

-- | A non-blocking version of <a>putMVar</a>. The <a>tryPutMVar</a>
--   function attempts to put the value <tt>a</tt> into the <a>MVar</a>,
--   returning <a>True</a> if it was successful, or <a>False</a> otherwise.
tryPutMVar :: MVar a -> a -> IO Bool

-- | Check whether a given <a>MVar</a> is empty.
--   
--   Notice that the boolean value returned is just a snapshot of the state
--   of the MVar. By the time you get to react on its result, the MVar may
--   have been filled (or emptied) - so be extremely careful when using
--   this operation. Use <a>tryTakeMVar</a> instead if possible.
isEmptyMVar :: MVar a -> IO Bool

-- | <a>withMVar</a> is an exception-safe wrapper for operating on the
--   contents of an <a>MVar</a>. This operation is exception-safe: it will
--   replace the original contents of the <a>MVar</a> if an exception is
--   raised (see <a>Control.Exception</a>). However, it is only atomic if
--   there are no other producers for this <a>MVar</a>.
withMVar :: MVar a -> (a -> IO b) -> IO b

-- | An exception-safe wrapper for modifying the contents of an
--   <a>MVar</a>. Like <a>withMVar</a>, <a>modifyMVar</a> will replace the
--   original contents of the <a>MVar</a> if an exception is raised during
--   the operation. This function is only atomic if there are no other
--   producers for this <a>MVar</a>.
modifyMVar_ :: MVar a -> (a -> IO a) -> IO ()

-- | A slight variation on <a>modifyMVar_</a> that allows a value to be
--   returned (<tt>b</tt>) in addition to the modified value of the
--   <a>MVar</a>.
modifyMVar :: MVar a -> (a -> IO (a, b)) -> IO b

-- | Like <a>modifyMVar_</a>, but the <tt>IO</tt> action in the second
--   argument is executed with asynchronous exceptions masked.
modifyMVarMasked_ :: MVar a -> (a -> IO a) -> IO ()

-- | Like <a>modifyMVar</a>, but the <tt>IO</tt> action in the second
--   argument is executed with asynchronous exceptions masked.
modifyMVarMasked :: MVar a -> (a -> IO (a, b)) -> IO b

-- | Make a <a>Weak</a> pointer to an <a>MVar</a>, using the second
--   argument as a finalizer to run when <a>MVar</a> is garbage-collected
mkWeakMVar :: MVar a -> IO () -> IO (Weak (MVar a))

-- | <i>Deprecated: use mkWeakMVar instead </i>
addMVarFinalizer :: MVar a -> IO () -> IO ()


-- | This module provides support for raising and catching both built-in
--   and user-defined exceptions.
--   
--   In addition to exceptions thrown by <a>IO</a> operations, exceptions
--   may be thrown by pure code (imprecise exceptions) or by external
--   events (asynchronous exceptions), but may only be caught in the
--   <a>IO</a> monad. For more details, see:
--   
--   <ul>
--   <li><i>A semantics for imprecise exceptions</i>, by Simon Peyton
--   Jones, Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson, in
--   <i>PLDI'99</i>.</li>
--   <li><i>Asynchronous exceptions in Haskell</i>, by Simon Marlow, Simon
--   Peyton Jones, Andy Moran and John Reppy, in <i>PLDI'01</i>.</li>
--   <li><i>An Extensible Dynamically-Typed Hierarchy of Exceptions</i>, by
--   Simon Marlow, in <i>Haskell '06</i>.</li>
--   </ul>
module Control.Exception

-- | The <tt>SomeException</tt> type is the root of the exception type
--   hierarchy. When an exception of type <tt>e</tt> is thrown, behind the
--   scenes it is encapsulated in a <tt>SomeException</tt>.
data SomeException
SomeException :: e -> SomeException

-- | Any type that you wish to throw or catch as an exception must be an
--   instance of the <tt>Exception</tt> class. The simplest case is a new
--   exception type directly below the root:
--   
--   <pre>
--   data MyException = ThisException | ThatException
--       deriving (Show, Typeable)
--   
--   instance Exception MyException
--   </pre>
--   
--   The default method definitions in the <tt>Exception</tt> class do what
--   we need in this case. You can now throw and catch
--   <tt>ThisException</tt> and <tt>ThatException</tt> as exceptions:
--   
--   <pre>
--   *Main&gt; throw ThisException `catch` \e -&gt; putStrLn ("Caught " ++ show (e :: MyException))
--   Caught ThisException
--   </pre>
--   
--   In more complicated examples, you may wish to define a whole hierarchy
--   of exceptions:
--   
--   <pre>
--   ---------------------------------------------------------------------
--   -- Make the root exception type for all the exceptions in a compiler
--   
--   data SomeCompilerException = forall e . Exception e =&gt; SomeCompilerException e
--       deriving Typeable
--   
--   instance Show SomeCompilerException where
--       show (SomeCompilerException e) = show e
--   
--   instance Exception SomeCompilerException
--   
--   compilerExceptionToException :: Exception e =&gt; e -&gt; SomeException
--   compilerExceptionToException = toException . SomeCompilerException
--   
--   compilerExceptionFromException :: Exception e =&gt; SomeException -&gt; Maybe e
--   compilerExceptionFromException x = do
--       SomeCompilerException a &lt;- fromException x
--       cast a
--   
--   ---------------------------------------------------------------------
--   -- Make a subhierarchy for exceptions in the frontend of the compiler
--   
--   data SomeFrontendException = forall e . Exception e =&gt; SomeFrontendException e
--       deriving Typeable
--   
--   instance Show SomeFrontendException where
--       show (SomeFrontendException e) = show e
--   
--   instance Exception SomeFrontendException where
--       toException = compilerExceptionToException
--       fromException = compilerExceptionFromException
--   
--   frontendExceptionToException :: Exception e =&gt; e -&gt; SomeException
--   frontendExceptionToException = toException . SomeFrontendException
--   
--   frontendExceptionFromException :: Exception e =&gt; SomeException -&gt; Maybe e
--   frontendExceptionFromException x = do
--       SomeFrontendException a &lt;- fromException x
--       cast a
--   
--   ---------------------------------------------------------------------
--   -- Make an exception type for a particular frontend compiler exception
--   
--   data MismatchedParentheses = MismatchedParentheses
--       deriving (Typeable, Show)
--   
--   instance Exception MismatchedParentheses where
--       toException   = frontendExceptionToException
--       fromException = frontendExceptionFromException
--   </pre>
--   
--   We can now catch a <tt>MismatchedParentheses</tt> exception as
--   <tt>MismatchedParentheses</tt>, <tt>SomeFrontendException</tt> or
--   <tt>SomeCompilerException</tt>, but not other types, e.g.
--   <tt>IOException</tt>:
--   
--   <pre>
--   *Main&gt; throw MismatchedParentheses <tt>catch</tt> e -&gt; putStrLn ("Caught " ++ show (e :: MismatchedParentheses))
--   Caught MismatchedParentheses
--   *Main&gt; throw MismatchedParentheses <tt>catch</tt> e -&gt; putStrLn ("Caught " ++ show (e :: SomeFrontendException))
--   Caught MismatchedParentheses
--   *Main&gt; throw MismatchedParentheses <tt>catch</tt> e -&gt; putStrLn ("Caught " ++ show (e :: SomeCompilerException))
--   Caught MismatchedParentheses
--   *Main&gt; throw MismatchedParentheses <tt>catch</tt> e -&gt; putStrLn ("Caught " ++ show (e :: IOException))
--   *** Exception: MismatchedParentheses
--   </pre>
class (Typeable e, Show e) => Exception e where toException = SomeException fromException (SomeException e) = cast e
toException :: Exception e => e -> SomeException
fromException :: Exception e => SomeException -> Maybe e

-- | Exceptions that occur in the <tt>IO</tt> monad. An
--   <tt>IOException</tt> records a more specific error type, a descriptive
--   string and maybe the handle that was used when the error was flagged.
data IOException

-- | Arithmetic exceptions.
data ArithException
Overflow :: ArithException
Underflow :: ArithException
LossOfPrecision :: ArithException
DivideByZero :: ArithException
Denormal :: ArithException
RatioZeroDenominator :: ArithException

-- | Exceptions generated by array operations
data ArrayException

-- | An attempt was made to index an array outside its declared bounds.
IndexOutOfBounds :: String -> ArrayException

-- | An attempt was made to evaluate an element of an array that had not
--   been initialized.
UndefinedElement :: String -> ArrayException

-- | <a>assert</a> was applied to <a>False</a>.
data AssertionFailed
AssertionFailed :: String -> AssertionFailed

-- | Asynchronous exceptions.
data AsyncException

-- | The current thread's stack exceeded its limit. Since an exception has
--   been raised, the thread's stack will certainly be below its limit
--   again, but the programmer should take remedial action immediately.
StackOverflow :: AsyncException

-- | The program's heap is reaching its limit, and the program should take
--   action to reduce the amount of live data it has. Notes:
--   
--   <ul>
--   <li>It is undefined which thread receives this exception.</li>
--   <li>GHC currently does not throw <a>HeapOverflow</a> exceptions.</li>
--   </ul>
HeapOverflow :: AsyncException

-- | This exception is raised by another thread calling <a>killThread</a>,
--   or by the system if it needs to terminate the thread for some reason.
ThreadKilled :: AsyncException

-- | This exception is raised by default in the main thread of the program
--   when the user requests to terminate the program via the usual
--   mechanism(s) (e.g. Control-C in the console).
UserInterrupt :: AsyncException

-- | Thrown when the runtime system detects that the computation is
--   guaranteed not to terminate. Note that there is no guarantee that the
--   runtime system will notice whether any given computation is guaranteed
--   to terminate or not.
data NonTermination
NonTermination :: NonTermination

-- | Thrown when the program attempts to call <tt>atomically</tt>, from the
--   <tt>stm</tt> package, inside another call to <tt>atomically</tt>.
data NestedAtomically
NestedAtomically :: NestedAtomically

-- | The thread is blocked on an <tt>MVar</tt>, but there are no other
--   references to the <tt>MVar</tt> so it can't ever continue.
data BlockedIndefinitelyOnMVar
BlockedIndefinitelyOnMVar :: BlockedIndefinitelyOnMVar

-- | The thread is waiting to retry an STM transaction, but there are no
--   other references to any <tt>TVar</tt>s involved, so it can't ever
--   continue.
data BlockedIndefinitelyOnSTM
BlockedIndefinitelyOnSTM :: BlockedIndefinitelyOnSTM

-- | There are no runnable threads, so the program is deadlocked. The
--   <tt>Deadlock</tt> exception is raised in the main thread only.
data Deadlock
Deadlock :: Deadlock

-- | A class method without a definition (neither a default definition, nor
--   a definition in the appropriate instance) was called. The
--   <tt>String</tt> gives information about which method it was.
data NoMethodError
NoMethodError :: String -> NoMethodError

-- | A pattern match failed. The <tt>String</tt> gives information about
--   the source location of the pattern.
data PatternMatchFail
PatternMatchFail :: String -> PatternMatchFail

-- | An uninitialised record field was used. The <tt>String</tt> gives
--   information about the source location where the record was
--   constructed.
data RecConError
RecConError :: String -> RecConError

-- | A record selector was applied to a constructor without the appropriate
--   field. This can only happen with a datatype with multiple
--   constructors, where some fields are in one constructor but not
--   another. The <tt>String</tt> gives information about the source
--   location of the record selector.
data RecSelError
RecSelError :: String -> RecSelError

-- | A record update was performed on a constructor without the appropriate
--   field. This can only happen with a datatype with multiple
--   constructors, where some fields are in one constructor but not
--   another. The <tt>String</tt> gives information about the source
--   location of the record update.
data RecUpdError
RecUpdError :: String -> RecUpdError

-- | This is thrown when the user calls <a>error</a>. The <tt>String</tt>
--   is the argument given to <a>error</a>.
data ErrorCall
ErrorCall :: String -> ErrorCall

-- | Throw an exception. Exceptions may be thrown from purely functional
--   code, but may only be caught within the <a>IO</a> monad.
throw :: Exception e => e -> a

-- | A variant of <a>throw</a> that can only be used within the <a>IO</a>
--   monad.
--   
--   Although <a>throwIO</a> has a type that is an instance of the type of
--   <a>throw</a>, the two functions are subtly different:
--   
--   <pre>
--   throw e   `seq` x  ===&gt; throw e
--   throwIO e `seq` x  ===&gt; x
--   </pre>
--   
--   The first example will cause the exception <tt>e</tt> to be raised,
--   whereas the second one won't. In fact, <a>throwIO</a> will only cause
--   an exception to be raised when it is used within the <a>IO</a> monad.
--   The <a>throwIO</a> variant should be used in preference to
--   <a>throw</a> to raise an exception within the <a>IO</a> monad because
--   it guarantees ordering with respect to other <a>IO</a> operations,
--   whereas <a>throw</a> does not.
throwIO :: Exception e => e -> IO a

-- | Raise an <a>IOError</a> in the <a>IO</a> monad.
ioError :: IOError -> IO a

-- | <a>throwTo</a> raises an arbitrary exception in the target thread (GHC
--   only).
--   
--   <a>throwTo</a> does not return until the exception has been raised in
--   the target thread. The calling thread can thus be certain that the
--   target thread has received the exception. This is a useful property to
--   know when dealing with race conditions: eg. if there are two threads
--   that can kill each other, it is guaranteed that only one of the
--   threads will get to kill the other.
--   
--   Whatever work the target thread was doing when the exception was
--   raised is not lost: the computation is suspended until required by
--   another thread.
--   
--   If the target thread is currently making a foreign call, then the
--   exception will not be raised (and hence <a>throwTo</a> will not
--   return) until the call has completed. This is the case regardless of
--   whether the call is inside a <a>mask</a> or not. However, in GHC a
--   foreign call can be annotated as <tt>interruptible</tt>, in which case
--   a <a>throwTo</a> will cause the RTS to attempt to cause the call to
--   return; see the GHC documentation for more details.
--   
--   Important note: the behaviour of <a>throwTo</a> differs from that
--   described in the paper "Asynchronous exceptions in Haskell"
--   (<a>http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm</a>).
--   In the paper, <a>throwTo</a> is non-blocking; but the library
--   implementation adopts a more synchronous design in which
--   <a>throwTo</a> does not return until the exception is received by the
--   target thread. The trade-off is discussed in Section 9 of the paper.
--   Like any blocking operation, <a>throwTo</a> is therefore interruptible
--   (see Section 5.3 of the paper). Unlike other interruptible operations,
--   however, <a>throwTo</a> is <i>always</i> interruptible, even if it
--   does not actually block.
--   
--   There is no guarantee that the exception will be delivered promptly,
--   although the runtime will endeavour to ensure that arbitrary delays
--   don't occur. In GHC, an exception can only be raised when a thread
--   reaches a <i>safe point</i>, where a safe point is where memory
--   allocation occurs. Some loops do not perform any memory allocation
--   inside the loop and therefore cannot be interrupted by a
--   <a>throwTo</a>.
--   
--   If the target of <a>throwTo</a> is the calling thread, then the
--   behaviour is the same as <a>throwIO</a>, except that the exception is
--   thrown as an asynchronous exception. This means that if there is an
--   enclosing pure computation, which would be the case if the current IO
--   operation is inside <a>unsafePerformIO</a> or
--   <a>unsafeInterleaveIO</a>, that computation is not permanently
--   replaced by the exception, but is suspended as if it had received an
--   asynchronous exception.
--   
--   Note that if <a>throwTo</a> is called with the current thread as the
--   target, the exception will be thrown even if the thread is currently
--   inside <a>mask</a> or <a>uninterruptibleMask</a>.
throwTo :: Exception e => ThreadId -> e -> IO ()

-- | 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:
--   
--   <pre>
--   catch (readFile f)
--         (\e -&gt; do let err = show (e :: IOException)
--                   hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err)
--                   return "")
--   </pre>
--   
--   Note that we have to give a type signature to <tt>e</tt>, 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 <a>Control.Exception</a>) for an explanation of
--   the problems with doing so.
--   
--   For catching exceptions in pure (non-<a>IO</a>) expressions, see the
--   function <a>evaluate</a>.
--   
--   Note that due to Haskell's unspecified evaluation order, an expression
--   may throw one of several possible exceptions: consider the expression
--   <tt>(error "urk") + (1 `div` 0)</tt>. Does the expression throw
--   <tt>ErrorCall "urk"</tt>, or <tt>DivideByZero</tt>?
--   
--   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 <tt>catch</tt> with type <tt>IO
--   Int -&gt; (ArithException -&gt; IO Int) -&gt; IO Int</tt> then the
--   handler may get run with <tt>DivideByZero</tt> as an argument, or an
--   <tt>ErrorCall "urk"</tt> exception may be propogated further up. If
--   you call it again, you might get a the opposite behaviour. This is ok,
--   because <a>catch</a> is an <a>IO</a> computation.
catch :: Exception e => IO a -> (e -> IO a) -> IO a

-- | Sometimes you want to catch two different sorts of exception. You
--   could do something like
--   
--   <pre>
--   f = expr `catch` \ (ex :: ArithException) -&gt; handleArith ex
--            `catch` \ (ex :: IOException)    -&gt; handleIO    ex
--   </pre>
--   
--   However, there are a couple of problems with this approach. The first
--   is that having two exception handlers is inefficient. However, the
--   more serious issue is that the second exception handler will catch
--   exceptions in the first, e.g. in the example above, if
--   <tt>handleArith</tt> throws an <tt>IOException</tt> then the second
--   exception handler will catch it.
--   
--   Instead, we provide a function <a>catches</a>, which would be used
--   thus:
--   
--   <pre>
--   f = expr `catches` [Handler (\ (ex :: ArithException) -&gt; handleArith ex),
--                       Handler (\ (ex :: IOException)    -&gt; handleIO    ex)]
--   </pre>
catches :: IO a -> [Handler a] -> IO a

-- | You need this when using <a>catches</a>.
data Handler a
Handler :: (e -> IO a) -> Handler a

-- | The function <a>catchJust</a> is like <a>catch</a>, but it takes an
--   extra argument which is an <i>exception predicate</i>, a function
--   which selects which type of exceptions we're interested in.
--   
--   <pre>
--   catchJust (\e -&gt; if isDoesNotExistErrorType (ioeGetErrorType e) then Just () else Nothing)
--             (readFile f)
--             (\_ -&gt; do hPutStrLn stderr ("No such file: " ++ show f)
--                       return "")
--   </pre>
--   
--   Any other exceptions which are not matched by the predicate are
--   re-raised, and may be caught by an enclosing <a>catch</a>,
--   <a>catchJust</a>, etc.
catchJust :: Exception e => (e -> Maybe b) -> IO a -> (b -> IO a) -> IO a

-- | A version of <a>catch</a> with the arguments swapped around; useful in
--   situations where the code for the handler is shorter. For example:
--   
--   <pre>
--   do handle (\NonTermination -&gt; exitWith (ExitFailure 1)) $
--      ...
--   </pre>
handle :: Exception e => (e -> IO a) -> IO a -> IO a

-- | A version of <a>catchJust</a> with the arguments swapped around (see
--   <a>handle</a>).
handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a

-- | Similar to <a>catch</a>, but returns an <a>Either</a> result which is
--   <tt>(<a>Right</a> a)</tt> if no exception of type <tt>e</tt> was
--   raised, or <tt>(<a>Left</a> ex)</tt> if an exception of type
--   <tt>e</tt> was raised and its value is <tt>ex</tt>. If any other type
--   of exception is raised than it will be propogated up to the next
--   enclosing exception handler.
--   
--   <pre>
--   try a = catch (Right `liftM` a) (return . Left)
--   </pre>
--   
--   Note that <a>System.IO.Error</a> also exports a function called
--   <a>try</a> with a similar type to <a>try</a>, except that it catches
--   only the IO and user families of exceptions (as required by the
--   Haskell 98 <tt>IO</tt> module).
try :: Exception e => IO a -> IO (Either e a)

-- | A variant of <a>try</a> that takes an exception predicate to select
--   which exceptions are caught (c.f. <a>catchJust</a>). If the exception
--   does not match the predicate, it is re-thrown.
tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)

-- | Forces its argument to be evaluated to weak head normal form when the
--   resultant <a>IO</a> action is executed. It can be used to order
--   evaluation with respect to other <a>IO</a> operations; its semantics
--   are given by
--   
--   <pre>
--   evaluate x `seq` y    ==&gt;  y
--   evaluate x `catch` f  ==&gt;  (return $! x) `catch` f
--   evaluate x &gt;&gt;= f      ==&gt;  (return $! x) &gt;&gt;= f
--   </pre>
--   
--   <i>Note:</i> the first equation implies that <tt>(evaluate x)</tt> is
--   <i>not</i> the same as <tt>(return $! x)</tt>. A correct definition is
--   
--   <pre>
--   evaluate x = (return $! x) &gt;&gt;= return
--   </pre>
evaluate :: a -> IO a

-- | This function maps one exception into another as proposed in the paper
--   "A semantics for imprecise exceptions".
mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a

-- | Executes an IO computation with asynchronous exceptions <i>masked</i>.
--   That is, any thread which attempts to raise an exception in the
--   current thread with <a>throwTo</a> will be blocked until asynchronous
--   exceptions are unmasked again.
--   
--   The argument passed to <a>mask</a> 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 <a>mask</a> is to protect the acquisition
--   of a resource:
--   
--   <pre>
--   mask $ \restore -&gt; do
--       x &lt;- acquire
--       restore (do_something_with x) `onException` release
--       release
--   </pre>
--   
--   This code guarantees that <tt>acquire</tt> is paired with
--   <tt>release</tt>, by masking asynchronous exceptions for the critical
--   parts. (Rather than write this code yourself, it would be better to
--   use <a>bracket</a> which abstracts the general pattern).
--   
--   Note that the <tt>restore</tt> action passed to the argument to
--   <a>mask</a> 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, <a>mask</a> 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 <a>forkIOWithUnmask</a>.
--   
--   Asynchronous exceptions may still be received while in the masked
--   state if the masked thread <i>blocks</i> in certain ways; see
--   <a>Control.Exception#interruptible</a>.
--   
--   Threads created by <a>forkIO</a> inherit the masked state from the
--   parent; that is, to start a thread in blocked mode, use <tt>mask_ $
--   forkIO ...</tt>. 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 a new thread in an unmasked state
--   use <a>forkIOUnmasked</a>.
mask :: ((forall a. IO a -> IO a) -> IO b) -> IO b

-- | Like <a>mask</a>, but does not pass a <tt>restore</tt> action to the
--   argument.
mask_ :: IO a -> IO a

-- | Like <a>mask</a>, but the masked computation is not interruptible (see
--   <a>Control.Exception#interruptible</a>). THIS SHOULD BE USED WITH
--   GREAT CARE, because if a thread executing in
--   <a>uninterruptibleMask</a> blocks for any reason, then the thread (and
--   possibly the program, if this is the main thread) will be unresponsive
--   and unkillable. This function should only be necessary if you need to
--   mask exceptions around an interruptible operation, and you can
--   guarantee that the interruptible operation will only block for a short
--   period of time.
uninterruptibleMask :: ((forall a. IO a -> IO a) -> IO b) -> IO b

-- | Like <a>uninterruptibleMask</a>, but does not pass a <tt>restore</tt>
--   action to the argument.
uninterruptibleMask_ :: IO a -> IO a

-- | Describes the behaviour of a thread when an asynchronous exception is
--   received.
data MaskingState

-- | asynchronous exceptions are unmasked (the normal state)
Unmasked :: MaskingState

-- | the state during <a>mask</a>: asynchronous exceptions are masked, but
--   blocking operations may still be interrupted
MaskedInterruptible :: MaskingState

-- | the state during <a>uninterruptibleMask</a>: asynchronous exceptions
--   are masked, and blocking operations may not be interrupted
MaskedUninterruptible :: MaskingState

-- | Returns the <a>MaskingState</a> for the current thread.
getMaskingState :: IO MaskingState

-- | When invoked inside <a>mask</a>, this function allows a blocked
--   asynchronous exception to be raised, if one exists. It is equivalent
--   to performing an interruptible operation (see ), but does not involve
--   any actual blocking.
--   
--   When called outside <a>mask</a>, or inside <a>uninterruptibleMask</a>,
--   this function has no effect.
allowInterrupt :: IO ()

-- | Note: this function is deprecated, please use <a>mask</a> instead.
--   
--   Applying <a>block</a> to a computation will execute that computation
--   with asynchronous exceptions <i>blocked</i>. That is, any thread which
--   attempts to raise an exception in the current thread with
--   <a>throwTo</a> will be blocked until asynchronous exceptions are
--   unblocked again. There's no need to worry about re-enabling
--   asynchronous exceptions; that is done automatically on exiting the
--   scope of <a>block</a>.
--   
--   Threads created by <a>forkIO</a> inherit the blocked state from the
--   parent; that is, to start a thread in blocked mode, use <tt>block $
--   forkIO ...</tt>. This is particularly useful if you need to establish
--   an exception handler in the forked thread before any asynchronous
--   exceptions are received.

-- | <i>Deprecated: use Control.Exception.mask instead </i>
block :: IO a -> IO a

-- | Note: this function is deprecated, please use <a>mask</a> instead.
--   
--   To re-enable asynchronous exceptions inside the scope of <a>block</a>,
--   <a>unblock</a> can be used. It scopes in exactly the same way, so on
--   exit from <a>unblock</a> asynchronous exception delivery will be
--   disabled again.

-- | <i>Deprecated: use Control.Exception.mask instead </i>
unblock :: IO a -> IO a

-- | returns True if asynchronous exceptions are blocked in the current
--   thread.

-- | <i>Deprecated: use Control.Exception.getMaskingState instead </i>
blocked :: IO Bool

-- | If the first argument evaluates to <a>True</a>, then the result is the
--   second argument. Otherwise an <tt>AssertionFailed</tt> exception is
--   raised, containing a <a>String</a> with the source file and line
--   number of the call to <a>assert</a>.
--   
--   Assertions can normally be turned on or off with a compiler flag (for
--   GHC, assertions are normally on unless optimisation is turned on with
--   <tt>-O</tt> or the <tt>-fignore-asserts</tt> option is given). When
--   assertions are turned off, the first argument to <a>assert</a> is
--   ignored, and the second argument is returned as the result.
assert :: Bool -> a -> a

-- | When you want to acquire a resource, do some work with it, and then
--   release the resource, it is a good idea to use <a>bracket</a>, because
--   <a>bracket</a> 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 <a>bracket</a> will
--   re-raise the exception (after performing the release).
--   
--   A common example is opening a file:
--   
--   <pre>
--   bracket
--     (openFile "filename" ReadMode)
--     (hClose)
--     (\fileHandle -&gt; do { ... })
--   </pre>
--   
--   The arguments to <a>bracket</a> are in this order so that we can
--   partially apply it, e.g.:
--   
--   <pre>
--   withFile name mode = bracket (openFile name mode) hClose
--   </pre>
bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c

-- | A variant of <a>bracket</a> where the return value from the first
--   computation is not required.
bracket_ :: IO a -> IO b -> IO c -> IO c

-- | Like <a>bracket</a>, but only performs the final action if there was
--   an exception raised by the in-between computation.
bracketOnError :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c

-- | A specialised variant of <a>bracket</a> with just a computation to run
--   afterward.
finally :: IO a -> IO b -> IO a

-- | Like <a>finally</a>, but only performs the final action if there was
--   an exception raised by the computation.
onException :: IO a -> IO b -> IO a
instance Functor Handler


-- | "Unsafe" IO operations.
module System.IO.Unsafe

-- | This is the "back door" into the <a>IO</a> monad, allowing <a>IO</a>
--   computation to be performed at any time. For this to be safe, the
--   <a>IO</a> computation should be free of side effects and independent
--   of its environment.
--   
--   If the I/O computation wrapped in <a>unsafePerformIO</a> performs side
--   effects, then the relative order in which those side effects take
--   place (relative to the main I/O trunk, or other calls to
--   <a>unsafePerformIO</a>) is indeterminate. Furthermore, when using
--   <a>unsafePerformIO</a> to cause side-effects, you should take the
--   following precautions to ensure the side effects are performed as many
--   times as you expect them to be. Note that these precautions are
--   necessary for GHC, but may not be sufficient, and other compilers may
--   require different precautions:
--   
--   <ul>
--   <li>Use <tt>{-# NOINLINE foo #-}</tt> as a pragma on any function
--   <tt>foo</tt> that calls <a>unsafePerformIO</a>. If the call is
--   inlined, the I/O may be performed more than once.</li>
--   <li>Use the compiler flag <tt>-fno-cse</tt> to prevent common
--   sub-expression elimination being performed on the module, which might
--   combine two side effects that were meant to be separate. A good
--   example is using multiple global variables (like <tt>test</tt> in the
--   example below).</li>
--   <li>Make sure that the either you switch off let-floating
--   (<tt>-fno-full-laziness</tt>), or that the call to
--   <a>unsafePerformIO</a> cannot float outside a lambda. For example, if
--   you say: <tt> f x = unsafePerformIO (newIORef []) </tt> you may get
--   only one reference cell shared between all calls to <tt>f</tt>. Better
--   would be <tt> f x = unsafePerformIO (newIORef [x]) </tt> because now
--   it can't float outside the lambda.</li>
--   </ul>
--   
--   It is less well known that <a>unsafePerformIO</a> is not type safe.
--   For example:
--   
--   <pre>
--   test :: IORef [a]
--   test = unsafePerformIO $ newIORef []
--   
--   main = do
--           writeIORef test [42]
--           bang &lt;- readIORef test
--           print (bang :: [Char])
--   </pre>
--   
--   This program will core dump. This problem with polymorphic references
--   is well known in the ML community, and does not arise with normal
--   monadic use of references. There is no easy way to make it impossible
--   once you use <a>unsafePerformIO</a>. Indeed, it is possible to write
--   <tt>coerce :: a -&gt; b</tt> with the help of <a>unsafePerformIO</a>.
--   So be careful!
unsafePerformIO :: IO a -> a

-- | This version of <a>unsafePerformIO</a> is more efficient because it
--   omits the check that the IO is only being performed by a single
--   thread. Hence, when you use <a>unsafeDupablePerformIO</a>, there is a
--   possibility that the IO action may be performed multiple times (on a
--   multiprocessor), and you should therefore ensure that it gives the
--   same results each time.
unsafeDupablePerformIO :: IO a -> a

-- | <a>unsafeInterleaveIO</a> allows <a>IO</a> computation to be deferred
--   lazily. When passed a value of type <tt>IO a</tt>, the <a>IO</a> will
--   only be performed when the value of the <tt>a</tt> is demanded. This
--   is used to implement lazy file reading, see <a>hGetContents</a>.
unsafeInterleaveIO :: IO a -> IO a

-- | A slightly faster version of <a>fixIO</a> that may not be safe to use
--   with multiple threads. The unsafety arises when used like this:
--   
--   <pre>
--   unsafeFixIO $ \r -&gt;
--      forkIO (print r)
--      return (...)
--   </pre>
--   
--   In this case, the child thread will receive a <tt>NonTermination</tt>
--   exception instead of waiting for the value of <tt>r</tt> to be
--   computed.
unsafeFixIO :: (a -> IO a) -> IO a


-- | Standard IO Errors.
module System.IO.Error

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

-- | Construct an <a>IOError</a> value with a string describing the error.
--   The <a>fail</a> method of the <a>IO</a> instance of the <a>Monad</a>
--   class raises a <a>userError</a>, thus:
--   
--   <pre>
--   instance Monad IO where 
--     ...
--     fail s = ioError (userError s)
--   </pre>
userError :: String -> IOError

-- | Construct an <a>IOError</a> 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.
mkIOError :: IOErrorType -> String -> Maybe Handle -> Maybe FilePath -> IOError

-- | Adds a location description and maybe a file path and file handle to
--   an <a>IOError</a>. If any of the file handle or file path is not given
--   the corresponding value in the <a>IOError</a> remains unaltered.
annotateIOError :: IOError -> String -> Maybe Handle -> Maybe FilePath -> IOError

-- | An error indicating that an <a>IO</a> operation failed because one of
--   its arguments already exists.
isAlreadyExistsError :: IOError -> Bool

-- | An error indicating that an <a>IO</a> operation failed because one of
--   its arguments does not exist.
isDoesNotExistError :: IOError -> Bool

-- | An error indicating that an <a>IO</a> operation failed because one of
--   its arguments is a single-use resource, which is already being used
--   (for example, opening the same file twice for writing might give this
--   error).
isAlreadyInUseError :: IOError -> Bool

-- | An error indicating that an <a>IO</a> operation failed because the
--   device is full.
isFullError :: IOError -> Bool

-- | An error indicating that an <a>IO</a> operation failed because the end
--   of file has been reached.
isEOFError :: IOError -> Bool

-- | An error indicating that an <a>IO</a> operation failed because the
--   operation was not possible. Any computation which returns an <a>IO</a>
--   result may fail with <a>isIllegalOperation</a>. In some cases, an
--   implementation will not be able to distinguish between the possible
--   error causes. In this case it should fail with
--   <a>isIllegalOperation</a>.
isIllegalOperation :: IOError -> Bool

-- | An error indicating that an <a>IO</a> operation failed because the
--   user does not have sufficient operating system privilege to perform
--   that operation.
isPermissionError :: IOError -> Bool

-- | A programmer-defined error value constructed using <a>userError</a>.
isUserError :: IOError -> Bool
ioeGetErrorType :: IOError -> IOErrorType
ioeGetLocation :: IOError -> String
ioeGetErrorString :: IOError -> String
ioeGetHandle :: IOError -> Maybe Handle
ioeGetFileName :: IOError -> Maybe FilePath
ioeSetErrorType :: IOError -> IOErrorType -> IOError
ioeSetErrorString :: IOError -> String -> IOError
ioeSetLocation :: IOError -> String -> IOError
ioeSetHandle :: IOError -> Handle -> IOError
ioeSetFileName :: IOError -> FilePath -> IOError

-- | An abstract type that contains a value for each variant of
--   <a>IOError</a>.
data IOErrorType

-- | I/O error where the operation failed because one of its arguments
--   already exists.
alreadyExistsErrorType :: IOErrorType

-- | I/O error where the operation failed because one of its arguments does
--   not exist.
doesNotExistErrorType :: IOErrorType

-- | I/O error where the operation failed because one of its arguments is a
--   single-use resource, which is already being used.
alreadyInUseErrorType :: IOErrorType

-- | I/O error where the operation failed because the device is full.
fullErrorType :: IOErrorType

-- | I/O error where the operation failed because the end of file has been
--   reached.
eofErrorType :: IOErrorType

-- | I/O error where the operation is not possible.
illegalOperationErrorType :: IOErrorType

-- | I/O error where the operation failed because the user does not have
--   sufficient operating system privilege to perform that operation.
permissionErrorType :: IOErrorType

-- | I/O error that is programmer-defined.
userErrorType :: IOErrorType

-- | I/O error where the operation failed because one of its arguments
--   already exists.
isAlreadyExistsErrorType :: IOErrorType -> Bool

-- | I/O error where the operation failed because one of its arguments does
--   not exist.
isDoesNotExistErrorType :: IOErrorType -> Bool

-- | I/O error where the operation failed because one of its arguments is a
--   single-use resource, which is already being used.
isAlreadyInUseErrorType :: IOErrorType -> Bool

-- | I/O error where the operation failed because the device is full.
isFullErrorType :: IOErrorType -> Bool

-- | I/O error where the operation failed because the end of file has been
--   reached.
isEOFErrorType :: IOErrorType -> Bool

-- | I/O error where the operation is not possible.
isIllegalOperationErrorType :: IOErrorType -> Bool

-- | I/O error where the operation failed because the user does not have
--   sufficient operating system privilege to perform that operation.
isPermissionErrorType :: IOErrorType -> Bool

-- | I/O error that is programmer-defined.
isUserErrorType :: IOErrorType -> Bool

-- | Raise an <a>IOError</a> in the <a>IO</a> monad.
ioError :: IOError -> IO a

-- | The <a>catchIOError</a> function establishes a handler that receives
--   any <a>IOError</a> raised in the action protected by
--   <a>catchIOError</a>. An <a>IOError</a> is caught by the most recent
--   handler established by one of the exception handling functions. These
--   handlers are not selective: all <a>IOError</a>s are caught. Exception
--   propagation must be explicitly provided in a handler by re-raising any
--   unwanted exceptions. For example, in
--   
--   <pre>
--   f = catchIOError g (\e -&gt; if IO.isEOFError e then return [] else ioError e)
--   </pre>
--   
--   the function <tt>f</tt> returns <tt>[]</tt> when an end-of-file
--   exception (cf. <a>isEOFError</a>) occurs in <tt>g</tt>; otherwise, the
--   exception is propagated to the next outer handler.
--   
--   When an exception propagates outside the main program, the Haskell
--   system prints the associated <a>IOError</a> value and exits the
--   program.
--   
--   Non-I/O exceptions are not caught by this variant; to catch all
--   exceptions, use <a>catch</a> from <a>Control.Exception</a>.
catchIOError :: IO a -> (IOError -> IO a) -> IO a

-- | The construct <a>tryIOError</a> <tt>comp</tt> 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 <a>try</a> from <a>Control.Exception</a>.
tryIOError :: IO a -> IO (Either IOError a)

-- | Catch any <a>IOError</a> that occurs in the computation and throw a
--   modified version.
modifyIOError :: (IOError -> IOError) -> IO a -> IO a

module GHC.Conc.Signal
type Signal = CInt
type HandlerFun = ForeignPtr Word8 -> IO ()
setHandler :: Signal -> Maybe (HandlerFun, Dynamic) -> IO (Maybe (HandlerFun, Dynamic))
runHandlers :: ForeignPtr Word8 -> Signal -> IO ()


-- | POSIX data types: Haskell equivalents of the types defined by the
--   <tt>&lt;sys/types.h&gt;</tt> C header on a POSIX system.
module System.Posix.Types
newtype CDev
CDev :: Word64 -> CDev
newtype CIno
CIno :: Word64 -> CIno
newtype CMode
CMode :: Word32 -> CMode
newtype COff
COff :: Int64 -> COff
newtype CPid
CPid :: Int32 -> CPid
newtype CSsize
CSsize :: Int32 -> CSsize
newtype CGid
CGid :: Word32 -> CGid
newtype CNlink
CNlink :: Word32 -> CNlink
newtype CUid
CUid :: Word32 -> CUid
newtype CCc
CCc :: Word8 -> CCc
newtype CSpeed
CSpeed :: Word32 -> CSpeed
newtype CTcflag
CTcflag :: Word32 -> CTcflag
newtype CRLim
CRLim :: Word64 -> CRLim
newtype Fd
Fd :: CInt -> Fd
type LinkCount = CNlink
type UserID = CUid
type GroupID = CGid
type ByteCount = CSize
type ClockTick = CClock
type EpochTime = CTime
type FileOffset = COff
type ProcessID = CPid
type ProcessGroupID = CPid
type DeviceID = CDev
type FileID = CIno
type FileMode = CMode
type Limit = CLong
instance Typeable Fd
instance Typeable CRLim
instance Typeable CTcflag
instance Typeable CSpeed
instance Typeable CCc
instance Typeable CUid
instance Typeable CNlink
instance Typeable CGid
instance Typeable CSsize
instance Typeable CPid
instance Typeable COff
instance Typeable CMode
instance Typeable CIno
instance Typeable CDev
instance Eq CDev
instance Ord CDev
instance Num CDev
instance Enum CDev
instance Storable CDev
instance Real CDev
instance Bounded CDev
instance Integral CDev
instance Bits CDev
instance Eq CIno
instance Ord CIno
instance Num CIno
instance Enum CIno
instance Storable CIno
instance Real CIno
instance Bounded CIno
instance Integral CIno
instance Bits CIno
instance Eq CMode
instance Ord CMode
instance Num CMode
instance Enum CMode
instance Storable CMode
instance Real CMode
instance Bounded CMode
instance Integral CMode
instance Bits CMode
instance Eq COff
instance Ord COff
instance Num COff
instance Enum COff
instance Storable COff
instance Real COff
instance Bounded COff
instance Integral COff
instance Bits COff
instance Eq CPid
instance Ord CPid
instance Num CPid
instance Enum CPid
instance Storable CPid
instance Real CPid
instance Bounded CPid
instance Integral CPid
instance Bits CPid
instance Eq CSsize
instance Ord CSsize
instance Num CSsize
instance Enum CSsize
instance Storable CSsize
instance Real CSsize
instance Bounded CSsize
instance Integral CSsize
instance Bits CSsize
instance Eq CGid
instance Ord CGid
instance Num CGid
instance Enum CGid
instance Storable CGid
instance Real CGid
instance Bounded CGid
instance Integral CGid
instance Bits CGid
instance Eq CNlink
instance Ord CNlink
instance Num CNlink
instance Enum CNlink
instance Storable CNlink
instance Real CNlink
instance Bounded CNlink
instance Integral CNlink
instance Bits CNlink
instance Eq CUid
instance Ord CUid
instance Num CUid
instance Enum CUid
instance Storable CUid
instance Real CUid
instance Bounded CUid
instance Integral CUid
instance Bits CUid
instance Eq CCc
instance Ord CCc
instance Num CCc
instance Enum CCc
instance Storable CCc
instance Real CCc
instance Eq CSpeed
instance Ord CSpeed
instance Num CSpeed
instance Enum CSpeed
instance Storable CSpeed
instance Real CSpeed
instance Eq CTcflag
instance Ord CTcflag
instance Num CTcflag
instance Enum CTcflag
instance Storable CTcflag
instance Real CTcflag
instance Bounded CTcflag
instance Integral CTcflag
instance Bits CTcflag
instance Eq CRLim
instance Ord CRLim
instance Num CRLim
instance Enum CRLim
instance Storable CRLim
instance Real CRLim
instance Bounded CRLim
instance Integral CRLim
instance Bits CRLim
instance Eq Fd
instance Ord Fd
instance Num Fd
instance Enum Fd
instance Storable Fd
instance Real Fd
instance Bounded Fd
instance Integral Fd
instance Bits Fd
instance Show Fd
instance Read Fd
instance Show CRLim
instance Read CRLim
instance Show CTcflag
instance Read CTcflag
instance Show CSpeed
instance Read CSpeed
instance Show CCc
instance Read CCc
instance Show CUid
instance Read CUid
instance Show CNlink
instance Read CNlink
instance Show CGid
instance Read CGid
instance Show CSsize
instance Read CSsize
instance Show CPid
instance Read CPid
instance Show COff
instance Read COff
instance Show CMode
instance Read CMode
instance Show CIno
instance Read CIno
instance Show CDev
instance Read CDev

module GHC.Fingerprint
data Fingerprint
Fingerprint :: {-# UNPACK #-} !Word64 -> {-# UNPACK #-} !Word64 -> Fingerprint
fingerprint0 :: Fingerprint
fingerprintData :: Ptr Word8 -> Int -> IO Fingerprint
fingerprintString :: String -> Fingerprint
fingerprintFingerprints :: [Fingerprint] -> Fingerprint


-- | A collection of data types, classes, and functions for interfacing
--   with another programming language.
--   
--   Safe API Only.
module Foreign.Safe


-- | This module provides text encoding/decoding using iconv
module GHC.IO.Encoding.Iconv
iconvEncoding :: String -> IO TextEncoding
mkIconvEncoding :: CodingFailureMode -> String -> IO TextEncoding
localeEncodingName :: String


-- | Text codecs for I/O
module GHC.IO.Encoding
data BufferCodec from to state
BufferCodec :: (Buffer from -> Buffer to -> IO (CodingProgress, Buffer from, Buffer to)) -> (Buffer from -> Buffer to -> IO (Buffer from, Buffer to)) -> IO () -> IO state -> (state -> IO ()) -> BufferCodec from to state

-- | The <tt>encode</tt> function translates elements of the buffer
--   <tt>from</tt> to the buffer <tt>to</tt>. It should translate as many
--   elements as possible given the sizes of the buffers, including
--   translating zero elements if there is either not enough room in
--   <tt>to</tt>, or <tt>from</tt> does not contain a complete multibyte
--   sequence.
--   
--   The fact that as many elements as possible are translated is used by
--   the IO library in order to report translation errors at the point they
--   actually occur, rather than when the buffer is translated.
--   
--   To allow us to use iconv as a BufferCode efficiently, character
--   buffers are defined to contain lone surrogates instead of those
--   private use characters that are used for roundtripping. Thus, Chars
--   poked and peeked from a character buffer must undergo
--   surrogatifyRoundtripCharacter and desurrogatifyRoundtripCharacter
--   respectively.
--   
--   For more information on this, see Note [Roundtripping] in
--   GHC.IO.Encoding.Failure.
encode :: BufferCodec from to state -> Buffer from -> Buffer to -> IO (CodingProgress, Buffer from, Buffer to)

-- | The <tt>recover</tt> function is used to continue decoding in the
--   presence of invalid or unrepresentable sequences. This includes both
--   those detected by <tt>encode</tt> returning <tt>InvalidSequence</tt>
--   and those that occur because the input byte sequence appears to be
--   truncated.
--   
--   Progress will usually be made by skipping the first element of the
--   <tt>from</tt> buffer. This function should only be called if you are
--   certain that you wish to do this skipping and if the <tt>to</tt>
--   buffer has at least one element of free space. Because this function
--   deals with decoding failure, it assumes that the from buffer has at
--   least one element.
--   
--   <tt>recover</tt> may raise an exception rather than skipping anything.
--   
--   Currently, some implementations of <tt>recover</tt> may mutate the
--   input buffer. In particular, this feature is used to implement
--   transliteration.
recover :: BufferCodec from to state -> Buffer from -> Buffer to -> IO (Buffer from, Buffer to)

-- | Resources associated with the encoding may now be released. The
--   <tt>encode</tt> function may not be called again after calling
--   <tt>close</tt>.
close :: BufferCodec from to state -> IO ()

-- | Return the current state of the codec.
--   
--   Many codecs are not stateful, and in these case the state can be
--   represented as '()'. Other codecs maintain a state. For example,
--   UTF-16 recognises a BOM (byte-order-mark) character at the beginning
--   of the input, and remembers thereafter whether to use big-endian or
--   little-endian mode. In this case, the state of the codec would include
--   two pieces of information: whether we are at the beginning of the
--   stream (the BOM only occurs at the beginning), and if not, whether to
--   use the big or little-endian encoding.
getState :: BufferCodec from to state -> IO state
setState :: BufferCodec from to state -> state -> IO ()

-- | A <a>TextEncoding</a> is a specification of a conversion scheme
--   between sequences of bytes and sequences of Unicode characters.
--   
--   For example, UTF-8 is an encoding of Unicode characters into a
--   sequence of bytes. The <a>TextEncoding</a> for UTF-8 is <tt>utf8</tt>.
data TextEncoding
TextEncoding :: String -> IO (TextDecoder dstate) -> IO (TextEncoder estate) -> TextEncoding

-- | a string that can be passed to <tt>mkTextEncoding</tt> to create an
--   equivalent <a>TextEncoding</a>.
textEncodingName :: TextEncoding -> String

-- | Creates a means of decoding bytes into characters: the result must not
--   be shared between several byte sequences or simultaneously across
--   threads
mkTextDecoder :: TextEncoding -> IO (TextDecoder dstate)

-- | Creates a means of encode characters into bytes: the result must not
--   be shared between several character sequences or simultaneously across
--   threads
mkTextEncoder :: TextEncoding -> IO (TextEncoder estate)
type TextEncoder state = BufferCodec CharBufElem Word8 state
type TextDecoder state = BufferCodec Word8 CharBufElem state
data CodingProgress

-- | Stopped because the input contains insufficient available elements, or
--   all of the input sequence has been sucessfully translated.
InputUnderflow :: CodingProgress

-- | Stopped because the output contains insufficient free elements
OutputUnderflow :: CodingProgress

-- | Stopped because there are sufficient free elements in the output to
--   output at least one encoded ASCII character, but the input contains an
--   invalid or unrepresentable sequence
InvalidSequence :: CodingProgress

-- | The Latin1 (ISO8859-1) encoding. This encoding maps bytes directly to
--   the first 256 Unicode code points, and is thus not a complete Unicode
--   encoding. An attempt to write a character greater than '\255' to a
--   <tt>Handle</tt> using the <a>latin1</a> encoding will result in an
--   error.
latin1 :: TextEncoding
latin1_encode :: CharBuffer -> Buffer Word8 -> IO (CharBuffer, Buffer Word8)
latin1_decode :: Buffer Word8 -> CharBuffer -> IO (Buffer Word8, CharBuffer)

-- | The UTF-8 Unicode encoding
utf8 :: TextEncoding

-- | The UTF-8 Unicode encoding, with a byte-order-mark (BOM; the byte
--   sequence 0xEF 0xBB 0xBF). This encoding behaves like <a>utf8</a>,
--   except that on input, the BOM sequence is ignored at the beginning of
--   the stream, and on output, the BOM sequence is prepended.
--   
--   The byte-order-mark is strictly unnecessary in UTF-8, but is sometimes
--   used to identify the encoding of a file.
utf8_bom :: TextEncoding

-- | The UTF-16 Unicode encoding (a byte-order-mark should be used to
--   indicate endianness).
utf16 :: TextEncoding

-- | The UTF-16 Unicode encoding (litte-endian)
utf16le :: TextEncoding

-- | The UTF-16 Unicode encoding (big-endian)
utf16be :: TextEncoding

-- | The UTF-32 Unicode encoding (a byte-order-mark should be used to
--   indicate endianness).
utf32 :: TextEncoding

-- | The UTF-32 Unicode encoding (litte-endian)
utf32le :: TextEncoding

-- | The UTF-32 Unicode encoding (big-endian)
utf32be :: TextEncoding
initLocaleEncoding :: TextEncoding

-- | The Unicode encoding of the current locale
getLocaleEncoding :: IO TextEncoding

-- | The Unicode encoding of the current locale, but allowing arbitrary
--   undecodable bytes to be round-tripped through it.
--   
--   This <a>TextEncoding</a> 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
--   <a>wide</a> W-family of UTF-16 APIs instead
getFileSystemEncoding :: IO TextEncoding

-- | The Unicode encoding of the current locale, but where undecodable
--   bytes are replaced with their closest visual match. Used for the
--   <tt>CString</tt> marshalling functions in <a>Foreign.C.String</a>
getForeignEncoding :: IO TextEncoding
setLocaleEncoding :: TextEncoding -> IO ()
setFileSystemEncoding :: TextEncoding -> IO ()
setForeignEncoding :: TextEncoding -> IO ()

-- | An encoding in which Unicode code points are translated to bytes by
--   taking the code point modulo 256. When decoding, bytes are translated
--   directly into the equivalent code point.
--   
--   This encoding never fails in either direction. However, encoding
--   discards information, so encode followed by decode is not the
--   identity.
char8 :: TextEncoding

-- | Look up the named Unicode encoding. May fail with
--   
--   <ul>
--   <li><tt>isDoesNotExistError</tt> if the encoding is unknown</li>
--   </ul>
--   
--   The set of known encodings is system-dependent, but includes at least:
--   
--   <ul>
--   <li><pre>UTF-8</pre></li>
--   <li><tt>UTF-16</tt>, <tt>UTF-16BE</tt>, <tt>UTF-16LE</tt></li>
--   <li><tt>UTF-32</tt>, <tt>UTF-32BE</tt>, <tt>UTF-32LE</tt></li>
--   </ul>
--   
--   On systems using GNU iconv (e.g. Linux), there is additional notation
--   for specifying how illegal characters are handled:
--   
--   <ul>
--   <li>a suffix of <tt>//IGNORE</tt>, e.g. <tt>UTF-8//IGNORE</tt>, will
--   cause all illegal sequences on input to be ignored, and on output will
--   drop all code points that have no representation in the target
--   encoding.</li>
--   <li>a suffix of <tt>//TRANSLIT</tt> will choose a replacement
--   character for illegal sequences or code points.</li>
--   </ul>
--   
--   On Windows, you can access supported code pages with the prefix
--   <tt>CP</tt>; for example, <tt>"CP1250"</tt>.
mkTextEncoding :: String -> IO TextEncoding


-- | Basic concurrency stuff.
module GHC.Conc.IO
ensureIOManagerIsRunning :: IO ()

-- | Suspends the current thread for a given number of microseconds (GHC
--   only).
--   
--   There is no guarantee that the thread will be rescheduled promptly
--   when the delay has expired, but the thread will never continue to run
--   <i>earlier</i> than specified.
threadDelay :: Int -> IO ()

-- | Set the value of returned TVar to True after a given number of
--   microseconds. The caveats associated with threadDelay also apply.
registerDelay :: Int -> IO (TVar Bool)

-- | Block the current thread until data is available to read on the given
--   file descriptor (GHC only).
--   
--   This will throw an <tt>IOError</tt> if the file descriptor was closed
--   while this thread was blocked. To safely close a file descriptor that
--   has been used with <a>threadWaitRead</a>, use <a>closeFdWith</a>.
threadWaitRead :: Fd -> IO ()

-- | Block the current thread until data can be written to the given file
--   descriptor (GHC only).
--   
--   This will throw an <tt>IOError</tt> if the file descriptor was closed
--   while this thread was blocked. To safely close a file descriptor that
--   has been used with <a>threadWaitWrite</a>, use <a>closeFdWith</a>.
threadWaitWrite :: Fd -> IO ()

-- | Close a file descriptor in a concurrency-safe way (GHC only). If you
--   are using <a>threadWaitRead</a> or <a>threadWaitWrite</a> to perform
--   blocking I/O, you <i>must</i> use this function to close file
--   descriptors, or blocked threads may not be woken.
--   
--   Any threads that are blocked on the file descriptor via
--   <a>threadWaitRead</a> or <a>threadWaitWrite</a> will be unblocked by
--   having IO exceptions thrown.
closeFdWith :: (Fd -> IO ()) -> Fd -> IO ()


-- | Basic concurrency stuff.
module GHC.Conc

-- | A <a>ThreadId</a> is an abstract type representing a handle to a
--   thread. <a>ThreadId</a> is an instance of <a>Eq</a>, <a>Ord</a> and
--   <a>Show</a>, where the <a>Ord</a> instance implements an arbitrary
--   total ordering over <a>ThreadId</a>s. The <a>Show</a> instance lets
--   you convert an arbitrary-valued <a>ThreadId</a> to string form;
--   showing a <a>ThreadId</a> value is occasionally useful when debugging
--   or diagnosing the behaviour of a concurrent program.
--   
--   <i>Note</i>: in GHC, if you have a <a>ThreadId</a>, you essentially
--   have a pointer to the thread itself. This means the thread itself
--   can't be garbage collected until you drop the <a>ThreadId</a>. This
--   misfeature will hopefully be corrected at a later date.
--   
--   <i>Note</i>: Hugs does not provide any operations on other threads; it
--   defines <a>ThreadId</a> as a synonym for ().
data ThreadId
ThreadId :: ThreadId# -> ThreadId

-- | Sparks off a new thread to run the <a>IO</a> computation passed as the
--   first argument, and returns the <a>ThreadId</a> of the newly created
--   thread.
--   
--   The new thread will be a lightweight thread; if you want to use a
--   foreign library that uses thread-local storage, use <a>forkOS</a>
--   instead.
--   
--   GHC note: the new thread inherits the <i>masked</i> state of the
--   parent (see <a>mask</a>).
--   
--   The newly created thread has an exception handler that discards the
--   exceptions <a>BlockedIndefinitelyOnMVar</a>,
--   <a>BlockedIndefinitelyOnSTM</a>, and <a>ThreadKilled</a>, and passes
--   all other exceptions to the uncaught exception handler.
forkIO :: IO () -> IO ThreadId

-- | This function is deprecated; use <a>forkIOWithUnmask</a> instead

-- | <i>Deprecated: use forkIOWithUnmask instead </i>
forkIOUnmasked :: IO () -> IO ThreadId

-- | Like <a>forkIO</a>, but the child thread is passed a function that can
--   be used to unmask asynchronous exceptions. This function is typically
--   used in the following way
--   
--   <pre>
--   ... mask_ $ forkIOWithUnmask $ \unmask -&gt;
--                  catch (unmask ...) handler
--   </pre>
--   
--   so that the exception handler in the child thread is established with
--   asynchronous exceptions masked, meanwhile the main body of the child
--   thread is executed in the unmasked state.
--   
--   Note that the unmask function passed to the child thread should only
--   be used in that thread; the behaviour is undefined if it is invoked in
--   a different thread.
forkIOWithUnmask :: ((forall a. IO a -> IO a) -> IO ()) -> IO ThreadId

-- | Like <a>forkIO</a>, but lets you specify on which processor the thread
--   should run. Unlike a <a>forkIO</a> thread, a thread created by
--   <a>forkOn</a> will stay on the same processor for its entire lifetime
--   (<a>forkIO</a> threads can migrate between processors according to the
--   scheduling policy). <a>forkOn</a> is useful for overriding the
--   scheduling policy when you know in advance how best to distribute the
--   threads.
--   
--   The <a>Int</a> argument specifies a <i>capability number</i> (see
--   <a>getNumCapabilities</a>). Typically capabilities correspond to
--   physical processors, but the exact behaviour is
--   implementation-dependent. The value passed to <a>forkOn</a> is
--   interpreted modulo the total number of capabilities as returned by
--   <a>getNumCapabilities</a>.
--   
--   GHC note: the number of capabilities is specified by the <tt>+RTS
--   -N</tt> option when the program is started. Capabilities can be fixed
--   to actual processor cores with <tt>+RTS -qa</tt> if the underlying
--   operating system supports that, although in practice this is usually
--   unnecessary (and may actually degrade perforamnce in some cases -
--   experimentation is recommended).
forkOn :: Int -> IO () -> IO ThreadId

-- | This function is deprecated; use <a>forkOn</a> instead

-- | <i>Deprecated: renamed to forkOn </i>
forkOnIO :: Int -> IO () -> IO ThreadId

-- | This function is deprecated; use <tt>forkOnWIthUnmask</tt> instead

-- | <i>Deprecated: use forkOnWithUnmask instead </i>
forkOnIOUnmasked :: Int -> IO () -> IO ThreadId

-- | Like <a>forkIOWithUnmask</a>, but the child thread is pinned to the
--   given CPU, as with <a>forkOn</a>.
forkOnWithUnmask :: Int -> ((forall a. IO a -> IO a) -> IO ()) -> IO ThreadId

-- | the value passed to the <tt>+RTS -N</tt> flag. This is the number of
--   Haskell threads that can run truly simultaneously at any given time,
--   and is typically set to the number of physical processor cores on the
--   machine.
--   
--   Strictly speaking it is better to use <a>getNumCapabilities</a>,
--   because the number of capabilities might vary at runtime.
numCapabilities :: Int

-- | Returns the number of Haskell threads that can run truly
--   simultaneously (on separate physical processors) at any given time. To
--   change this value, use <a>setNumCapabilities</a>.
getNumCapabilities :: IO Int

-- | Set the number of Haskell threads that can run truly simultaneously
--   (on separate physical processors) at any given time. The number passed
--   to <a>forkOn</a> is interpreted modulo this value. The initial value
--   is given by the <tt>+RTS -N</tt> runtime flag.
--   
--   This is also the number of threads that will participate in parallel
--   garbage collection. It is strongly recommended that the number of
--   capabilities is not set larger than the number of physical processor
--   cores, and it may often be beneficial to leave one or more cores free
--   to avoid contention with other processes in the machine.
setNumCapabilities :: Int -> IO ()
getNumProcessors :: IO Int

-- | Returns the number of sparks currently in the local spark pool
numSparks :: IO Int
childHandler :: SomeException -> IO ()

-- | Returns the <a>ThreadId</a> of the calling thread (GHC only).
myThreadId :: IO ThreadId

-- | <a>killThread</a> raises the <a>ThreadKilled</a> exception in the
--   given thread (GHC only).
--   
--   <pre>
--   killThread tid = throwTo tid ThreadKilled
--   </pre>
killThread :: ThreadId -> IO ()

-- | <a>throwTo</a> raises an arbitrary exception in the target thread (GHC
--   only).
--   
--   <a>throwTo</a> does not return until the exception has been raised in
--   the target thread. The calling thread can thus be certain that the
--   target thread has received the exception. This is a useful property to
--   know when dealing with race conditions: eg. if there are two threads
--   that can kill each other, it is guaranteed that only one of the
--   threads will get to kill the other.
--   
--   Whatever work the target thread was doing when the exception was
--   raised is not lost: the computation is suspended until required by
--   another thread.
--   
--   If the target thread is currently making a foreign call, then the
--   exception will not be raised (and hence <a>throwTo</a> will not
--   return) until the call has completed. This is the case regardless of
--   whether the call is inside a <a>mask</a> or not. However, in GHC a
--   foreign call can be annotated as <tt>interruptible</tt>, in which case
--   a <a>throwTo</a> will cause the RTS to attempt to cause the call to
--   return; see the GHC documentation for more details.
--   
--   Important note: the behaviour of <a>throwTo</a> differs from that
--   described in the paper "Asynchronous exceptions in Haskell"
--   (<a>http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm</a>).
--   In the paper, <a>throwTo</a> is non-blocking; but the library
--   implementation adopts a more synchronous design in which
--   <a>throwTo</a> does not return until the exception is received by the
--   target thread. The trade-off is discussed in Section 9 of the paper.
--   Like any blocking operation, <a>throwTo</a> is therefore interruptible
--   (see Section 5.3 of the paper). Unlike other interruptible operations,
--   however, <a>throwTo</a> is <i>always</i> interruptible, even if it
--   does not actually block.
--   
--   There is no guarantee that the exception will be delivered promptly,
--   although the runtime will endeavour to ensure that arbitrary delays
--   don't occur. In GHC, an exception can only be raised when a thread
--   reaches a <i>safe point</i>, where a safe point is where memory
--   allocation occurs. Some loops do not perform any memory allocation
--   inside the loop and therefore cannot be interrupted by a
--   <a>throwTo</a>.
--   
--   If the target of <a>throwTo</a> is the calling thread, then the
--   behaviour is the same as <a>throwIO</a>, except that the exception is
--   thrown as an asynchronous exception. This means that if there is an
--   enclosing pure computation, which would be the case if the current IO
--   operation is inside <a>unsafePerformIO</a> or
--   <a>unsafeInterleaveIO</a>, that computation is not permanently
--   replaced by the exception, but is suspended as if it had received an
--   asynchronous exception.
--   
--   Note that if <a>throwTo</a> is called with the current thread as the
--   target, the exception will be thrown even if the thread is currently
--   inside <a>mask</a> or <a>uninterruptibleMask</a>.
throwTo :: Exception e => ThreadId -> e -> IO ()
par :: a -> b -> b
pseq :: a -> b -> b

-- | Internal function used by the RTS to run sparks.
runSparks :: IO ()

-- | The <a>yield</a> action allows (forces, in a co-operative multitasking
--   implementation) a context-switch to any other currently runnable
--   threads (if any), and is occasionally useful when implementing
--   concurrency abstractions.
yield :: IO ()

-- | <a>labelThread</a> stores a string as identifier for this thread if
--   you built a RTS with debugging support. This identifier will be used
--   in the debugging output to make distinction of different threads
--   easier (otherwise you only have the thread state object's address in
--   the heap).
--   
--   Other applications like the graphical Concurrent Haskell Debugger
--   (<a>http://www.informatik.uni-kiel.de/~fhu/chd/</a>) may choose to
--   overload <a>labelThread</a> for their purposes as well.
labelThread :: ThreadId -> String -> IO ()

-- | make a weak pointer to a <a>ThreadId</a>. It can be important to do
--   this if you want to hold a reference to a <a>ThreadId</a> while still
--   allowing the thread to receive the <tt>BlockedIndefinitely</tt> family
--   of exceptions (e.g. <a>BlockedIndefinitelyOnMVar</a>). Holding a
--   normal <a>ThreadId</a> reference will prevent the delivery of
--   <tt>BlockedIndefinitely</tt> exceptions because the reference could be
--   used as the target of <a>throwTo</a> at any time, which would unblock
--   the thread.
--   
--   Holding a <tt>Weak ThreadId</tt>, on the other hand, will not prevent
--   the thread from receiving <tt>BlockedIndefinitely</tt> exceptions. It
--   is still possible to throw an exception to a <tt>Weak ThreadId</tt>,
--   but the caller must use <tt>deRefWeak</tt> first to determine whether
--   the thread still exists.
mkWeakThreadId :: ThreadId -> IO (Weak ThreadId)

-- | The current status of a thread
data ThreadStatus

-- | the thread is currently runnable or running
ThreadRunning :: ThreadStatus

-- | the thread has finished
ThreadFinished :: ThreadStatus

-- | the thread is blocked on some resource
ThreadBlocked :: BlockReason -> ThreadStatus

-- | the thread received an uncaught exception
ThreadDied :: ThreadStatus
data BlockReason

-- | blocked on on <a>MVar</a>
BlockedOnMVar :: BlockReason

-- | blocked on a computation in progress by another thread
BlockedOnBlackHole :: BlockReason

-- | blocked in <a>throwTo</a>
BlockedOnException :: BlockReason

-- | blocked in <a>retry</a> in an STM transaction
BlockedOnSTM :: BlockReason

-- | currently in a foreign call
BlockedOnForeignCall :: BlockReason

-- | blocked on some other resource. Without <tt>-threaded</tt>, I/O and
--   <tt>threadDelay</tt> show up as <a>BlockedOnOther</a>, with
--   <tt>-threaded</tt> they show up as <a>BlockedOnMVar</a>.
BlockedOnOther :: BlockReason
threadStatus :: ThreadId -> IO ThreadStatus

-- | returns the number of the capability on which the thread is currently
--   running, and a boolean indicating whether the thread is locked to that
--   capability or not. A thread is locked to a capability if it was
--   created with <tt>forkOn</tt>.
threadCapability :: ThreadId -> IO (Int, Bool)

-- | Suspends the current thread for a given number of microseconds (GHC
--   only).
--   
--   There is no guarantee that the thread will be rescheduled promptly
--   when the delay has expired, but the thread will never continue to run
--   <i>earlier</i> than specified.
threadDelay :: Int -> IO ()

-- | Set the value of returned TVar to True after a given number of
--   microseconds. The caveats associated with threadDelay also apply.
registerDelay :: Int -> IO (TVar Bool)

-- | Block the current thread until data is available to read on the given
--   file descriptor (GHC only).
--   
--   This will throw an <tt>IOError</tt> if the file descriptor was closed
--   while this thread was blocked. To safely close a file descriptor that
--   has been used with <a>threadWaitRead</a>, use <a>closeFdWith</a>.
threadWaitRead :: Fd -> IO ()

-- | Block the current thread until data can be written to the given file
--   descriptor (GHC only).
--   
--   This will throw an <tt>IOError</tt> if the file descriptor was closed
--   while this thread was blocked. To safely close a file descriptor that
--   has been used with <a>threadWaitWrite</a>, use <a>closeFdWith</a>.
threadWaitWrite :: Fd -> IO ()

-- | Close a file descriptor in a concurrency-safe way (GHC only). If you
--   are using <a>threadWaitRead</a> or <a>threadWaitWrite</a> to perform
--   blocking I/O, you <i>must</i> use this function to close file
--   descriptors, or blocked threads may not be woken.
--   
--   Any threads that are blocked on the file descriptor via
--   <a>threadWaitRead</a> or <a>threadWaitWrite</a> will be unblocked by
--   having IO exceptions thrown.
closeFdWith :: (Fd -> IO ()) -> Fd -> IO ()

-- | A monad supporting atomic memory transactions.
newtype STM a
STM :: (State# RealWorld -> (# State# RealWorld, a #)) -> STM a

-- | Perform a series of STM actions atomically.
--   
--   You cannot use <a>atomically</a> inside an <a>unsafePerformIO</a> or
--   <a>unsafeInterleaveIO</a>. Any attempt to do so will result in a
--   runtime error. (Reason: allowing this would effectively allow a
--   transaction inside a transaction, depending on exactly when the thunk
--   is evaluated.)
--   
--   However, see <a>newTVarIO</a>, which can be called inside
--   <a>unsafePerformIO</a>, and which allows top-level TVars to be
--   allocated.
atomically :: STM a -> IO a

-- | Retry execution of the current memory transaction because it has seen
--   values in TVars which mean that it should not continue (e.g. the TVars
--   represent a shared buffer that is now empty). The implementation may
--   block the thread until one of the TVars that it has read from has been
--   udpated. (GHC only)
retry :: STM a

-- | Compose two alternative STM actions (GHC only). If the first action
--   completes without retrying then it forms the result of the orElse.
--   Otherwise, if the first action retries, then the second action is
--   tried in its place. If both actions retry then the orElse as a whole
--   retries.
orElse :: STM a -> STM a -> STM a

-- | A variant of <a>throw</a> that can only be used within the <a>STM</a>
--   monad.
--   
--   Throwing an exception in <tt>STM</tt> aborts the transaction and
--   propagates the exception.
--   
--   Although <a>throwSTM</a> has a type that is an instance of the type of
--   <a>throw</a>, the two functions are subtly different:
--   
--   <pre>
--   throw e    `seq` x  ===&gt; throw e
--   throwSTM e `seq` x  ===&gt; x
--   </pre>
--   
--   The first example will cause the exception <tt>e</tt> to be raised,
--   whereas the second one won't. In fact, <a>throwSTM</a> will only cause
--   an exception to be raised when it is used within the <a>STM</a> monad.
--   The <a>throwSTM</a> variant should be used in preference to
--   <a>throw</a> to raise an exception within the <a>STM</a> monad because
--   it guarantees ordering with respect to other <a>STM</a> operations,
--   whereas <a>throw</a> does not.
throwSTM :: Exception e => e -> STM a

-- | Exception handling within STM actions.
catchSTM :: Exception e => STM a -> (e -> STM a) -> STM a

-- | alwaysSucceeds adds a new invariant that must be true when passed to
--   alwaysSucceeds, at the end of the current transaction, and at the end
--   of every subsequent transaction. If it fails at any of those points
--   then the transaction violating it is aborted and the exception raised
--   by the invariant is propagated.
alwaysSucceeds :: STM a -> STM ()

-- | always is a variant of alwaysSucceeds in which the invariant is
--   expressed as an STM Bool action that must return True. Returning False
--   or raising an exception are both treated as invariant failures.
always :: STM Bool -> STM ()

-- | Shared memory locations that support atomic memory transactions.
data TVar a
TVar :: (TVar# RealWorld a) -> TVar a

-- | Create a new TVar holding a value supplied
newTVar :: a -> STM (TVar a)

-- | <tt>IO</tt> version of <a>newTVar</a>. This is useful for creating
--   top-level <a>TVar</a>s using <a>unsafePerformIO</a>, because using
--   <a>atomically</a> inside <a>unsafePerformIO</a> isn't possible.
newTVarIO :: a -> IO (TVar a)

-- | Return the current value stored in a TVar
readTVar :: TVar a -> STM a

-- | Return the current value stored in a TVar. This is equivalent to
--   
--   <pre>
--   readTVarIO = atomically . readTVar
--   </pre>
--   
--   but works much faster, because it doesn't perform a complete
--   transaction, it just reads the current value of the <a>TVar</a>.
readTVarIO :: TVar a -> IO a

-- | Write the supplied value into a TVar
writeTVar :: TVar a -> a -> STM ()

-- | Unsafely performs IO in the STM monad. Beware: this is a highly
--   dangerous thing to do.
--   
--   <ul>
--   <li>The STM implementation will often run transactions multiple times,
--   so you need to be prepared for this if your IO has any side
--   effects.</li>
--   <li>The STM implementation will abort transactions that are known to
--   be invalid and need to be restarted. This may happen in the middle of
--   <a>unsafeIOToSTM</a>, so make sure you don't acquire any resources
--   that need releasing (exception handlers are ignored when aborting the
--   transaction). That includes doing any IO using Handles, for example.
--   Getting this wrong will probably lead to random deadlocks.</li>
--   <li>The transaction may have seen an inconsistent view of memory when
--   the IO runs. Invariants that you expect to be true throughout your
--   program may not be true inside a transaction, due to the way
--   transactions are implemented. Normally this wouldn't be visible to the
--   programmer, but using <a>unsafeIOToSTM</a> can expose it.</li>
--   </ul>
unsafeIOToSTM :: IO a -> STM a
withMVar :: MVar a -> (a -> IO b) -> IO b
type Signal = CInt
type HandlerFun = ForeignPtr Word8 -> IO ()
setHandler :: Signal -> Maybe (HandlerFun, Dynamic) -> IO (Maybe (HandlerFun, Dynamic))
runHandlers :: ForeignPtr Word8 -> Signal -> IO ()
ensureIOManagerIsRunning :: IO ()
setUncaughtExceptionHandler :: (SomeException -> IO ()) -> IO ()
getUncaughtExceptionHandler :: IO (SomeException -> IO ())
reportError :: SomeException -> IO ()
reportStackOverflow :: IO ()


-- | External API for GHC's Handle implementation
module GHC.IO.Handle

-- | Haskell defines operations to read and write characters from and to
--   files, represented by values of type <tt>Handle</tt>. Each value of
--   this type is a <i>handle</i>: a record used by the Haskell run-time
--   system to <i>manage</i> I/O with file system objects. A handle has at
--   least the following properties:
--   
--   <ul>
--   <li>whether it manages input or output or both;</li>
--   <li>whether it is <i>open</i>, <i>closed</i> or
--   <i>semi-closed</i>;</li>
--   <li>whether the object is seekable;</li>
--   <li>whether buffering is disabled, or enabled on a line or block
--   basis;</li>
--   <li>a buffer (whose length may be zero).</li>
--   </ul>
--   
--   Most handles will also have a current I/O position indicating where
--   the next input or output operation will occur. A handle is
--   <i>readable</i> if it manages only input or both input and output;
--   likewise, it is <i>writable</i> if it manages only output or both
--   input and output. A handle is <i>open</i> 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 <a>Show</a> and <a>Eq</a> 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 <a>==</a> only to itself; no attempt is
--   made to compare the internal state of different handles for equality.
data Handle

-- | Three kinds of buffering are supported: line-buffering,
--   block-buffering or no-buffering. These modes have the following
--   effects. For output, items are written out, or <i>flushed</i>, from
--   the internal buffer according to the buffer mode:
--   
--   <ul>
--   <li><i>line-buffering</i>: the entire output buffer is flushed
--   whenever a newline is output, the buffer overflows, a <a>hFlush</a> is
--   issued, or the handle is closed.</li>
--   <li><i>block-buffering</i>: the entire buffer is written out whenever
--   it overflows, a <a>hFlush</a> is issued, or the handle is closed.</li>
--   <li><i>no-buffering</i>: output is written immediately, and never
--   stored in the buffer.</li>
--   </ul>
--   
--   An implementation is free to flush the buffer more frequently, but not
--   less frequently, than specified above. The output buffer is emptied as
--   soon as it has been written out.
--   
--   Similarly, input occurs according to the buffer mode for the handle:
--   
--   <ul>
--   <li><i>line-buffering</i>: when the buffer for the handle is not
--   empty, the next item is obtained from the buffer; otherwise, when the
--   buffer is empty, characters up to and including the next newline
--   character are read into the buffer. No characters are available until
--   the newline character is available or the buffer is full.</li>
--   <li><i>block-buffering</i>: when the buffer for the handle becomes
--   empty, the next block of data is read into the buffer.</li>
--   <li><i>no-buffering</i>: the next input item is read and returned. The
--   <a>hLookAhead</a> operation implies that even a no-buffered handle may
--   require a one-character buffer.</li>
--   </ul>
--   
--   The default buffering mode when a handle is opened is
--   implementation-dependent and may depend on the file system object
--   which is attached to that handle. For most implementations, physical
--   files will normally be block-buffered and terminals will normally be
--   line-buffered.
data BufferMode

-- | buffering is disabled if possible.
NoBuffering :: BufferMode

-- | line-buffering should be enabled if possible.
LineBuffering :: BufferMode

-- | block-buffering should be enabled if possible. The size of the buffer
--   is <tt>n</tt> items if the argument is <a>Just</a> <tt>n</tt> and is
--   otherwise implementation-dependent.
BlockBuffering :: (Maybe Int) -> BufferMode

-- | makes a new <a>Handle</a>
mkFileHandle :: (IODevice dev, BufferedIO dev, Typeable dev) => dev -> FilePath -> IOMode -> Maybe TextEncoding -> NewlineMode -> IO Handle

-- | like <a>mkFileHandle</a>, except that a <a>Handle</a> is created with
--   two independent buffers, one for reading and one for writing. Used for
--   full-duplex streams, such as network sockets.
mkDuplexHandle :: (IODevice dev, BufferedIO dev, Typeable dev) => dev -> FilePath -> Maybe TextEncoding -> NewlineMode -> IO Handle

-- | For a handle <tt>hdl</tt> which attached to a physical file,
--   <a>hFileSize</a> <tt>hdl</tt> returns the size of that file in 8-bit
--   bytes.
hFileSize :: Handle -> IO Integer

-- | <a>hSetFileSize</a> <tt>hdl</tt> <tt>size</tt> truncates the physical
--   file with handle <tt>hdl</tt> to <tt>size</tt> bytes.
hSetFileSize :: Handle -> Integer -> IO ()

-- | For a readable handle <tt>hdl</tt>, <a>hIsEOF</a> <tt>hdl</tt> returns
--   <a>True</a> if no further input can be taken from <tt>hdl</tt> or for
--   a physical file, if the current I/O position is equal to the length of
--   the file. Otherwise, it returns <a>False</a>.
--   
--   NOTE: <a>hIsEOF</a> may block, because it has to attempt to read from
--   the stream to determine whether there is any more data to be read.
hIsEOF :: Handle -> IO Bool

-- | Computation <a>hLookAhead</a> returns the next character from the
--   handle without removing it from the input buffer, blocking until a
--   character is available.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><tt>isEOFError</tt> if the end of file has been reached.</li>
--   </ul>
hLookAhead :: Handle -> IO Char

-- | Computation <a>hSetBuffering</a> <tt>hdl mode</tt> sets the mode of
--   buffering for handle <tt>hdl</tt> on subsequent reads and writes.
--   
--   If the buffer mode is changed from <a>BlockBuffering</a> or
--   <a>LineBuffering</a> to <a>NoBuffering</a>, then
--   
--   <ul>
--   <li>if <tt>hdl</tt> is writable, the buffer is flushed as for
--   <a>hFlush</a>;</li>
--   <li>if <tt>hdl</tt> is not writable, the contents of the buffer is
--   discarded.</li>
--   </ul>
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><tt>isPermissionError</tt> if the handle has already been used for
--   reading or writing and the implementation does not allow the buffering
--   mode to be changed.</li>
--   </ul>
hSetBuffering :: Handle -> BufferMode -> IO ()

-- | Select binary mode (<a>True</a>) or text mode (<a>False</a>) on a open
--   handle. (See also <tt>openBinaryFile</tt>.)
--   
--   This has the same effect as calling <a>hSetEncoding</a> with
--   <a>char8</a>, together with <a>hSetNewlineMode</a> with
--   <a>noNewlineTranslation</a>.
hSetBinaryMode :: Handle -> Bool -> IO ()

-- | The action <a>hSetEncoding</a> <tt>hdl</tt> <tt>encoding</tt> changes
--   the text encoding for the handle <tt>hdl</tt> to <tt>encoding</tt>.
--   The default encoding when a <a>Handle</a> is created is
--   <tt>localeEncoding</tt>, namely the default encoding for the current
--   locale.
--   
--   To create a <a>Handle</a> with no encoding at all, use
--   <tt>openBinaryFile</tt>. To stop further encoding or decoding on an
--   existing <a>Handle</a>, use <a>hSetBinaryMode</a>.
--   
--   <a>hSetEncoding</a> may need to flush buffered data in order to change
--   the encoding.
hSetEncoding :: Handle -> TextEncoding -> IO ()

-- | Return the current <a>TextEncoding</a> for the specified
--   <a>Handle</a>, or <a>Nothing</a> if the <a>Handle</a> is in binary
--   mode.
--   
--   Note that the <a>TextEncoding</a> remembers nothing about the state of
--   the encoder/decoder in use on this <a>Handle</a>. For example, if the
--   encoding in use is UTF-16, then using <a>hGetEncoding</a> and
--   <a>hSetEncoding</a> to save and restore the encoding may result in an
--   extra byte-order-mark being written to the file.
hGetEncoding :: Handle -> IO (Maybe TextEncoding)

-- | The action <a>hFlush</a> <tt>hdl</tt> causes any items buffered for
--   output in handle <tt>hdl</tt> to be sent immediately to the operating
--   system.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><tt>isFullError</tt> if the device is full;</li>
--   <li><tt>isPermissionError</tt> if a system resource limit would be
--   exceeded. It is unspecified whether the characters in the buffer are
--   discarded or retained under these circumstances.</li>
--   </ul>
hFlush :: Handle -> IO ()

-- | The action <a>hFlushAll</a> <tt>hdl</tt> flushes all buffered data in
--   <tt>hdl</tt>, including any buffered read data. Buffered read data is
--   flushed by seeking the file position back to the point before the
--   bufferred data was read, and hence only works if <tt>hdl</tt> is
--   seekable (see <a>hIsSeekable</a>).
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><tt>isFullError</tt> if the device is full;</li>
--   <li><tt>isPermissionError</tt> if a system resource limit would be
--   exceeded. It is unspecified whether the characters in the buffer are
--   discarded or retained under these circumstances;</li>
--   <li><tt>isIllegalOperation</tt> if <tt>hdl</tt> has buffered read
--   data, and is not seekable.</li>
--   </ul>
hFlushAll :: Handle -> IO ()

-- | Returns a duplicate of the original handle, with its own buffer. The
--   two Handles will share a file pointer, however. The original handle's
--   buffer is flushed, including discarding any input data, before the
--   handle is duplicated.
hDuplicate :: Handle -> IO Handle

-- | Makes the second handle a duplicate of the first handle. The second
--   handle will be closed first, if it is not already.
--   
--   This can be used to retarget the standard Handles, for example:
--   
--   <pre>
--   do h &lt;- openFile "mystdout" WriteMode
--      hDuplicateTo h stdout
--   </pre>
hDuplicateTo :: Handle -> Handle -> IO ()

-- | Computation <a>hClose</a> <tt>hdl</tt> makes handle <tt>hdl</tt>
--   closed. Before the computation finishes, if <tt>hdl</tt> is writable
--   its buffer is flushed as for <a>hFlush</a>. Performing <a>hClose</a>
--   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
--   <a>hClose</a> fails for any reason, any further operations (apart from
--   <a>hClose</a>) on the handle will still fail as if <tt>hdl</tt> had
--   been successfully closed.
hClose :: Handle -> IO ()
hClose_help :: Handle__ -> IO (Handle__, Maybe SomeException)
type HandlePosition = Integer
data HandlePosn
HandlePosn :: Handle -> HandlePosition -> HandlePosn

-- | Computation <a>hGetPosn</a> <tt>hdl</tt> returns the current I/O
--   position of <tt>hdl</tt> as a value of the abstract type
--   <a>HandlePosn</a>.
hGetPosn :: Handle -> IO HandlePosn

-- | If a call to <a>hGetPosn</a> <tt>hdl</tt> returns a position
--   <tt>p</tt>, then computation <a>hSetPosn</a> <tt>p</tt> sets the
--   position of <tt>hdl</tt> to the position it held at the time of the
--   call to <a>hGetPosn</a>.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><tt>isPermissionError</tt> if a system resource limit would be
--   exceeded.</li>
--   </ul>
hSetPosn :: HandlePosn -> IO ()

-- | A mode that determines the effect of <tt>hSeek</tt> <tt>hdl mode
--   i</tt>.
data SeekMode

-- | the position of <tt>hdl</tt> is set to <tt>i</tt>.
AbsoluteSeek :: SeekMode

-- | the position of <tt>hdl</tt> is set to offset <tt>i</tt> from the
--   current position.
RelativeSeek :: SeekMode

-- | the position of <tt>hdl</tt> is set to offset <tt>i</tt> from the end
--   of the file.
SeekFromEnd :: SeekMode

-- | Computation <a>hSeek</a> <tt>hdl mode i</tt> sets the position of
--   handle <tt>hdl</tt> depending on <tt>mode</tt>. The offset <tt>i</tt>
--   is given in terms of 8-bit bytes.
--   
--   If <tt>hdl</tt> is block- or line-buffered, then seeking to a position
--   which is not in the current buffer will first cause any items in the
--   output buffer to be written to the device, and then cause the input
--   buffer to be discarded. Some handles may not be seekable (see
--   <a>hIsSeekable</a>), or only support a subset of the possible
--   positioning operations (for instance, it may only be possible to seek
--   to the end of a tape, or to a positive offset from the beginning or
--   current position). It is not possible to set a negative I/O position,
--   or for a physical file, an I/O position beyond the current
--   end-of-file.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><tt>isIllegalOperationError</tt> if the Handle is not seekable, or
--   does not support the requested seek mode.</li>
--   <li><tt>isPermissionError</tt> if a system resource limit would be
--   exceeded.</li>
--   </ul>
hSeek :: Handle -> SeekMode -> Integer -> IO ()

-- | Computation <a>hTell</a> <tt>hdl</tt> returns the current position of
--   the handle <tt>hdl</tt>, as the number of bytes from the beginning of
--   the file. The value returned may be subsequently passed to
--   <a>hSeek</a> to reposition the handle to the current position.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><tt>isIllegalOperationError</tt> if the Handle is not
--   seekable.</li>
--   </ul>
hTell :: Handle -> IO Integer
hIsOpen :: Handle -> IO Bool
hIsClosed :: Handle -> IO Bool
hIsReadable :: Handle -> IO Bool
hIsWritable :: Handle -> IO Bool

-- | Computation <a>hGetBuffering</a> <tt>hdl</tt> returns the current
--   buffering mode for <tt>hdl</tt>.
hGetBuffering :: Handle -> IO BufferMode
hIsSeekable :: Handle -> IO Bool

-- | Set the echoing status of a handle connected to a terminal.
hSetEcho :: Handle -> Bool -> IO ()

-- | Get the echoing status of a handle connected to a terminal.
hGetEcho :: Handle -> IO Bool

-- | Is the handle connected to a terminal?
hIsTerminalDevice :: Handle -> IO Bool

-- | Set the <a>NewlineMode</a> on the specified <a>Handle</a>. All
--   buffered data is flushed first.
hSetNewlineMode :: Handle -> NewlineMode -> IO ()

-- | The representation of a newline in the external file or stream.
data Newline

-- | '\n'
LF :: Newline

-- | '\r\n'
CRLF :: Newline

-- | Specifies the translation, if any, of newline characters between
--   internal Strings and the external file or stream. Haskell Strings are
--   assumed to represent newlines with the '\n' character; the newline
--   mode specifies how to translate '\n' on output, and what to translate
--   into '\n' on input.
data NewlineMode
NewlineMode :: Newline -> Newline -> NewlineMode

-- | the representation of newlines on input
inputNL :: NewlineMode -> Newline

-- | the representation of newlines on output
outputNL :: NewlineMode -> Newline

-- | The native newline representation for the current platform: <a>LF</a>
--   on Unix systems, <a>CRLF</a> on Windows.
nativeNewline :: Newline

-- | Do no newline translation at all.
--   
--   <pre>
--   noNewlineTranslation  = NewlineMode { inputNL  = LF, outputNL = LF }
--   </pre>
noNewlineTranslation :: NewlineMode

-- | Map '\r\n' into '\n' on input, and '\n' to the native newline
--   represetnation on output. This mode can be used on any platform, and
--   works with text files using any newline convention. The downside is
--   that <tt>readFile &gt;&gt;= writeFile</tt> might yield a different
--   file.
--   
--   <pre>
--   universalNewlineMode  = NewlineMode { inputNL  = CRLF, 
--                                         outputNL = nativeNewline }
--   </pre>
universalNewlineMode :: NewlineMode

-- | Use the native newline representation on both input and output
--   
--   <pre>
--   nativeNewlineMode  = NewlineMode { inputNL  = nativeNewline
--                                      outputNL = nativeNewline }
--   </pre>
nativeNewlineMode :: NewlineMode

-- | <a>hShow</a> is in the <a>IO</a> monad, and gives more comprehensive
--   output than the (pure) instance of <a>Show</a> for <a>Handle</a>.
hShow :: Handle -> IO String

-- | Computation <a>hWaitForInput</a> <tt>hdl t</tt> waits until input is
--   available on handle <tt>hdl</tt>. It returns <a>True</a> as soon as
--   input is available on <tt>hdl</tt>, or <a>False</a> if no input is
--   available within <tt>t</tt> milliseconds. Note that
--   <a>hWaitForInput</a> waits until one or more full <i>characters</i>
--   are available, which means that it needs to do decoding, and hence may
--   fail with a decoding error.
--   
--   If <tt>t</tt> is less than zero, then <tt>hWaitForInput</tt> waits
--   indefinitely.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><a>isEOFError</a> if the end of file has been reached.</li>
--   <li>a decoding error, if the input begins with an invalid byte
--   sequence in this Handle's encoding.</li>
--   </ul>
--   
--   NOTE for GHC users: unless you use the <tt>-threaded</tt> flag,
--   <tt>hWaitForInput t</tt> where <tt>t &gt;= 0</tt> will block all other
--   Haskell threads for the duration of the call. It behaves like a
--   <tt>safe</tt> foreign call in this respect.
hWaitForInput :: Handle -> Int -> IO Bool

-- | Computation <a>hGetChar</a> <tt>hdl</tt> reads a character from the
--   file or channel managed by <tt>hdl</tt>, blocking until a character is
--   available.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><a>isEOFError</a> if the end of file has been reached.</li>
--   </ul>
hGetChar :: Handle -> IO Char

-- | Computation <a>hGetLine</a> <tt>hdl</tt> reads a line from the file or
--   channel managed by <tt>hdl</tt>.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><a>isEOFError</a> if the end of file is encountered when reading
--   the <i>first</i> character of the line.</li>
--   </ul>
--   
--   If <a>hGetLine</a> encounters end-of-file at any other point while
--   reading in a line, it is treated as a line terminator and the
--   (partial) line is returned.
hGetLine :: Handle -> IO String

-- | Computation <a>hGetContents</a> <tt>hdl</tt> returns the list of
--   characters corresponding to the unread portion of the channel or file
--   managed by <tt>hdl</tt>, which is put into an intermediate state,
--   <i>semi-closed</i>. In this state, <tt>hdl</tt> is effectively closed,
--   but items are read from <tt>hdl</tt> on demand and accumulated in a
--   special list returned by <a>hGetContents</a> <tt>hdl</tt>.
--   
--   Any operation that fails because a handle is closed, also fails if a
--   handle is semi-closed. The only exception is <tt>hClose</tt>. A
--   semi-closed handle becomes closed:
--   
--   <ul>
--   <li>if <tt>hClose</tt> is applied to it;</li>
--   <li>if an I/O error occurs when reading an item from the handle;</li>
--   <li>or once the entire contents of the handle has been read.</li>
--   </ul>
--   
--   Once a semi-closed handle becomes closed, the contents of the
--   associated list becomes fixed. The contents of this final list is only
--   partially specified: it will contain at least all the items of the
--   stream that were evaluated prior to the handle becoming closed.
--   
--   Any I/O errors encountered while a handle is semi-closed are simply
--   discarded.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><a>isEOFError</a> if the end of file has been reached.</li>
--   </ul>
hGetContents :: Handle -> IO String

-- | Computation <a>hPutChar</a> <tt>hdl ch</tt> writes the character
--   <tt>ch</tt> to the file or channel managed by <tt>hdl</tt>. Characters
--   may be buffered if buffering is enabled for <tt>hdl</tt>.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><a>isFullError</a> if the device is full; or</li>
--   <li><a>isPermissionError</a> if another system resource limit would be
--   exceeded.</li>
--   </ul>
hPutChar :: Handle -> Char -> IO ()

-- | Computation <a>hPutStr</a> <tt>hdl s</tt> writes the string <tt>s</tt>
--   to the file or channel managed by <tt>hdl</tt>.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><a>isFullError</a> if the device is full; or</li>
--   <li><a>isPermissionError</a> if another system resource limit would be
--   exceeded.</li>
--   </ul>
hPutStr :: Handle -> String -> IO ()

-- | <a>hGetBuf</a> <tt>hdl buf count</tt> reads data from the handle
--   <tt>hdl</tt> into the buffer <tt>buf</tt> until either EOF is reached
--   or <tt>count</tt> 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 <tt>count</tt> is zero).
--   
--   <a>hGetBuf</a> never raises an EOF exception, instead it returns a
--   value smaller than <tt>count</tt>.
--   
--   If the handle is a pipe or socket, and the writing end is closed,
--   <a>hGetBuf</a> will behave as if EOF was reached.
--   
--   <a>hGetBuf</a> ignores the prevailing <tt>TextEncoding</tt> and
--   <a>NewlineMode</a> on the <a>Handle</a>, and reads bytes directly.
hGetBuf :: Handle -> Ptr a -> Int -> IO Int

-- | <a>hGetBufNonBlocking</a> <tt>hdl buf count</tt> reads data from the
--   handle <tt>hdl</tt> into the buffer <tt>buf</tt> until either EOF is
--   reached, or <tt>count</tt> 8-bit bytes have been read, or there is no
--   more data available to read immediately.
--   
--   <a>hGetBufNonBlocking</a> is identical to <a>hGetBuf</a>, except that
--   it will never block waiting for data to become available, instead it
--   returns only whatever data is available. To wait for data to arrive
--   before calling <a>hGetBufNonBlocking</a>, use <a>hWaitForInput</a>.
--   
--   If the handle is a pipe or socket, and the writing end is closed,
--   <a>hGetBufNonBlocking</a> will behave as if EOF was reached.
--   
--   <a>hGetBufNonBlocking</a> ignores the prevailing <tt>TextEncoding</tt>
--   and <a>NewlineMode</a> on the <a>Handle</a>, and reads bytes directly.
--   
--   NOTE: on Windows, this function does not work correctly; it behaves
--   identically to <a>hGetBuf</a>.
hGetBufNonBlocking :: Handle -> Ptr a -> Int -> IO Int

-- | <a>hPutBuf</a> <tt>hdl buf count</tt> writes <tt>count</tt> 8-bit
--   bytes from the buffer <tt>buf</tt> to the handle <tt>hdl</tt>. It
--   returns ().
--   
--   <a>hPutBuf</a> ignores any text encoding that applies to the
--   <a>Handle</a>, writing the bytes directly to the underlying file or
--   device.
--   
--   <a>hPutBuf</a> ignores the prevailing <tt>TextEncoding</tt> and
--   <a>NewlineMode</a> on the <a>Handle</a>, and writes bytes directly.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><a>ResourceVanished</a> 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).</li>
--   </ul>
hPutBuf :: Handle -> Ptr a -> Int -> IO ()
hPutBufNonBlocking :: Handle -> Ptr a -> Int -> IO Int
instance Show HandlePosn
instance Eq HandlePosn


-- | Handle operations implemented by file descriptors (FDs)
module GHC.IO.Handle.FD

-- | A handle managing input from the Haskell program's standard input
--   channel.
stdin :: Handle

-- | A handle managing output to the Haskell program's standard output
--   channel.
stdout :: Handle

-- | A handle managing output to the Haskell program's standard error
--   channel.
stderr :: Handle

-- | Computation <a>openFile</a> <tt>file mode</tt> allocates and returns a
--   new, open handle to manage the file <tt>file</tt>. It manages input if
--   <tt>mode</tt> is <a>ReadMode</a>, output if <tt>mode</tt> is
--   <a>WriteMode</a> or <a>AppendMode</a>, and both input and output if
--   mode is <a>ReadWriteMode</a>.
--   
--   If the file does not exist and it is opened for output, it should be
--   created as a new file. If <tt>mode</tt> is <a>WriteMode</a> and the
--   file already exists, then it should be truncated to zero length. Some
--   operating systems delete empty files, so there is no guarantee that
--   the file will exist following an <a>openFile</a> with <tt>mode</tt>
--   <a>WriteMode</a> unless it is subsequently written to successfully.
--   The handle is positioned at the end of the file if <tt>mode</tt> is
--   <a>AppendMode</a>, and otherwise at the beginning (in which case its
--   internal position is 0). The initial buffer mode is
--   implementation-dependent.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><tt>isAlreadyInUseError</tt> if the file is already open and
--   cannot be reopened;</li>
--   <li><tt>isDoesNotExistError</tt> if the file does not exist; or</li>
--   <li><tt>isPermissionError</tt> if the user does not have permission to
--   open the file.</li>
--   </ul>
--   
--   Note: if you will be working with files containing binary data, you'll
--   want to be using <a>openBinaryFile</a>.
openFile :: FilePath -> IOMode -> IO Handle

-- | Like <a>openFile</a>, but open the file in binary mode. On Windows,
--   reading a file in text mode (which is the default) will translate CRLF
--   to LF, and writing will translate LF to CRLF. This is usually what you
--   want with text files. With binary files this is undesirable; also, as
--   usual under Microsoft operating systems, text mode treats control-Z as
--   EOF. Binary mode turns off all special treatment of end-of-line and
--   end-of-file characters. (See also <a>hSetBinaryMode</a>.)
openBinaryFile :: FilePath -> IOMode -> IO Handle

-- | Like <a>openFile</a>, but opens the file in ordinary blocking mode.
--   This can be useful for opening a FIFO for reading: if we open in
--   non-blocking mode then the open will fail if there are no writers,
--   whereas a blocking open will block until a writer appears.
openFileBlocking :: FilePath -> IOMode -> IO Handle
mkHandleFromFD :: FD -> IODeviceType -> FilePath -> IOMode -> Bool -> Maybe TextEncoding -> IO Handle

-- | Turn an existing file descriptor into a Handle. This is used by
--   various external libraries to make Handles.
--   
--   Makes a binary Handle. This is for historical reasons; it should
--   probably be a text Handle with the default encoding and newline
--   translation instead.
fdToHandle :: FD -> IO Handle

-- | Old API kept to avoid breaking clients
fdToHandle' :: CInt -> Maybe IODeviceType -> Bool -> FilePath -> IOMode -> Bool -> IO Handle

-- | The computation <a>isEOF</a> is identical to <a>hIsEOF</a>, except
--   that it works only on <a>stdin</a>.
isEOF :: IO Bool


-- | The standard IO library.
module System.IO

-- | A value of type <tt><a>IO</a> a</tt> is a computation which, when
--   performed, does some I/O before returning a value of type <tt>a</tt>.
--   
--   There is really only one way to "perform" an I/O action: bind it to
--   <tt>Main.main</tt> in your program. When your program is run, the I/O
--   will be performed. It isn't possible to perform I/O from an arbitrary
--   function, unless that function is itself in the <a>IO</a> monad and
--   called at some point, directly or indirectly, from <tt>Main.main</tt>.
--   
--   <a>IO</a> is a monad, so <a>IO</a> actions can be combined using
--   either the do-notation or the <tt>&gt;&gt;</tt> and <tt>&gt;&gt;=</tt>
--   operations from the <tt>Monad</tt> class.
data IO a :: * -> *
fixIO :: (a -> IO a) -> IO a

-- | File and directory names are values of type <a>String</a>, whose
--   precise meaning is operating system dependent. Files can be opened,
--   yielding a handle which can then be used to operate on the contents of
--   that file.
type FilePath = String

-- | Haskell defines operations to read and write characters from and to
--   files, represented by values of type <tt>Handle</tt>. Each value of
--   this type is a <i>handle</i>: a record used by the Haskell run-time
--   system to <i>manage</i> I/O with file system objects. A handle has at
--   least the following properties:
--   
--   <ul>
--   <li>whether it manages input or output or both;</li>
--   <li>whether it is <i>open</i>, <i>closed</i> or
--   <i>semi-closed</i>;</li>
--   <li>whether the object is seekable;</li>
--   <li>whether buffering is disabled, or enabled on a line or block
--   basis;</li>
--   <li>a buffer (whose length may be zero).</li>
--   </ul>
--   
--   Most handles will also have a current I/O position indicating where
--   the next input or output operation will occur. A handle is
--   <i>readable</i> if it manages only input or both input and output;
--   likewise, it is <i>writable</i> if it manages only output or both
--   input and output. A handle is <i>open</i> 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 <a>Show</a> and <a>Eq</a> 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 <a>==</a> only to itself; no attempt is
--   made to compare the internal state of different handles for equality.
data Handle

-- | A handle managing input from the Haskell program's standard input
--   channel.
stdin :: Handle

-- | A handle managing output to the Haskell program's standard output
--   channel.
stdout :: Handle

-- | A handle managing output to the Haskell program's standard error
--   channel.
stderr :: Handle

-- | <tt><a>withFile</a> name mode act</tt> opens a file using
--   <a>openFile</a> and passes the resulting handle to the computation
--   <tt>act</tt>. The handle will be closed on exit from <a>withFile</a>,
--   whether by normal termination or by raising an exception. If closing
--   the handle raises an exception, then this exception will be raised by
--   <a>withFile</a> rather than any exception raised by <tt>act</tt>.
withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r

-- | Computation <a>openFile</a> <tt>file mode</tt> allocates and returns a
--   new, open handle to manage the file <tt>file</tt>. It manages input if
--   <tt>mode</tt> is <a>ReadMode</a>, output if <tt>mode</tt> is
--   <a>WriteMode</a> or <a>AppendMode</a>, and both input and output if
--   mode is <a>ReadWriteMode</a>.
--   
--   If the file does not exist and it is opened for output, it should be
--   created as a new file. If <tt>mode</tt> is <a>WriteMode</a> and the
--   file already exists, then it should be truncated to zero length. Some
--   operating systems delete empty files, so there is no guarantee that
--   the file will exist following an <a>openFile</a> with <tt>mode</tt>
--   <a>WriteMode</a> unless it is subsequently written to successfully.
--   The handle is positioned at the end of the file if <tt>mode</tt> is
--   <a>AppendMode</a>, and otherwise at the beginning (in which case its
--   internal position is 0). The initial buffer mode is
--   implementation-dependent.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><tt>isAlreadyInUseError</tt> if the file is already open and
--   cannot be reopened;</li>
--   <li><tt>isDoesNotExistError</tt> if the file does not exist; or</li>
--   <li><tt>isPermissionError</tt> if the user does not have permission to
--   open the file.</li>
--   </ul>
--   
--   Note: if you will be working with files containing binary data, you'll
--   want to be using <a>openBinaryFile</a>.
openFile :: FilePath -> IOMode -> IO Handle

-- | See <a>openFile</a>
data IOMode
ReadMode :: IOMode
WriteMode :: IOMode
AppendMode :: IOMode
ReadWriteMode :: IOMode

-- | Computation <a>hClose</a> <tt>hdl</tt> makes handle <tt>hdl</tt>
--   closed. Before the computation finishes, if <tt>hdl</tt> is writable
--   its buffer is flushed as for <a>hFlush</a>. Performing <a>hClose</a>
--   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
--   <a>hClose</a> fails for any reason, any further operations (apart from
--   <a>hClose</a>) on the handle will still fail as if <tt>hdl</tt> had
--   been successfully closed.
hClose :: Handle -> IO ()

-- | The <a>readFile</a> function reads a file and returns the contents of
--   the file as a string. The file is read lazily, on demand, as with
--   <a>getContents</a>.
readFile :: FilePath -> IO String

-- | The computation <a>writeFile</a> <tt>file str</tt> function writes the
--   string <tt>str</tt>, to the file <tt>file</tt>.
writeFile :: FilePath -> String -> IO ()

-- | The computation <a>appendFile</a> <tt>file str</tt> function appends
--   the string <tt>str</tt>, to the file <tt>file</tt>.
--   
--   Note that <a>writeFile</a> and <a>appendFile</a> write a literal
--   string to a file. To write a value of any printable type, as with
--   <a>print</a>, use the <a>show</a> function to convert the value to a
--   string first.
--   
--   <pre>
--   main = appendFile "squares" (show [(x,x*x) | x &lt;- [0,0.1..2]])
--   </pre>
appendFile :: FilePath -> String -> IO ()

-- | For a handle <tt>hdl</tt> which attached to a physical file,
--   <a>hFileSize</a> <tt>hdl</tt> returns the size of that file in 8-bit
--   bytes.
hFileSize :: Handle -> IO Integer

-- | <a>hSetFileSize</a> <tt>hdl</tt> <tt>size</tt> truncates the physical
--   file with handle <tt>hdl</tt> to <tt>size</tt> bytes.
hSetFileSize :: Handle -> Integer -> IO ()

-- | For a readable handle <tt>hdl</tt>, <a>hIsEOF</a> <tt>hdl</tt> returns
--   <a>True</a> if no further input can be taken from <tt>hdl</tt> or for
--   a physical file, if the current I/O position is equal to the length of
--   the file. Otherwise, it returns <a>False</a>.
--   
--   NOTE: <a>hIsEOF</a> may block, because it has to attempt to read from
--   the stream to determine whether there is any more data to be read.
hIsEOF :: Handle -> IO Bool

-- | The computation <a>isEOF</a> is identical to <a>hIsEOF</a>, except
--   that it works only on <a>stdin</a>.
isEOF :: IO Bool

-- | Three kinds of buffering are supported: line-buffering,
--   block-buffering or no-buffering. These modes have the following
--   effects. For output, items are written out, or <i>flushed</i>, from
--   the internal buffer according to the buffer mode:
--   
--   <ul>
--   <li><i>line-buffering</i>: the entire output buffer is flushed
--   whenever a newline is output, the buffer overflows, a <a>hFlush</a> is
--   issued, or the handle is closed.</li>
--   <li><i>block-buffering</i>: the entire buffer is written out whenever
--   it overflows, a <a>hFlush</a> is issued, or the handle is closed.</li>
--   <li><i>no-buffering</i>: output is written immediately, and never
--   stored in the buffer.</li>
--   </ul>
--   
--   An implementation is free to flush the buffer more frequently, but not
--   less frequently, than specified above. The output buffer is emptied as
--   soon as it has been written out.
--   
--   Similarly, input occurs according to the buffer mode for the handle:
--   
--   <ul>
--   <li><i>line-buffering</i>: when the buffer for the handle is not
--   empty, the next item is obtained from the buffer; otherwise, when the
--   buffer is empty, characters up to and including the next newline
--   character are read into the buffer. No characters are available until
--   the newline character is available or the buffer is full.</li>
--   <li><i>block-buffering</i>: when the buffer for the handle becomes
--   empty, the next block of data is read into the buffer.</li>
--   <li><i>no-buffering</i>: the next input item is read and returned. The
--   <a>hLookAhead</a> operation implies that even a no-buffered handle may
--   require a one-character buffer.</li>
--   </ul>
--   
--   The default buffering mode when a handle is opened is
--   implementation-dependent and may depend on the file system object
--   which is attached to that handle. For most implementations, physical
--   files will normally be block-buffered and terminals will normally be
--   line-buffered.
data BufferMode

-- | buffering is disabled if possible.
NoBuffering :: BufferMode

-- | line-buffering should be enabled if possible.
LineBuffering :: BufferMode

-- | block-buffering should be enabled if possible. The size of the buffer
--   is <tt>n</tt> items if the argument is <a>Just</a> <tt>n</tt> and is
--   otherwise implementation-dependent.
BlockBuffering :: (Maybe Int) -> BufferMode

-- | Computation <a>hSetBuffering</a> <tt>hdl mode</tt> sets the mode of
--   buffering for handle <tt>hdl</tt> on subsequent reads and writes.
--   
--   If the buffer mode is changed from <a>BlockBuffering</a> or
--   <a>LineBuffering</a> to <a>NoBuffering</a>, then
--   
--   <ul>
--   <li>if <tt>hdl</tt> is writable, the buffer is flushed as for
--   <a>hFlush</a>;</li>
--   <li>if <tt>hdl</tt> is not writable, the contents of the buffer is
--   discarded.</li>
--   </ul>
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><tt>isPermissionError</tt> if the handle has already been used for
--   reading or writing and the implementation does not allow the buffering
--   mode to be changed.</li>
--   </ul>
hSetBuffering :: Handle -> BufferMode -> IO ()

-- | Computation <a>hGetBuffering</a> <tt>hdl</tt> returns the current
--   buffering mode for <tt>hdl</tt>.
hGetBuffering :: Handle -> IO BufferMode

-- | The action <a>hFlush</a> <tt>hdl</tt> causes any items buffered for
--   output in handle <tt>hdl</tt> to be sent immediately to the operating
--   system.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><tt>isFullError</tt> if the device is full;</li>
--   <li><tt>isPermissionError</tt> if a system resource limit would be
--   exceeded. It is unspecified whether the characters in the buffer are
--   discarded or retained under these circumstances.</li>
--   </ul>
hFlush :: Handle -> IO ()

-- | Computation <a>hGetPosn</a> <tt>hdl</tt> returns the current I/O
--   position of <tt>hdl</tt> as a value of the abstract type
--   <a>HandlePosn</a>.
hGetPosn :: Handle -> IO HandlePosn

-- | If a call to <a>hGetPosn</a> <tt>hdl</tt> returns a position
--   <tt>p</tt>, then computation <a>hSetPosn</a> <tt>p</tt> sets the
--   position of <tt>hdl</tt> to the position it held at the time of the
--   call to <a>hGetPosn</a>.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><tt>isPermissionError</tt> if a system resource limit would be
--   exceeded.</li>
--   </ul>
hSetPosn :: HandlePosn -> IO ()
data HandlePosn

-- | Computation <a>hSeek</a> <tt>hdl mode i</tt> sets the position of
--   handle <tt>hdl</tt> depending on <tt>mode</tt>. The offset <tt>i</tt>
--   is given in terms of 8-bit bytes.
--   
--   If <tt>hdl</tt> is block- or line-buffered, then seeking to a position
--   which is not in the current buffer will first cause any items in the
--   output buffer to be written to the device, and then cause the input
--   buffer to be discarded. Some handles may not be seekable (see
--   <a>hIsSeekable</a>), or only support a subset of the possible
--   positioning operations (for instance, it may only be possible to seek
--   to the end of a tape, or to a positive offset from the beginning or
--   current position). It is not possible to set a negative I/O position,
--   or for a physical file, an I/O position beyond the current
--   end-of-file.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><tt>isIllegalOperationError</tt> if the Handle is not seekable, or
--   does not support the requested seek mode.</li>
--   <li><tt>isPermissionError</tt> if a system resource limit would be
--   exceeded.</li>
--   </ul>
hSeek :: Handle -> SeekMode -> Integer -> IO ()

-- | A mode that determines the effect of <tt>hSeek</tt> <tt>hdl mode
--   i</tt>.
data SeekMode

-- | the position of <tt>hdl</tt> is set to <tt>i</tt>.
AbsoluteSeek :: SeekMode

-- | the position of <tt>hdl</tt> is set to offset <tt>i</tt> from the
--   current position.
RelativeSeek :: SeekMode

-- | the position of <tt>hdl</tt> is set to offset <tt>i</tt> from the end
--   of the file.
SeekFromEnd :: SeekMode

-- | Computation <a>hTell</a> <tt>hdl</tt> returns the current position of
--   the handle <tt>hdl</tt>, as the number of bytes from the beginning of
--   the file. The value returned may be subsequently passed to
--   <a>hSeek</a> to reposition the handle to the current position.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><tt>isIllegalOperationError</tt> if the Handle is not
--   seekable.</li>
--   </ul>
hTell :: Handle -> IO Integer
hIsOpen :: Handle -> IO Bool
hIsClosed :: Handle -> IO Bool
hIsReadable :: Handle -> IO Bool
hIsWritable :: Handle -> IO Bool
hIsSeekable :: Handle -> IO Bool

-- | Is the handle connected to a terminal?
hIsTerminalDevice :: Handle -> IO Bool

-- | Set the echoing status of a handle connected to a terminal.
hSetEcho :: Handle -> Bool -> IO ()

-- | Get the echoing status of a handle connected to a terminal.
hGetEcho :: Handle -> IO Bool

-- | <a>hShow</a> is in the <a>IO</a> monad, and gives more comprehensive
--   output than the (pure) instance of <a>Show</a> for <a>Handle</a>.
hShow :: Handle -> IO String

-- | Computation <a>hWaitForInput</a> <tt>hdl t</tt> waits until input is
--   available on handle <tt>hdl</tt>. It returns <a>True</a> as soon as
--   input is available on <tt>hdl</tt>, or <a>False</a> if no input is
--   available within <tt>t</tt> milliseconds. Note that
--   <a>hWaitForInput</a> waits until one or more full <i>characters</i>
--   are available, which means that it needs to do decoding, and hence may
--   fail with a decoding error.
--   
--   If <tt>t</tt> is less than zero, then <tt>hWaitForInput</tt> waits
--   indefinitely.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><a>isEOFError</a> if the end of file has been reached.</li>
--   <li>a decoding error, if the input begins with an invalid byte
--   sequence in this Handle's encoding.</li>
--   </ul>
--   
--   NOTE for GHC users: unless you use the <tt>-threaded</tt> flag,
--   <tt>hWaitForInput t</tt> where <tt>t &gt;= 0</tt> will block all other
--   Haskell threads for the duration of the call. It behaves like a
--   <tt>safe</tt> foreign call in this respect.
hWaitForInput :: Handle -> Int -> IO Bool

-- | Computation <a>hReady</a> <tt>hdl</tt> indicates whether at least one
--   item is available for input from handle <tt>hdl</tt>.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><a>isEOFError</a> if the end of file has been reached.</li>
--   </ul>
hReady :: Handle -> IO Bool

-- | Computation <a>hGetChar</a> <tt>hdl</tt> reads a character from the
--   file or channel managed by <tt>hdl</tt>, blocking until a character is
--   available.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><a>isEOFError</a> if the end of file has been reached.</li>
--   </ul>
hGetChar :: Handle -> IO Char

-- | Computation <a>hGetLine</a> <tt>hdl</tt> reads a line from the file or
--   channel managed by <tt>hdl</tt>.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><a>isEOFError</a> if the end of file is encountered when reading
--   the <i>first</i> character of the line.</li>
--   </ul>
--   
--   If <a>hGetLine</a> encounters end-of-file at any other point while
--   reading in a line, it is treated as a line terminator and the
--   (partial) line is returned.
hGetLine :: Handle -> IO String

-- | Computation <a>hLookAhead</a> returns the next character from the
--   handle without removing it from the input buffer, blocking until a
--   character is available.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><tt>isEOFError</tt> if the end of file has been reached.</li>
--   </ul>
hLookAhead :: Handle -> IO Char

-- | Computation <a>hGetContents</a> <tt>hdl</tt> returns the list of
--   characters corresponding to the unread portion of the channel or file
--   managed by <tt>hdl</tt>, which is put into an intermediate state,
--   <i>semi-closed</i>. In this state, <tt>hdl</tt> is effectively closed,
--   but items are read from <tt>hdl</tt> on demand and accumulated in a
--   special list returned by <a>hGetContents</a> <tt>hdl</tt>.
--   
--   Any operation that fails because a handle is closed, also fails if a
--   handle is semi-closed. The only exception is <tt>hClose</tt>. A
--   semi-closed handle becomes closed:
--   
--   <ul>
--   <li>if <tt>hClose</tt> is applied to it;</li>
--   <li>if an I/O error occurs when reading an item from the handle;</li>
--   <li>or once the entire contents of the handle has been read.</li>
--   </ul>
--   
--   Once a semi-closed handle becomes closed, the contents of the
--   associated list becomes fixed. The contents of this final list is only
--   partially specified: it will contain at least all the items of the
--   stream that were evaluated prior to the handle becoming closed.
--   
--   Any I/O errors encountered while a handle is semi-closed are simply
--   discarded.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><a>isEOFError</a> if the end of file has been reached.</li>
--   </ul>
hGetContents :: Handle -> IO String

-- | Computation <a>hPutChar</a> <tt>hdl ch</tt> writes the character
--   <tt>ch</tt> to the file or channel managed by <tt>hdl</tt>. Characters
--   may be buffered if buffering is enabled for <tt>hdl</tt>.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><a>isFullError</a> if the device is full; or</li>
--   <li><a>isPermissionError</a> if another system resource limit would be
--   exceeded.</li>
--   </ul>
hPutChar :: Handle -> Char -> IO ()

-- | Computation <a>hPutStr</a> <tt>hdl s</tt> writes the string <tt>s</tt>
--   to the file or channel managed by <tt>hdl</tt>.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><a>isFullError</a> if the device is full; or</li>
--   <li><a>isPermissionError</a> if another system resource limit would be
--   exceeded.</li>
--   </ul>
hPutStr :: Handle -> String -> IO ()

-- | The same as <a>hPutStr</a>, but adds a newline character.
hPutStrLn :: Handle -> String -> IO ()

-- | Computation <a>hPrint</a> <tt>hdl t</tt> writes the string
--   representation of <tt>t</tt> given by the <a>shows</a> function to the
--   file or channel managed by <tt>hdl</tt> and appends a newline.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><a>isFullError</a> if the device is full; or</li>
--   <li><a>isPermissionError</a> if another system resource limit would be
--   exceeded.</li>
--   </ul>
hPrint :: Show a => Handle -> a -> IO ()

-- | The <a>interact</a> function takes a function of type
--   <tt>String-&gt;String</tt> as its argument. The entire input from the
--   standard input device is passed to this function as its argument, and
--   the resulting string is output on the standard output device.
interact :: (String -> String) -> IO ()

-- | Write a character to the standard output device (same as
--   <a>hPutChar</a> <a>stdout</a>).
putChar :: Char -> IO ()

-- | Write a string to the standard output device (same as <a>hPutStr</a>
--   <a>stdout</a>).
putStr :: String -> IO ()

-- | The same as <a>putStr</a>, but adds a newline character.
putStrLn :: String -> IO ()

-- | The <a>print</a> function outputs a value of any printable type to the
--   standard output device. Printable types are those that are instances
--   of class <a>Show</a>; <a>print</a> converts values to strings for
--   output using the <a>show</a> operation and adds a newline.
--   
--   For example, a program to print the first 20 integers and their powers
--   of 2 could be written as:
--   
--   <pre>
--   main = print ([(n, 2^n) | n &lt;- [0..19]])
--   </pre>
print :: Show a => a -> IO ()

-- | Read a character from the standard input device (same as
--   <a>hGetChar</a> <a>stdin</a>).
getChar :: IO Char

-- | Read a line from the standard input device (same as <a>hGetLine</a>
--   <a>stdin</a>).
getLine :: IO String

-- | The <a>getContents</a> operation returns all user input as a single
--   string, which is read lazily as it is needed (same as
--   <a>hGetContents</a> <a>stdin</a>).
getContents :: IO String

-- | The <a>readIO</a> function is similar to <a>read</a> except that it
--   signals parse failure to the <a>IO</a> monad instead of terminating
--   the program.
readIO :: Read a => String -> IO a

-- | The <a>readLn</a> function combines <a>getLine</a> and <a>readIO</a>.
readLn :: Read a => IO a

-- | <tt><a>withBinaryFile</a> name mode act</tt> opens a file using
--   <a>openBinaryFile</a> and passes the resulting handle to the
--   computation <tt>act</tt>. The handle will be closed on exit from
--   <a>withBinaryFile</a>, whether by normal termination or by raising an
--   exception.
withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r

-- | Like <a>openFile</a>, but open the file in binary mode. On Windows,
--   reading a file in text mode (which is the default) will translate CRLF
--   to LF, and writing will translate LF to CRLF. This is usually what you
--   want with text files. With binary files this is undesirable; also, as
--   usual under Microsoft operating systems, text mode treats control-Z as
--   EOF. Binary mode turns off all special treatment of end-of-line and
--   end-of-file characters. (See also <a>hSetBinaryMode</a>.)
openBinaryFile :: FilePath -> IOMode -> IO Handle

-- | Select binary mode (<a>True</a>) or text mode (<a>False</a>) on a open
--   handle. (See also <tt>openBinaryFile</tt>.)
--   
--   This has the same effect as calling <a>hSetEncoding</a> with
--   <a>char8</a>, together with <a>hSetNewlineMode</a> with
--   <a>noNewlineTranslation</a>.
hSetBinaryMode :: Handle -> Bool -> IO ()

-- | <a>hPutBuf</a> <tt>hdl buf count</tt> writes <tt>count</tt> 8-bit
--   bytes from the buffer <tt>buf</tt> to the handle <tt>hdl</tt>. It
--   returns ().
--   
--   <a>hPutBuf</a> ignores any text encoding that applies to the
--   <a>Handle</a>, writing the bytes directly to the underlying file or
--   device.
--   
--   <a>hPutBuf</a> ignores the prevailing <tt>TextEncoding</tt> and
--   <a>NewlineMode</a> on the <a>Handle</a>, and writes bytes directly.
--   
--   This operation may fail with:
--   
--   <ul>
--   <li><a>ResourceVanished</a> 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).</li>
--   </ul>
hPutBuf :: Handle -> Ptr a -> Int -> IO ()

-- | <a>hGetBuf</a> <tt>hdl buf count</tt> reads data from the handle
--   <tt>hdl</tt> into the buffer <tt>buf</tt> until either EOF is reached
--   or <tt>count</tt> 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 <tt>count</tt> is zero).
--   
--   <a>hGetBuf</a> never raises an EOF exception, instead it returns a
--   value smaller than <tt>count</tt>.
--   
--   If the handle is a pipe or socket, and the writing end is closed,
--   <a>hGetBuf</a> will behave as if EOF was reached.
--   
--   <a>hGetBuf</a> ignores the prevailing <tt>TextEncoding</tt> and
--   <a>NewlineMode</a> on the <a>Handle</a>, and reads bytes directly.
hGetBuf :: Handle -> Ptr a -> Int -> IO Int

-- | <a>hGetBufSome</a> <tt>hdl buf count</tt> reads data from the handle
--   <tt>hdl</tt> into the buffer <tt>buf</tt>. If there is any data
--   available to read, then <a>hGetBufSome</a> returns it immediately; it
--   only blocks if there is no data to be read.
--   
--   It returns the number of bytes actually read. This may be zero if EOF
--   was reached before any data was read (or if <tt>count</tt> is zero).
--   
--   <a>hGetBufSome</a> never raises an EOF exception, instead it returns a
--   value smaller than <tt>count</tt>.
--   
--   If the handle is a pipe or socket, and the writing end is closed,
--   <a>hGetBufSome</a> will behave as if EOF was reached.
--   
--   <a>hGetBufSome</a> ignores the prevailing <tt>TextEncoding</tt> and
--   <a>NewlineMode</a> on the <a>Handle</a>, and reads bytes directly.
hGetBufSome :: Handle -> Ptr a -> Int -> IO Int
hPutBufNonBlocking :: Handle -> Ptr a -> Int -> IO Int

-- | <a>hGetBufNonBlocking</a> <tt>hdl buf count</tt> reads data from the
--   handle <tt>hdl</tt> into the buffer <tt>buf</tt> until either EOF is
--   reached, or <tt>count</tt> 8-bit bytes have been read, or there is no
--   more data available to read immediately.
--   
--   <a>hGetBufNonBlocking</a> is identical to <a>hGetBuf</a>, except that
--   it will never block waiting for data to become available, instead it
--   returns only whatever data is available. To wait for data to arrive
--   before calling <a>hGetBufNonBlocking</a>, use <a>hWaitForInput</a>.
--   
--   If the handle is a pipe or socket, and the writing end is closed,
--   <a>hGetBufNonBlocking</a> will behave as if EOF was reached.
--   
--   <a>hGetBufNonBlocking</a> ignores the prevailing <tt>TextEncoding</tt>
--   and <a>NewlineMode</a> on the <a>Handle</a>, and reads bytes directly.
--   
--   NOTE: on Windows, this function does not work correctly; it behaves
--   identically to <a>hGetBuf</a>.
hGetBufNonBlocking :: Handle -> Ptr a -> Int -> IO Int

-- | The function creates a temporary file in ReadWrite mode. The created
--   file isn't deleted automatically, so you need to delete it manually.
--   
--   The file is creates with permissions such that only the current user
--   can read/write it.
--   
--   With some exceptions (see below), the file will be created securely in
--   the sense that an attacker should not be able to cause openTempFile to
--   overwrite another file on the filesystem using your credentials, by
--   putting symbolic links (on Unix) in the place where the temporary file
--   is to be created. On Unix the <tt>O_CREAT</tt> and <tt>O_EXCL</tt>
--   flags are used to prevent this attack, but note that <tt>O_EXCL</tt>
--   is sometimes not supported on NFS filesystems, so if you rely on this
--   behaviour it is best to use local filesystems only.
openTempFile :: FilePath -> String -> IO (FilePath, Handle)

-- | Like <a>openTempFile</a>, but opens the file in binary mode. See
--   <a>openBinaryFile</a> for more comments.
openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle)

-- | Like <a>openTempFile</a>, but uses the default file permissions
openTempFileWithDefaultPermissions :: FilePath -> String -> IO (FilePath, Handle)

-- | Like <a>openBinaryTempFile</a>, but uses the default file permissions
openBinaryTempFileWithDefaultPermissions :: FilePath -> String -> IO (FilePath, Handle)

-- | The action <a>hSetEncoding</a> <tt>hdl</tt> <tt>encoding</tt> changes
--   the text encoding for the handle <tt>hdl</tt> to <tt>encoding</tt>.
--   The default encoding when a <a>Handle</a> is created is
--   <tt>localeEncoding</tt>, namely the default encoding for the current
--   locale.
--   
--   To create a <a>Handle</a> with no encoding at all, use
--   <tt>openBinaryFile</tt>. To stop further encoding or decoding on an
--   existing <a>Handle</a>, use <a>hSetBinaryMode</a>.
--   
--   <a>hSetEncoding</a> may need to flush buffered data in order to change
--   the encoding.
hSetEncoding :: Handle -> TextEncoding -> IO ()

-- | Return the current <a>TextEncoding</a> for the specified
--   <a>Handle</a>, or <a>Nothing</a> if the <a>Handle</a> is in binary
--   mode.
--   
--   Note that the <a>TextEncoding</a> remembers nothing about the state of
--   the encoder/decoder in use on this <a>Handle</a>. For example, if the
--   encoding in use is UTF-16, then using <a>hGetEncoding</a> and
--   <a>hSetEncoding</a> to save and restore the encoding may result in an
--   extra byte-order-mark being written to the file.
hGetEncoding :: Handle -> IO (Maybe TextEncoding)

-- | A <a>TextEncoding</a> is a specification of a conversion scheme
--   between sequences of bytes and sequences of Unicode characters.
--   
--   For example, UTF-8 is an encoding of Unicode characters into a
--   sequence of bytes. The <a>TextEncoding</a> for UTF-8 is <tt>utf8</tt>.
data TextEncoding

-- | The Latin1 (ISO8859-1) encoding. This encoding maps bytes directly to
--   the first 256 Unicode code points, and is thus not a complete Unicode
--   encoding. An attempt to write a character greater than '\255' to a
--   <tt>Handle</tt> using the <a>latin1</a> encoding will result in an
--   error.
latin1 :: TextEncoding

-- | The UTF-8 Unicode encoding
utf8 :: TextEncoding

-- | The UTF-8 Unicode encoding, with a byte-order-mark (BOM; the byte
--   sequence 0xEF 0xBB 0xBF). This encoding behaves like <a>utf8</a>,
--   except that on input, the BOM sequence is ignored at the beginning of
--   the stream, and on output, the BOM sequence is prepended.
--   
--   The byte-order-mark is strictly unnecessary in UTF-8, but is sometimes
--   used to identify the encoding of a file.
utf8_bom :: TextEncoding

-- | The UTF-16 Unicode encoding (a byte-order-mark should be used to
--   indicate endianness).
utf16 :: TextEncoding

-- | The UTF-16 Unicode encoding (litte-endian)
utf16le :: TextEncoding

-- | The UTF-16 Unicode encoding (big-endian)
utf16be :: TextEncoding

-- | The UTF-32 Unicode encoding (a byte-order-mark should be used to
--   indicate endianness).
utf32 :: TextEncoding

-- | The UTF-32 Unicode encoding (litte-endian)
utf32le :: TextEncoding

-- | The UTF-32 Unicode encoding (big-endian)
utf32be :: TextEncoding

-- | The Unicode encoding of the current locale
--   
--   This is the initial locale encoding: if it has been subsequently
--   changed by <a>setLocaleEncoding</a> this value will not reflect that
--   change.
localeEncoding :: TextEncoding

-- | An encoding in which Unicode code points are translated to bytes by
--   taking the code point modulo 256. When decoding, bytes are translated
--   directly into the equivalent code point.
--   
--   This encoding never fails in either direction. However, encoding
--   discards information, so encode followed by decode is not the
--   identity.
char8 :: TextEncoding

-- | Look up the named Unicode encoding. May fail with
--   
--   <ul>
--   <li><tt>isDoesNotExistError</tt> if the encoding is unknown</li>
--   </ul>
--   
--   The set of known encodings is system-dependent, but includes at least:
--   
--   <ul>
--   <li><pre>UTF-8</pre></li>
--   <li><tt>UTF-16</tt>, <tt>UTF-16BE</tt>, <tt>UTF-16LE</tt></li>
--   <li><tt>UTF-32</tt>, <tt>UTF-32BE</tt>, <tt>UTF-32LE</tt></li>
--   </ul>
--   
--   On systems using GNU iconv (e.g. Linux), there is additional notation
--   for specifying how illegal characters are handled:
--   
--   <ul>
--   <li>a suffix of <tt>//IGNORE</tt>, e.g. <tt>UTF-8//IGNORE</tt>, will
--   cause all illegal sequences on input to be ignored, and on output will
--   drop all code points that have no representation in the target
--   encoding.</li>
--   <li>a suffix of <tt>//TRANSLIT</tt> will choose a replacement
--   character for illegal sequences or code points.</li>
--   </ul>
--   
--   On Windows, you can access supported code pages with the prefix
--   <tt>CP</tt>; for example, <tt>"CP1250"</tt>.
mkTextEncoding :: String -> IO TextEncoding

-- | Set the <a>NewlineMode</a> on the specified <a>Handle</a>. All
--   buffered data is flushed first.
hSetNewlineMode :: Handle -> NewlineMode -> IO ()

-- | The representation of a newline in the external file or stream.
data Newline

-- | '\n'
LF :: Newline

-- | '\r\n'
CRLF :: Newline

-- | The native newline representation for the current platform: <a>LF</a>
--   on Unix systems, <a>CRLF</a> on Windows.
nativeNewline :: Newline

-- | Specifies the translation, if any, of newline characters between
--   internal Strings and the external file or stream. Haskell Strings are
--   assumed to represent newlines with the '\n' character; the newline
--   mode specifies how to translate '\n' on output, and what to translate
--   into '\n' on input.
data NewlineMode
NewlineMode :: Newline -> Newline -> NewlineMode

-- | the representation of newlines on input
inputNL :: NewlineMode -> Newline

-- | the representation of newlines on output
outputNL :: NewlineMode -> Newline

-- | Do no newline translation at all.
--   
--   <pre>
--   noNewlineTranslation  = NewlineMode { inputNL  = LF, outputNL = LF }
--   </pre>
noNewlineTranslation :: NewlineMode

-- | Map '\r\n' into '\n' on input, and '\n' to the native newline
--   represetnation on output. This mode can be used on any platform, and
--   works with text files using any newline convention. The downside is
--   that <tt>readFile &gt;&gt;= writeFile</tt> might yield a different
--   file.
--   
--   <pre>
--   universalNewlineMode  = NewlineMode { inputNL  = CRLF, 
--                                         outputNL = nativeNewline }
--   </pre>
universalNewlineMode :: NewlineMode

-- | Use the native newline representation on both input and output
--   
--   <pre>
--   nativeNewlineMode  = NewlineMode { inputNL  = nativeNewline
--                                      outputNL = nativeNewline }
--   </pre>
nativeNewlineMode :: NewlineMode


-- | The Prelude: a standard module imported by default into all Haskell
--   modules. For more documentation, see the Haskell 98 Report
--   <a>http://www.haskell.org/onlinereport/</a>.
module Prelude
data Bool :: *
False :: Bool
True :: Bool

-- | Boolean "and"
(&&) :: Bool -> Bool -> Bool

-- | Boolean "or"
(||) :: Bool -> Bool -> Bool

-- | Boolean "not"
not :: Bool -> Bool

-- | <a>otherwise</a> is defined as the value <a>True</a>. It helps to make
--   guards more readable. eg.
--   
--   <pre>
--   f x | x &lt; 0     = ...
--       | otherwise = ...
--   </pre>
otherwise :: Bool

-- | The <a>Maybe</a> type encapsulates an optional value. A value of type
--   <tt><a>Maybe</a> a</tt> either contains a value of type <tt>a</tt>
--   (represented as <tt><a>Just</a> a</tt>), or it is empty (represented
--   as <a>Nothing</a>). Using <a>Maybe</a> is a good way to deal with
--   errors or exceptional cases without resorting to drastic measures such
--   as <a>error</a>.
--   
--   The <a>Maybe</a> type is also a monad. It is a simple kind of error
--   monad, where all errors are represented by <a>Nothing</a>. A richer
--   error monad can be built using the <a>Either</a> type.
data Maybe a
Nothing :: Maybe a
Just :: a -> Maybe a

-- | The <a>maybe</a> function takes a default value, a function, and a
--   <a>Maybe</a> value. If the <a>Maybe</a> value is <a>Nothing</a>, the
--   function returns the default value. Otherwise, it applies the function
--   to the value inside the <a>Just</a> and returns the result.
maybe :: b -> (a -> b) -> Maybe a -> b

-- | The <a>Either</a> type represents values with two possibilities: a
--   value of type <tt><a>Either</a> a b</tt> is either <tt><a>Left</a>
--   a</tt> or <tt><a>Right</a> b</tt>.
--   
--   The <a>Either</a> type is sometimes used to represent a value which is
--   either correct or an error; by convention, the <a>Left</a> constructor
--   is used to hold an error value and the <a>Right</a> constructor is
--   used to hold a correct value (mnemonic: "right" also means "correct").
data Either a b
Left :: a -> Either a b
Right :: b -> Either a b

-- | Case analysis for the <a>Either</a> type. If the value is
--   <tt><a>Left</a> a</tt>, apply the first function to <tt>a</tt>; if it
--   is <tt><a>Right</a> b</tt>, apply the second function to <tt>b</tt>.
either :: (a -> c) -> (b -> c) -> Either a b -> c
data Ordering :: *
LT :: Ordering
EQ :: Ordering
GT :: Ordering

-- | The character type <a>Char</a> is an enumeration whose values
--   represent Unicode (or equivalently ISO/IEC 10646) characters (see
--   <a>http://www.unicode.org/</a> for details). This set extends the ISO
--   8859-1 (Latin-1) character set (the first 256 characters), which is
--   itself an extension of the ASCII character set (the first 128
--   characters). A character literal in Haskell has type <a>Char</a>.
--   
--   To convert a <a>Char</a> to or from the corresponding <a>Int</a> value
--   defined by Unicode, use <a>toEnum</a> and <a>fromEnum</a> from the
--   <a>Enum</a> class respectively (or equivalently <tt>ord</tt> and
--   <tt>chr</tt>).
data Char :: *

-- | A <a>String</a> is a list of characters. String constants in Haskell
--   are values of type <a>String</a>.
type String = [Char]

-- | Extract the first component of a pair.
fst :: (a, b) -> a

-- | Extract the second component of a pair.
snd :: (a, b) -> b

-- | <a>curry</a> converts an uncurried function to a curried function.
curry :: ((a, b) -> c) -> a -> b -> c

-- | <a>uncurry</a> converts a curried function to a function on pairs.
uncurry :: (a -> b -> c) -> ((a, b) -> c)

-- | The <a>Eq</a> class defines equality (<a>==</a>) and inequality
--   (<a>/=</a>). All the basic datatypes exported by the <a>Prelude</a>
--   are instances of <a>Eq</a>, and <a>Eq</a> may be derived for any
--   datatype whose constituents are also instances of <a>Eq</a>.
--   
--   Minimal complete definition: either <a>==</a> or <a>/=</a>.
class Eq a
(==) :: Eq a => a -> a -> Bool
(/=) :: Eq a => a -> a -> Bool

-- | The <a>Ord</a> class is used for totally ordered datatypes.
--   
--   Instances of <a>Ord</a> can be derived for any user-defined datatype
--   whose constituent types are in <a>Ord</a>. The declared order of the
--   constructors in the data declaration determines the ordering in
--   derived <a>Ord</a> instances. The <a>Ordering</a> datatype allows a
--   single comparison to determine the precise ordering of two objects.
--   
--   Minimal complete definition: either <a>compare</a> or <a>&lt;=</a>.
--   Using <a>compare</a> can be more efficient for complex types.
class Eq a => Ord a
compare :: Ord a => a -> a -> Ordering
(<) :: Ord a => a -> a -> Bool
(>=) :: Ord a => a -> a -> Bool
(>) :: Ord a => a -> a -> Bool
(<=) :: Ord a => a -> a -> Bool
max :: Ord a => a -> a -> a
min :: Ord a => a -> a -> a

-- | Class <a>Enum</a> defines operations on sequentially ordered types.
--   
--   The <tt>enumFrom</tt>... methods are used in Haskell's translation of
--   arithmetic sequences.
--   
--   Instances of <a>Enum</a> may be derived for any enumeration type
--   (types whose constructors have no fields). The nullary constructors
--   are assumed to be numbered left-to-right by <a>fromEnum</a> from
--   <tt>0</tt> through <tt>n-1</tt>. See Chapter 10 of the <i>Haskell
--   Report</i> for more details.
--   
--   For any type that is an instance of class <a>Bounded</a> as well as
--   <a>Enum</a>, the following should hold:
--   
--   <ul>
--   <li>The calls <tt><a>succ</a> <a>maxBound</a></tt> and <tt><a>pred</a>
--   <a>minBound</a></tt> should result in a runtime error.</li>
--   <li><a>fromEnum</a> and <a>toEnum</a> should give a runtime error if
--   the result value is not representable in the result type. For example,
--   <tt><a>toEnum</a> 7 :: <a>Bool</a></tt> is an error.</li>
--   <li><a>enumFrom</a> and <a>enumFromThen</a> should be defined with an
--   implicit bound, thus:</li>
--   </ul>
--   
--   <pre>
--   enumFrom     x   = enumFromTo     x maxBound
--   enumFromThen x y = enumFromThenTo x y bound
--     where
--       bound | fromEnum y &gt;= fromEnum x = maxBound
--             | otherwise                = minBound
--   </pre>
class Enum a where succ = toEnum . (+ 1) . fromEnum pred = toEnum . (subtract 1) . fromEnum enumFrom x = map toEnum [fromEnum x .. ] enumFromThen x y = map toEnum [fromEnum x, fromEnum y .. ] enumFromTo x y = map toEnum [fromEnum x .. fromEnum y] enumFromThenTo x1 x2 y = map toEnum [fromEnum x1, fromEnum x2 .. fromEnum y]
succ :: Enum a => a -> a
pred :: Enum a => a -> a
toEnum :: Enum a => Int -> a
fromEnum :: Enum a => a -> Int
enumFrom :: Enum a => a -> [a]
enumFromThen :: Enum a => a -> a -> [a]
enumFromTo :: Enum a => a -> a -> [a]
enumFromThenTo :: Enum a => a -> a -> a -> [a]

-- | The <a>Bounded</a> class is used to name the upper and lower limits of
--   a type. <a>Ord</a> is not a superclass of <a>Bounded</a> since types
--   that are not totally ordered may also have upper and lower bounds.
--   
--   The <a>Bounded</a> class may be derived for any enumeration type;
--   <a>minBound</a> is the first constructor listed in the <tt>data</tt>
--   declaration and <a>maxBound</a> is the last. <a>Bounded</a> may also
--   be derived for single-constructor datatypes whose constituent types
--   are in <a>Bounded</a>.
class Bounded a
minBound, maxBound :: Bounded a => a

-- | A fixed-precision integer type with at least the range <tt>[-2^29 ..
--   2^29-1]</tt>. The exact range for a given implementation can be
--   determined by using <a>minBound</a> and <a>maxBound</a> from the
--   <a>Bounded</a> class.
data Int :: *

-- | Arbitrary-precision integers.
data Integer :: *

-- | Single-precision floating point numbers. It is desirable that this
--   type be at least equal in range and precision to the IEEE
--   single-precision type.
data Float :: *

-- | Double-precision floating point numbers. It is desirable that this
--   type be at least equal in range and precision to the IEEE
--   double-precision type.
data Double :: *

-- | Arbitrary-precision rational numbers, represented as a ratio of two
--   <a>Integer</a> values. A rational number may be constructed using the
--   <a>%</a> operator.
type Rational = Ratio Integer

-- | Basic numeric class.
--   
--   Minimal complete definition: all except <a>negate</a> or <tt>(-)</tt>
class Num a where x - y = x + negate y negate x = 0 - x
(+, *, -) :: Num a => a -> a -> a
negate :: Num a => a -> a
abs :: Num a => a -> a
signum :: Num a => a -> a
fromInteger :: Num a => Integer -> a
class (Num a, Ord a) => Real a
toRational :: Real a => a -> Rational

-- | Integral numbers, supporting integer division.
--   
--   Minimal complete definition: <a>quotRem</a> and <a>toInteger</a>
class (Real a, Enum a) => Integral a where n quot d = q where (q, _) = quotRem n d n rem d = r where (_, r) = quotRem n d n div d = q where (q, _) = divMod n d n mod d = r where (_, r) = divMod n d divMod n d = if signum r == negate (signum d) then (q - 1, r + d) else qr where qr@(q, r) = quotRem n d
quot :: Integral a => a -> a -> a
rem :: Integral a => a -> a -> a
div :: Integral a => a -> a -> a
mod :: Integral a => a -> a -> a
quotRem :: Integral a => a -> a -> (a, a)
divMod :: Integral a => a -> a -> (a, a)
toInteger :: Integral a => a -> Integer

-- | Fractional numbers, supporting real division.
--   
--   Minimal complete definition: <a>fromRational</a> and (<a>recip</a> or
--   <tt>(<a>/</a>)</tt>)
class Num a => Fractional a where recip x = 1 / x x / y = x * recip y
(/) :: Fractional a => a -> a -> a
recip :: Fractional a => a -> a
fromRational :: Fractional a => Rational -> a

-- | Trigonometric and hyperbolic functions and related functions.
--   
--   Minimal complete definition: <a>pi</a>, <a>exp</a>, <a>log</a>,
--   <a>sin</a>, <a>cos</a>, <a>sinh</a>, <a>cosh</a>, <a>asin</a>,
--   <a>acos</a>, <a>atan</a>, <a>asinh</a>, <a>acosh</a> and <a>atanh</a>
class Fractional a => Floating a where x ** y = exp (log x * y) logBase x y = log y / log x sqrt x = x ** 0.5 tan x = sin x / cos x tanh x = sinh x / cosh x
pi :: Floating a => a
exp, sqrt, log :: Floating a => a -> a
(**, logBase) :: Floating a => a -> a -> a
sin, tan, cos :: Floating a => a -> a
asin, atan, acos :: Floating a => a -> a
sinh, tanh, cosh :: Floating a => a -> a
asinh, atanh, acosh :: Floating a => a -> a

-- | Extracting components of fractions.
--   
--   Minimal complete definition: <a>properFraction</a>
class (Real a, Fractional a) => RealFrac a where truncate x = m where (m, _) = properFraction x round x = let (n, r) = properFraction x m = if r < 0 then n - 1 else n + 1 in case signum (abs r - 0.5) of { -1 -> n 0 -> if even n then n else m 1 -> m _ -> error "round default defn: Bad value" } ceiling x = if r > 0 then n + 1 else n where (n, r) = properFraction x floor x = if r < 0 then n - 1 else n where (n, r) = properFraction x
properFraction :: (RealFrac a, Integral b) => a -> (b, a)
truncate :: (RealFrac a, Integral b) => a -> b
round :: (RealFrac a, Integral b) => a -> b
ceiling :: (RealFrac a, Integral b) => a -> b
floor :: (RealFrac a, Integral b) => a -> b

-- | Efficient, machine-independent access to the components of a
--   floating-point number.
--   
--   Minimal complete definition: all except <a>exponent</a>,
--   <a>significand</a>, <a>scaleFloat</a> and <a>atan2</a>
class (RealFrac a, Floating a) => RealFloat a where exponent x = if m == 0 then 0 else n + floatDigits x where (m, n) = decodeFloat x significand x = encodeFloat m (negate (floatDigits x)) where (m, _) = decodeFloat x scaleFloat 0 x = x scaleFloat k x | isFix = x | otherwise = encodeFloat m (n + clamp b k) where (m, n) = decodeFloat x (l, h) = floatRange x d = floatDigits x b = h - l + 4 * d isFix = x == 0 || isNaN x || isInfinite x atan2 y x | x > 0 = atan (y / x) | x == 0 && y > 0 = pi / 2 | x < 0 && y > 0 = pi + atan (y / x) | (x <= 0 && y < 0) || (x < 0 && isNegativeZero y) || (isNegativeZero x && isNegativeZero y) = - atan2 (- y) x | y == 0 && (x < 0 || isNegativeZero x) = pi | x == 0 && y == 0 = y | otherwise = x + y
floatRadix :: RealFloat a => a -> Integer
floatDigits :: RealFloat a => a -> Int
floatRange :: RealFloat a => a -> (Int, Int)
decodeFloat :: RealFloat a => a -> (Integer, Int)
encodeFloat :: RealFloat a => Integer -> Int -> a
exponent :: RealFloat a => a -> Int
significand :: RealFloat a => a -> a
scaleFloat :: RealFloat a => Int -> a -> a
isNaN :: RealFloat a => a -> Bool
isInfinite :: RealFloat a => a -> Bool
isDenormalized :: RealFloat a => a -> Bool
isNegativeZero :: RealFloat a => a -> Bool
isIEEE :: RealFloat a => a -> Bool
atan2 :: RealFloat a => a -> a -> a

-- | the same as <tt><a>flip</a> (<a>-</a>)</tt>.
--   
--   Because <tt>-</tt> is treated specially in the Haskell grammar,
--   <tt>(-</tt> <i>e</i><tt>)</tt> is not a section, but an application of
--   prefix negation. However, <tt>(<a>subtract</a></tt>
--   <i>exp</i><tt>)</tt> is equivalent to the disallowed section.
subtract :: Num a => a -> a -> a
even :: Integral a => a -> Bool
odd :: Integral a => a -> Bool

-- | <tt><a>gcd</a> x y</tt> is the non-negative factor of both <tt>x</tt>
--   and <tt>y</tt> of which every common factor of <tt>x</tt> and
--   <tt>y</tt> is also a factor; for example <tt><a>gcd</a> 4 2 = 2</tt>,
--   <tt><a>gcd</a> (-4) 6 = 2</tt>, <tt><a>gcd</a> 0 4</tt> = <tt>4</tt>.
--   <tt><a>gcd</a> 0 0</tt> = <tt>0</tt>. (That is, the common divisor
--   that is "greatest" in the divisibility preordering.)
--   
--   Note: Since for signed fixed-width integer types, <tt><a>abs</a>
--   <a>minBound</a> &lt; 0</tt>, the result may be negative if one of the
--   arguments is <tt><a>minBound</a></tt> (and necessarily is if the other
--   is <tt>0</tt> or <tt><a>minBound</a></tt>) for such types.
gcd :: Integral a => a -> a -> a

-- | <tt><a>lcm</a> x y</tt> is the smallest positive integer that both
--   <tt>x</tt> and <tt>y</tt> divide.
lcm :: Integral a => a -> a -> a

-- | raise a number to a non-negative integral power
(^) :: (Num a, Integral b) => a -> b -> a

-- | raise a number to an integral power
(^^) :: (Fractional a, Integral b) => a -> b -> a

-- | general coercion from integral types
fromIntegral :: (Integral a, Num b) => a -> b

-- | general coercion to fractional types
realToFrac :: (Real a, Fractional b) => a -> b

-- | The <a>Monad</a> class defines the basic operations over a
--   <i>monad</i>, a concept from a branch of mathematics known as
--   <i>category theory</i>. From the perspective of a Haskell programmer,
--   however, it is best to think of a monad as an <i>abstract datatype</i>
--   of actions. Haskell's <tt>do</tt> expressions provide a convenient
--   syntax for writing monadic expressions.
--   
--   Minimal complete definition: <a>&gt;&gt;=</a> and <a>return</a>.
--   
--   Instances of <a>Monad</a> should satisfy the following laws:
--   
--   <pre>
--   return a &gt;&gt;= k  ==  k a
--   m &gt;&gt;= return  ==  m
--   m &gt;&gt;= (\x -&gt; k x &gt;&gt;= h)  ==  (m &gt;&gt;= k) &gt;&gt;= h
--   </pre>
--   
--   Instances of both <a>Monad</a> and <a>Functor</a> should additionally
--   satisfy the law:
--   
--   <pre>
--   fmap f xs  ==  xs &gt;&gt;= return . f
--   </pre>
--   
--   The instances of <a>Monad</a> for lists, <a>Maybe</a> and <a>IO</a>
--   defined in the <a>Prelude</a> satisfy these laws.
class Monad m where m >> k = m >>= \ _ -> k fail s = error s
(>>=) :: Monad m => m a -> (a -> m b) -> m b
(>>) :: Monad m => m a -> m b -> m b
return :: Monad m => a -> m a
fail :: Monad m => String -> m a

-- | The <a>Functor</a> class is used for types that can be mapped over.
--   Instances of <a>Functor</a> should satisfy the following laws:
--   
--   <pre>
--   fmap id  ==  id
--   fmap (f . g)  ==  fmap f . fmap g
--   </pre>
--   
--   The instances of <a>Functor</a> for lists, <a>Maybe</a> and <a>IO</a>
--   satisfy these laws.
class Functor f where <$ = fmap . const
fmap :: Functor f => (a -> b) -> f a -> f b

-- | <tt><a>mapM</a> f</tt> is equivalent to <tt><a>sequence</a> .
--   <a>map</a> f</tt>.
mapM :: Monad m => (a -> m b) -> [a] -> m [b]

-- | <tt><a>mapM_</a> f</tt> is equivalent to <tt><a>sequence_</a> .
--   <a>map</a> f</tt>.
mapM_ :: Monad m => (a -> m b) -> [a] -> m ()

-- | Evaluate each action in the sequence from left to right, and collect
--   the results.
sequence :: Monad m => [m a] -> m [a]

-- | Evaluate each action in the sequence from left to right, and ignore
--   the results.
sequence_ :: Monad m => [m a] -> m ()

-- | Same as <a>&gt;&gt;=</a>, but with the arguments interchanged.
(=<<) :: Monad m => (a -> m b) -> m a -> m b

-- | Identity function.
id :: a -> a

-- | Constant function.
const :: a -> b -> a

-- | Function composition.
(.) :: (b -> c) -> (a -> b) -> a -> c

-- | <tt><a>flip</a> f</tt> takes its (first) two arguments in the reverse
--   order of <tt>f</tt>.
flip :: (a -> b -> c) -> b -> a -> c

-- | Application operator. This operator is redundant, since ordinary
--   application <tt>(f x)</tt> means the same as <tt>(f <a>$</a> x)</tt>.
--   However, <a>$</a> has low, right-associative binding precedence, so it
--   sometimes allows parentheses to be omitted; for example:
--   
--   <pre>
--   f $ g $ h x  =  f (g (h x))
--   </pre>
--   
--   It is also useful in higher-order situations, such as <tt><a>map</a>
--   (<a>$</a> 0) xs</tt>, or <tt><a>zipWith</a> (<a>$</a>) fs xs</tt>.
($) :: (a -> b) -> a -> b

-- | <tt><a>until</a> p f</tt> yields the result of applying <tt>f</tt>
--   until <tt>p</tt> holds.
until :: (a -> Bool) -> (a -> a) -> a -> a

-- | <a>asTypeOf</a> is a type-restricted version of <a>const</a>. It is
--   usually used as an infix operator, and its typing forces its first
--   argument (which is usually overloaded) to have the same type as the
--   second.
asTypeOf :: a -> a -> a

-- | <a>error</a> stops execution and displays an error message.
error :: [Char] -> a

-- | A special case of <a>error</a>. It is expected that compilers will
--   recognize this and insert error messages which are more appropriate to
--   the context in which <a>undefined</a> appears.
undefined :: a

-- | Evaluates its first argument to head normal form, and then returns its
--   second argument as the result.
seq :: a -> b -> b

-- | Strict (call-by-value) application, defined in terms of <a>seq</a>.
($!) :: (a -> b) -> a -> b

-- | <a>map</a> <tt>f xs</tt> is the list obtained by applying <tt>f</tt>
--   to each element of <tt>xs</tt>, i.e.,
--   
--   <pre>
--   map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn]
--   map f [x1, x2, ...] == [f x1, f x2, ...]
--   </pre>
map :: (a -> b) -> [a] -> [b]

-- | Append two lists, i.e.,
--   
--   <pre>
--   [x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn]
--   [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]
--   </pre>
--   
--   If the first list is not finite, the result is the first list.
(++) :: [a] -> [a] -> [a]

-- | <a>filter</a>, applied to a predicate and a list, returns the list of
--   those elements that satisfy the predicate; i.e.,
--   
--   <pre>
--   filter p xs = [ x | x &lt;- xs, p x]
--   </pre>
filter :: (a -> Bool) -> [a] -> [a]

-- | Extract the first element of a list, which must be non-empty.
head :: [a] -> a

-- | Extract the last element of a list, which must be finite and
--   non-empty.
last :: [a] -> a

-- | Extract the elements after the head of a list, which must be
--   non-empty.
tail :: [a] -> [a]

-- | Return all the elements of a list except the last one. The list must
--   be non-empty.
init :: [a] -> [a]

-- | Test whether a list is empty.
null :: [a] -> Bool

-- | <i>O(n)</i>. <a>length</a> returns the length of a finite list as an
--   <a>Int</a>. It is an instance of the more general
--   <a>genericLength</a>, the result type of which may be any kind of
--   number.
length :: [a] -> Int

-- | List index (subscript) operator, starting from 0. It is an instance of
--   the more general <a>genericIndex</a>, which takes an index of any
--   integral type.
(!!) :: [a] -> Int -> a

-- | <a>reverse</a> <tt>xs</tt> returns the elements of <tt>xs</tt> in
--   reverse order. <tt>xs</tt> must be finite.
reverse :: [a] -> [a]

-- | <a>foldl</a>, applied to a binary operator, a starting value
--   (typically the left-identity of the operator), and a list, reduces the
--   list using the binary operator, from left to right:
--   
--   <pre>
--   foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
--   </pre>
--   
--   The list must be finite.
foldl :: (a -> b -> a) -> a -> [b] -> a

-- | <a>foldl1</a> is a variant of <a>foldl</a> that has no starting value
--   argument, and thus must be applied to non-empty lists.
foldl1 :: (a -> a -> a) -> [a] -> a

-- | <a>foldr</a>, applied to a binary operator, a starting value
--   (typically the right-identity of the operator), and a list, reduces
--   the list using the binary operator, from right to left:
--   
--   <pre>
--   foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)
--   </pre>
foldr :: (a -> b -> b) -> b -> [a] -> b

-- | <a>foldr1</a> is a variant of <a>foldr</a> that has no starting value
--   argument, and thus must be applied to non-empty lists.
foldr1 :: (a -> a -> a) -> [a] -> a

-- | <a>and</a> returns the conjunction of a Boolean list. For the result
--   to be <a>True</a>, the list must be finite; <a>False</a>, however,
--   results from a <a>False</a> value at a finite index of a finite or
--   infinite list.
and :: [Bool] -> Bool

-- | <a>or</a> returns the disjunction of a Boolean list. For the result to
--   be <a>False</a>, the list must be finite; <a>True</a>, however,
--   results from a <a>True</a> value at a finite index of a finite or
--   infinite list.
or :: [Bool] -> Bool

-- | Applied to a predicate and a list, <a>any</a> determines if any
--   element of the list satisfies the predicate. For the result to be
--   <a>False</a>, the list must be finite; <a>True</a>, however, results
--   from a <a>True</a> value for the predicate applied to an element at a
--   finite index of a finite or infinite list.
any :: (a -> Bool) -> [a] -> Bool

-- | Applied to a predicate and a list, <a>all</a> determines if all
--   elements of the list satisfy the predicate. For the result to be
--   <a>True</a>, the list must be finite; <a>False</a>, however, results
--   from a <a>False</a> value for the predicate applied to an element at a
--   finite index of a finite or infinite list.
all :: (a -> Bool) -> [a] -> Bool

-- | The <a>sum</a> function computes the sum of a finite list of numbers.
sum :: Num a => [a] -> a

-- | The <a>product</a> function computes the product of a finite list of
--   numbers.
product :: Num a => [a] -> a

-- | Concatenate a list of lists.
concat :: [[a]] -> [a]

-- | Map a function over a list and concatenate the results.
concatMap :: (a -> [b]) -> [a] -> [b]

-- | <a>maximum</a> returns the maximum value from a list, which must be
--   non-empty, finite, and of an ordered type. It is a special case of
--   <a>maximumBy</a>, which allows the programmer to supply their own
--   comparison function.
maximum :: Ord a => [a] -> a

-- | <a>minimum</a> returns the minimum value from a list, which must be
--   non-empty, finite, and of an ordered type. It is a special case of
--   <a>minimumBy</a>, which allows the programmer to supply their own
--   comparison function.
minimum :: Ord a => [a] -> a

-- | <a>scanl</a> is similar to <a>foldl</a>, but returns a list of
--   successive reduced values from the left:
--   
--   <pre>
--   scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
--   </pre>
--   
--   Note that
--   
--   <pre>
--   last (scanl f z xs) == foldl f z xs.
--   </pre>
scanl :: (a -> b -> a) -> a -> [b] -> [a]

-- | <a>scanl1</a> is a variant of <a>scanl</a> that has no starting value
--   argument:
--   
--   <pre>
--   scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
--   </pre>
scanl1 :: (a -> a -> a) -> [a] -> [a]

-- | <a>scanr</a> is the right-to-left dual of <a>scanl</a>. Note that
--   
--   <pre>
--   head (scanr f z xs) == foldr f z xs.
--   </pre>
scanr :: (a -> b -> b) -> b -> [a] -> [b]

-- | <a>scanr1</a> is a variant of <a>scanr</a> that has no starting value
--   argument.
scanr1 :: (a -> a -> a) -> [a] -> [a]

-- | <a>iterate</a> <tt>f x</tt> returns an infinite list of repeated
--   applications of <tt>f</tt> to <tt>x</tt>:
--   
--   <pre>
--   iterate f x == [x, f x, f (f x), ...]
--   </pre>
iterate :: (a -> a) -> a -> [a]

-- | <a>repeat</a> <tt>x</tt> is an infinite list, with <tt>x</tt> the
--   value of every element.
repeat :: a -> [a]

-- | <a>replicate</a> <tt>n x</tt> is a list of length <tt>n</tt> with
--   <tt>x</tt> the value of every element. It is an instance of the more
--   general <a>genericReplicate</a>, in which <tt>n</tt> may be of any
--   integral type.
replicate :: Int -> a -> [a]

-- | <a>cycle</a> ties a finite list into a circular one, or equivalently,
--   the infinite repetition of the original list. It is the identity on
--   infinite lists.
cycle :: [a] -> [a]

-- | <a>take</a> <tt>n</tt>, applied to a list <tt>xs</tt>, returns the
--   prefix of <tt>xs</tt> of length <tt>n</tt>, or <tt>xs</tt> itself if
--   <tt>n &gt; <a>length</a> xs</tt>:
--   
--   <pre>
--   take 5 "Hello World!" == "Hello"
--   take 3 [1,2,3,4,5] == [1,2,3]
--   take 3 [1,2] == [1,2]
--   take 3 [] == []
--   take (-1) [1,2] == []
--   take 0 [1,2] == []
--   </pre>
--   
--   It is an instance of the more general <a>genericTake</a>, in which
--   <tt>n</tt> may be of any integral type.
take :: Int -> [a] -> [a]

-- | <a>drop</a> <tt>n xs</tt> returns the suffix of <tt>xs</tt> after the
--   first <tt>n</tt> elements, or <tt>[]</tt> if <tt>n &gt; <a>length</a>
--   xs</tt>:
--   
--   <pre>
--   drop 6 "Hello World!" == "World!"
--   drop 3 [1,2,3,4,5] == [4,5]
--   drop 3 [1,2] == []
--   drop 3 [] == []
--   drop (-1) [1,2] == [1,2]
--   drop 0 [1,2] == [1,2]
--   </pre>
--   
--   It is an instance of the more general <a>genericDrop</a>, in which
--   <tt>n</tt> may be of any integral type.
drop :: Int -> [a] -> [a]

-- | <a>splitAt</a> <tt>n xs</tt> returns a tuple where first element is
--   <tt>xs</tt> prefix of length <tt>n</tt> and second element is the
--   remainder of the list:
--   
--   <pre>
--   splitAt 6 "Hello World!" == ("Hello ","World!")
--   splitAt 3 [1,2,3,4,5] == ([1,2,3],[4,5])
--   splitAt 1 [1,2,3] == ([1],[2,3])
--   splitAt 3 [1,2,3] == ([1,2,3],[])
--   splitAt 4 [1,2,3] == ([1,2,3],[])
--   splitAt 0 [1,2,3] == ([],[1,2,3])
--   splitAt (-1) [1,2,3] == ([],[1,2,3])
--   </pre>
--   
--   It is equivalent to <tt>(<a>take</a> n xs, <a>drop</a> n xs)</tt> when
--   <tt>n</tt> is not <tt>_|_</tt> (<tt>splitAt _|_ xs = _|_</tt>).
--   <a>splitAt</a> is an instance of the more general
--   <a>genericSplitAt</a>, in which <tt>n</tt> may be of any integral
--   type.
splitAt :: Int -> [a] -> ([a], [a])

-- | <a>takeWhile</a>, applied to a predicate <tt>p</tt> and a list
--   <tt>xs</tt>, returns the longest prefix (possibly empty) of
--   <tt>xs</tt> of elements that satisfy <tt>p</tt>:
--   
--   <pre>
--   takeWhile (&lt; 3) [1,2,3,4,1,2,3,4] == [1,2]
--   takeWhile (&lt; 9) [1,2,3] == [1,2,3]
--   takeWhile (&lt; 0) [1,2,3] == []
--   </pre>
takeWhile :: (a -> Bool) -> [a] -> [a]

-- | <a>dropWhile</a> <tt>p xs</tt> returns the suffix remaining after
--   <a>takeWhile</a> <tt>p xs</tt>:
--   
--   <pre>
--   dropWhile (&lt; 3) [1,2,3,4,5,1,2,3] == [3,4,5,1,2,3]
--   dropWhile (&lt; 9) [1,2,3] == []
--   dropWhile (&lt; 0) [1,2,3] == [1,2,3]
--   </pre>
dropWhile :: (a -> Bool) -> [a] -> [a]

-- | <a>span</a>, applied to a predicate <tt>p</tt> and a list <tt>xs</tt>,
--   returns a tuple where first element is longest prefix (possibly empty)
--   of <tt>xs</tt> of elements that satisfy <tt>p</tt> and second element
--   is the remainder of the list:
--   
--   <pre>
--   span (&lt; 3) [1,2,3,4,1,2,3,4] == ([1,2],[3,4,1,2,3,4])
--   span (&lt; 9) [1,2,3] == ([1,2,3],[])
--   span (&lt; 0) [1,2,3] == ([],[1,2,3])
--   </pre>
--   
--   <a>span</a> <tt>p xs</tt> is equivalent to <tt>(<a>takeWhile</a> p xs,
--   <a>dropWhile</a> p xs)</tt>
span :: (a -> Bool) -> [a] -> ([a], [a])

-- | <a>break</a>, applied to a predicate <tt>p</tt> and a list
--   <tt>xs</tt>, returns a tuple where first element is longest prefix
--   (possibly empty) of <tt>xs</tt> of elements that <i>do not satisfy</i>
--   <tt>p</tt> and second element is the remainder of the list:
--   
--   <pre>
--   break (&gt; 3) [1,2,3,4,1,2,3,4] == ([1,2,3],[4,1,2,3,4])
--   break (&lt; 9) [1,2,3] == ([],[1,2,3])
--   break (&gt; 9) [1,2,3] == ([1,2,3],[])
--   </pre>
--   
--   <a>break</a> <tt>p</tt> is equivalent to <tt><a>span</a> (<a>not</a> .
--   p)</tt>.
break :: (a -> Bool) -> [a] -> ([a], [a])

-- | <a>elem</a> is the list membership predicate, usually written in infix
--   form, e.g., <tt>x `elem` xs</tt>. For the result to be <a>False</a>,
--   the list must be finite; <a>True</a>, however, results from an element
--   equal to <tt>x</tt> found at a finite index of a finite or infinite
--   list.
elem :: Eq a => a -> [a] -> Bool

-- | <a>notElem</a> is the negation of <a>elem</a>.
notElem :: Eq a => a -> [a] -> Bool

-- | <a>lookup</a> <tt>key assocs</tt> looks up a key in an association
--   list.
lookup :: Eq a => a -> [(a, b)] -> Maybe b

-- | <a>zip</a> takes two lists and returns a list of corresponding pairs.
--   If one input list is short, excess elements of the longer list are
--   discarded.
zip :: [a] -> [b] -> [(a, b)]

-- | <a>zip3</a> takes three lists and returns a list of triples, analogous
--   to <a>zip</a>.
zip3 :: [a] -> [b] -> [c] -> [(a, b, c)]

-- | <a>zipWith</a> generalises <a>zip</a> by zipping with the function
--   given as the first argument, instead of a tupling function. For
--   example, <tt><a>zipWith</a> (+)</tt> is applied to two lists to
--   produce the list of corresponding sums.
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]

-- | The <a>zipWith3</a> function takes a function which combines three
--   elements, as well as three lists and returns a list of their
--   point-wise combination, analogous to <a>zipWith</a>.
zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]

-- | <a>unzip</a> transforms a list of pairs into a list of first
--   components and a list of second components.
unzip :: [(a, b)] -> ([a], [b])

-- | The <a>unzip3</a> function takes a list of triples and returns three
--   lists, analogous to <a>unzip</a>.
unzip3 :: [(a, b, c)] -> ([a], [b], [c])

-- | <a>lines</a> breaks a string up into a list of strings at newline
--   characters. The resulting strings do not contain newlines.
lines :: String -> [String]

-- | <a>words</a> breaks a string up into a list of words, which were
--   delimited by white space.
words :: String -> [String]

-- | <a>unlines</a> is an inverse operation to <a>lines</a>. It joins
--   lines, after appending a terminating newline to each.
unlines :: [String] -> String

-- | <a>unwords</a> is an inverse operation to <a>words</a>. It joins words
--   with separating spaces.
unwords :: [String] -> String

-- | The <tt>shows</tt> functions return a function that prepends the
--   output <a>String</a> to an existing <a>String</a>. This allows
--   constant-time concatenation of results using function composition.
type ShowS = String -> String

-- | Conversion of values to readable <a>String</a>s.
--   
--   Minimal complete definition: <a>showsPrec</a> or <a>show</a>.
--   
--   Derived instances of <a>Show</a> have the following properties, which
--   are compatible with derived instances of <a>Read</a>:
--   
--   <ul>
--   <li>The result of <a>show</a> is a syntactically correct Haskell
--   expression containing only constants, given the fixity declarations in
--   force at the point where the type is declared. It contains only the
--   constructor names defined in the data type, parentheses, and spaces.
--   When labelled constructor fields are used, braces, commas, field
--   names, and equal signs are also used.</li>
--   <li>If the constructor is defined to be an infix operator, then
--   <a>showsPrec</a> will produce infix applications of the
--   constructor.</li>
--   <li>the representation will be enclosed in parentheses if the
--   precedence of the top-level constructor in <tt>x</tt> is less than
--   <tt>d</tt> (associativity is ignored). Thus, if <tt>d</tt> is
--   <tt>0</tt> then the result is never surrounded in parentheses; if
--   <tt>d</tt> is <tt>11</tt> it is always surrounded in parentheses,
--   unless it is an atomic expression.</li>
--   <li>If the constructor is defined using record syntax, then
--   <a>show</a> will produce the record-syntax form, with the fields given
--   in the same order as the original declaration.</li>
--   </ul>
--   
--   For example, given the declarations
--   
--   <pre>
--   infixr 5 :^:
--   data Tree a =  Leaf a  |  Tree a :^: Tree a
--   </pre>
--   
--   the derived instance of <a>Show</a> is equivalent to
--   
--   <pre>
--   instance (Show a) =&gt; Show (Tree a) where
--   
--          showsPrec d (Leaf m) = showParen (d &gt; app_prec) $
--               showString "Leaf " . showsPrec (app_prec+1) m
--            where app_prec = 10
--   
--          showsPrec d (u :^: v) = showParen (d &gt; up_prec) $
--               showsPrec (up_prec+1) u .
--               showString " :^: "      .
--               showsPrec (up_prec+1) v
--            where up_prec = 5
--   </pre>
--   
--   Note that right-associativity of <tt>:^:</tt> is ignored. For example,
--   
--   <ul>
--   <li><tt><a>show</a> (Leaf 1 :^: Leaf 2 :^: Leaf 3)</tt> produces the
--   string <tt>"Leaf 1 :^: (Leaf 2 :^: Leaf 3)"</tt>.</li>
--   </ul>
class Show a where showsPrec _ x s = show x ++ s show x = shows x "" showList ls s = showList__ shows ls s
showsPrec :: Show a => Int -> a -> ShowS
show :: Show a => a -> String
showList :: Show a => [a] -> ShowS

-- | equivalent to <a>showsPrec</a> with a precedence of 0.
shows :: Show a => a -> ShowS

-- | utility function converting a <a>Char</a> to a show function that
--   simply prepends the character unchanged.
showChar :: Char -> ShowS

-- | utility function converting a <a>String</a> to a show function that
--   simply prepends the string unchanged.
showString :: String -> ShowS

-- | utility function that surrounds the inner show function with
--   parentheses when the <a>Bool</a> parameter is <a>True</a>.
showParen :: Bool -> ShowS -> ShowS

-- | A parser for a type <tt>a</tt>, represented as a function that takes a
--   <a>String</a> and returns a list of possible parses as
--   <tt>(a,<a>String</a>)</tt> pairs.
--   
--   Note that this kind of backtracking parser is very inefficient;
--   reading a large structure may be quite slow (cf <a>ReadP</a>).
type ReadS a = String -> [(a, String)]

-- | Parsing of <a>String</a>s, producing values.
--   
--   Minimal complete definition: <a>readsPrec</a> (or, for GHC only,
--   <a>readPrec</a>)
--   
--   Derived instances of <a>Read</a> make the following assumptions, which
--   derived instances of <a>Show</a> obey:
--   
--   <ul>
--   <li>If the constructor is defined to be an infix operator, then the
--   derived <a>Read</a> instance will parse only infix applications of the
--   constructor (not the prefix form).</li>
--   <li>Associativity is not used to reduce the occurrence of parentheses,
--   although precedence may be.</li>
--   <li>If the constructor is defined using record syntax, the derived
--   <a>Read</a> will parse only the record-syntax form, and furthermore,
--   the fields must be given in the same order as the original
--   declaration.</li>
--   <li>The derived <a>Read</a> instance allows arbitrary Haskell
--   whitespace between tokens of the input string. Extra parentheses are
--   also allowed.</li>
--   </ul>
--   
--   For example, given the declarations
--   
--   <pre>
--   infixr 5 :^:
--   data Tree a =  Leaf a  |  Tree a :^: Tree a
--   </pre>
--   
--   the derived instance of <a>Read</a> in Haskell 98 is equivalent to
--   
--   <pre>
--   instance (Read a) =&gt; Read (Tree a) where
--   
--           readsPrec d r =  readParen (d &gt; app_prec)
--                            (\r -&gt; [(Leaf m,t) |
--                                    ("Leaf",s) &lt;- lex r,
--                                    (m,t) &lt;- readsPrec (app_prec+1) s]) r
--   
--                         ++ readParen (d &gt; up_prec)
--                            (\r -&gt; [(u:^:v,w) |
--                                    (u,s) &lt;- readsPrec (up_prec+1) r,
--                                    (":^:",t) &lt;- lex s,
--                                    (v,w) &lt;- readsPrec (up_prec+1) t]) r
--   
--             where app_prec = 10
--                   up_prec = 5
--   </pre>
--   
--   Note that right-associativity of <tt>:^:</tt> is unused.
--   
--   The derived instance in GHC is equivalent to
--   
--   <pre>
--   instance (Read a) =&gt; Read (Tree a) where
--   
--           readPrec = parens $ (prec app_prec $ do
--                                    Ident "Leaf" &lt;- lexP
--                                    m &lt;- step readPrec
--                                    return (Leaf m))
--   
--                        +++ (prec up_prec $ do
--                                    u &lt;- step readPrec
--                                    Symbol ":^:" &lt;- lexP
--                                    v &lt;- step readPrec
--                                    return (u :^: v))
--   
--             where app_prec = 10
--                   up_prec = 5
--   
--           readListPrec = readListPrecDefault
--   </pre>
class Read a where readsPrec = readPrec_to_S readPrec readList = readPrec_to_S (list readPrec) 0 readPrec = readS_to_Prec readsPrec readListPrec = readS_to_Prec (\ _ -> readList)
readsPrec :: Read a => Int -> ReadS a
readList :: Read a => ReadS [a]

-- | equivalent to <a>readsPrec</a> with a precedence of 0.
reads :: Read a => ReadS a

-- | <tt><a>readParen</a> <a>True</a> p</tt> parses what <tt>p</tt> parses,
--   but surrounded with parentheses.
--   
--   <tt><a>readParen</a> <a>False</a> p</tt> parses what <tt>p</tt>
--   parses, but optionally surrounded with parentheses.
readParen :: Bool -> ReadS a -> ReadS a

-- | The <a>read</a> function reads input from a string, which must be
--   completely consumed by the input process.
read :: Read a => String -> a

-- | The <a>lex</a> function reads a single lexeme from the input,
--   discarding initial white space, and returning the characters that
--   constitute the lexeme. If the input string contains only white space,
--   <a>lex</a> returns a single successful `lexeme' consisting of the
--   empty string. (Thus <tt><a>lex</a> "" = [("","")]</tt>.) If there is
--   no legal lexeme at the beginning of the input string, <a>lex</a> fails
--   (i.e. returns <tt>[]</tt>).
--   
--   This lexer is not completely faithful to the Haskell lexical syntax in
--   the following respects:
--   
--   <ul>
--   <li>Qualified names are not handled properly</li>
--   <li>Octal and hexadecimal numerics are not recognized as a single
--   token</li>
--   <li>Comments are not treated properly</li>
--   </ul>
lex :: ReadS String

-- | A value of type <tt><a>IO</a> a</tt> is a computation which, when
--   performed, does some I/O before returning a value of type <tt>a</tt>.
--   
--   There is really only one way to "perform" an I/O action: bind it to
--   <tt>Main.main</tt> in your program. When your program is run, the I/O
--   will be performed. It isn't possible to perform I/O from an arbitrary
--   function, unless that function is itself in the <a>IO</a> monad and
--   called at some point, directly or indirectly, from <tt>Main.main</tt>.
--   
--   <a>IO</a> is a monad, so <a>IO</a> actions can be combined using
--   either the do-notation or the <tt>&gt;&gt;</tt> and <tt>&gt;&gt;=</tt>
--   operations from the <tt>Monad</tt> class.
data IO a :: * -> *

-- | Write a character to the standard output device (same as
--   <a>hPutChar</a> <a>stdout</a>).
putChar :: Char -> IO ()

-- | Write a string to the standard output device (same as <a>hPutStr</a>
--   <a>stdout</a>).
putStr :: String -> IO ()

-- | The same as <a>putStr</a>, but adds a newline character.
putStrLn :: String -> IO ()

-- | The <a>print</a> function outputs a value of any printable type to the
--   standard output device. Printable types are those that are instances
--   of class <a>Show</a>; <a>print</a> converts values to strings for
--   output using the <a>show</a> operation and adds a newline.
--   
--   For example, a program to print the first 20 integers and their powers
--   of 2 could be written as:
--   
--   <pre>
--   main = print ([(n, 2^n) | n &lt;- [0..19]])
--   </pre>
print :: Show a => a -> IO ()

-- | Read a character from the standard input device (same as
--   <a>hGetChar</a> <a>stdin</a>).
getChar :: IO Char

-- | Read a line from the standard input device (same as <a>hGetLine</a>
--   <a>stdin</a>).
getLine :: IO String

-- | The <a>getContents</a> operation returns all user input as a single
--   string, which is read lazily as it is needed (same as
--   <a>hGetContents</a> <a>stdin</a>).
getContents :: IO String

-- | The <a>interact</a> function takes a function of type
--   <tt>String-&gt;String</tt> as its argument. The entire input from the
--   standard input device is passed to this function as its argument, and
--   the resulting string is output on the standard output device.
interact :: (String -> String) -> IO ()

-- | File and directory names are values of type <a>String</a>, whose
--   precise meaning is operating system dependent. Files can be opened,
--   yielding a handle which can then be used to operate on the contents of
--   that file.
type FilePath = String

-- | The <a>readFile</a> function reads a file and returns the contents of
--   the file as a string. The file is read lazily, on demand, as with
--   <a>getContents</a>.
readFile :: FilePath -> IO String

-- | The computation <a>writeFile</a> <tt>file str</tt> function writes the
--   string <tt>str</tt>, to the file <tt>file</tt>.
writeFile :: FilePath -> String -> IO ()

-- | The computation <a>appendFile</a> <tt>file str</tt> function appends
--   the string <tt>str</tt>, to the file <tt>file</tt>.
--   
--   Note that <a>writeFile</a> and <a>appendFile</a> write a literal
--   string to a file. To write a value of any printable type, as with
--   <a>print</a>, use the <a>show</a> function to convert the value to a
--   string first.
--   
--   <pre>
--   main = appendFile "squares" (show [(x,x*x) | x &lt;- [0,0.1..2]])
--   </pre>
appendFile :: FilePath -> String -> IO ()

-- | The <a>readIO</a> function is similar to <a>read</a> except that it
--   signals parse failure to the <a>IO</a> monad instead of terminating
--   the program.
readIO :: Read a => String -> IO a

-- | The <a>readLn</a> function combines <a>getLine</a> and <a>readIO</a>.
readLn :: Read a => IO a

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

-- | Raise an <a>IOError</a> in the <a>IO</a> monad.
ioError :: IOError -> IO a

-- | Construct an <a>IOError</a> value with a string describing the error.
--   The <a>fail</a> method of the <a>IO</a> instance of the <a>Monad</a>
--   class raises a <a>userError</a>, thus:
--   
--   <pre>
--   instance Monad IO where 
--     ...
--     fail s = ioError (userError s)
--   </pre>
userError :: String -> IOError


-- | "Scrap your boilerplate" --- Generic programming in Haskell. See
--   <a>http://www.cs.vu.nl/boilerplate/</a>. This module provides the
--   <a>Data</a> class with its primitives for generic programming, along
--   with instances for many datatypes. It corresponds to a merge between
--   the previous <a>Data.Generics.Basics</a> and almost all of
--   <a>Data.Generics.Instances</a>. The instances that are not present in
--   this module were moved to the <tt>Data.Generics.Instances</tt> module
--   in the <tt>syb</tt> package.
--   
--   For more information, please visit the new SYB wiki:
--   <a>http://www.cs.uu.nl/wiki/bin/view/GenericProgramming/SYB</a>.
module Data.Data

-- | The <a>Data</a> class comprehends a fundamental primitive
--   <a>gfoldl</a> for folding over constructor applications, say terms.
--   This primitive can be instantiated in several ways to map over the
--   immediate subterms of a term; see the <tt>gmap</tt> combinators later
--   in this class. Indeed, a generic programmer does not necessarily need
--   to use the ingenious gfoldl primitive but rather the intuitive
--   <tt>gmap</tt> combinators. The <a>gfoldl</a> primitive is completed by
--   means to query top-level constructors, to turn constructor
--   representations into proper terms, and to list all possible datatype
--   constructors. This completion allows us to serve generic programming
--   scenarios like read, show, equality, term generation.
--   
--   The combinators <a>gmapT</a>, <a>gmapQ</a>, <a>gmapM</a>, etc are all
--   provided with default definitions in terms of <a>gfoldl</a>, leaving
--   open the opportunity to provide datatype-specific definitions. (The
--   inclusion of the <tt>gmap</tt> combinators as members of class
--   <a>Data</a> allows the programmer or the compiler to derive
--   specialised, and maybe more efficient code per datatype. <i>Note</i>:
--   <a>gfoldl</a> is more higher-order than the <tt>gmap</tt> combinators.
--   This is subject to ongoing benchmarking experiments. It might turn out
--   that the <tt>gmap</tt> combinators will be moved out of the class
--   <a>Data</a>.)
--   
--   Conceptually, the definition of the <tt>gmap</tt> combinators in terms
--   of the primitive <a>gfoldl</a> requires the identification of the
--   <a>gfoldl</a> function arguments. Technically, we also need to
--   identify the type constructor <tt>c</tt> for the construction of the
--   result type from the folded term type.
--   
--   In the definition of <tt>gmapQ</tt><i>x</i> combinators, we use
--   phantom type constructors for the <tt>c</tt> in the type of
--   <a>gfoldl</a> because the result type of a query does not involve the
--   (polymorphic) type of the term argument. In the definition of
--   <a>gmapQl</a> we simply use the plain constant type constructor
--   because <a>gfoldl</a> is left-associative anyway and so it is readily
--   suited to fold a left-associative binary operation over the immediate
--   subterms. In the definition of gmapQr, extra effort is needed. We use
--   a higher-order accumulation trick to mediate between left-associative
--   constructor application vs. right-associative binary operation (e.g.,
--   <tt>(:)</tt>). When the query is meant to compute a value of type
--   <tt>r</tt>, then the result type withing generic folding is <tt>r
--   -&gt; r</tt>. So the result of folding is a function to which we
--   finally pass the right unit.
--   
--   With the <tt>-XDeriveDataTypeable</tt> option, GHC can generate
--   instances of the <a>Data</a> class automatically. For example, given
--   the declaration
--   
--   <pre>
--   data T a b = C1 a b | C2 deriving (Typeable, Data)
--   </pre>
--   
--   GHC will generate an instance that is equivalent to
--   
--   <pre>
--   instance (Data a, Data b) =&gt; Data (T a b) where
--       gfoldl k z (C1 a b) = z C1 `k` a `k` b
--       gfoldl k z C2       = z C2
--   
--       gunfold k z c = case constrIndex c of
--                           1 -&gt; k (k (z C1))
--                           2 -&gt; z C2
--   
--       toConstr (C1 _ _) = con_C1
--       toConstr C2       = con_C2
--   
--       dataTypeOf _ = ty_T
--   
--   con_C1 = mkConstr ty_T "C1" [] Prefix
--   con_C2 = mkConstr ty_T "C2" [] Prefix
--   ty_T   = mkDataType "Module.T" [con_C1, con_C2]
--   </pre>
--   
--   This is suitable for datatypes that are exported transparently.
class Typeable a => Data a where gfoldl _ z = z dataCast1 _ = Nothing dataCast2 _ = Nothing gmapT f x0 = unID (gfoldl k ID x0) where k :: Data d => ID (d -> b) -> d -> ID b k (ID c) x = ID (c (f x)) gmapQl o r f = unCONST . gfoldl k z where k :: Data d => CONST r (d -> b) -> d -> CONST r b k c x = CONST $ (unCONST c) `o` f x z :: g -> CONST r g z _ = CONST r gmapQr o r0 f x0 = unQr (gfoldl k (const (Qr id)) x0) r0 where k :: Data d => Qr r (d -> b) -> d -> Qr r b k (Qr c) x = Qr (\ r -> c (f x `o` r)) gmapQ f = gmapQr (:) [] f gmapQi i f x = case gfoldl k z x of { Qi _ q -> fromJust q } where k :: Data d => Qi u (d -> b) -> d -> Qi u b k (Qi i' q) a = Qi (i' + 1) (if i == i' then Just (f a) else q) z :: g -> Qi q g z _ = Qi 0 Nothing gmapM f = gfoldl k return where k :: Data d => m (d -> b) -> d -> m b k c x = do { c' <- c; x' <- f x; return (c' x') } gmapMp f x = unMp (gfoldl k z x) >>= \ (x', b) -> if b then return x' else mzero where z :: g -> Mp m g z g = Mp (return (g, False)) k :: Data d => Mp m (d -> b) -> d -> Mp m b k (Mp c) y = Mp (c >>= \ (h, b) -> (f y >>= \ y' -> return (h y', True)) `mplus` return (h y, b)) gmapMo f x = unMp (gfoldl k z x) >>= \ (x', b) -> if b then return x' else mzero where z :: g -> Mp m g z g = Mp (return (g, False)) k :: Data d => Mp m (d -> b) -> d -> Mp m b k (Mp c) y = Mp (c >>= \ (h, b) -> if b then return (h y, b) else (f y >>= \ y' -> return (h y', True)) `mplus` return (h y, b))
gfoldl :: Data a => (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> a -> c a
gunfold :: Data a => (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c a
toConstr :: Data a => a -> Constr
dataTypeOf :: Data a => a -> DataType
dataCast1 :: (Data a, Typeable1 t) => (forall d. Data d => c (t d)) -> Maybe (c a)
dataCast2 :: (Data a, Typeable2 t) => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c a)
gmapT :: Data a => (forall b. Data b => b -> b) -> a -> a
gmapQl :: Data a => (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> a -> r
gmapQr :: Data a => (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> a -> r
gmapQ :: Data a => (forall d. Data d => d -> u) -> a -> [u]
gmapQi :: Data a => Int -> (forall d. Data d => d -> u) -> a -> u
gmapM :: (Data a, Monad m) => (forall d. Data d => d -> m d) -> a -> m a
gmapMp :: (Data a, MonadPlus m) => (forall d. Data d => d -> m d) -> a -> m a
gmapMo :: (Data a, MonadPlus m) => (forall d. Data d => d -> m d) -> a -> m a

-- | Representation of datatypes. A package of constructor representations
--   with names of type and module.
data DataType

-- | Constructs an algebraic datatype
mkDataType :: String -> [Constr] -> DataType

-- | Constructs the <a>Int</a> type
mkIntType :: String -> DataType

-- | Constructs the <a>Float</a> type
mkFloatType :: String -> DataType

-- | This function is now deprecated. Please use <a>mkCharType</a> instead.

-- | <i>Deprecated: Use mkCharType instead </i>
mkStringType :: String -> DataType

-- | Constructs the <a>Char</a> type
mkCharType :: String -> DataType

-- | Constructs a non-representation for a non-presentable type
mkNoRepType :: String -> DataType

-- | Deprecated version (misnamed)

-- | <i>Deprecated: Use mkNoRepType instead </i>
mkNorepType :: String -> DataType

-- | Gets the type constructor including the module
dataTypeName :: DataType -> String

-- | Public representation of datatypes
data DataRep
AlgRep :: [Constr] -> DataRep
IntRep :: DataRep
FloatRep :: DataRep
CharRep :: DataRep
NoRep :: DataRep

-- | Gets the public presentation of a datatype
dataTypeRep :: DataType -> DataRep

-- | Look up a constructor by its representation
repConstr :: DataType -> ConstrRep -> Constr

-- | Test for an algebraic type
isAlgType :: DataType -> Bool

-- | Gets the constructors of an algebraic datatype
dataTypeConstrs :: DataType -> [Constr]

-- | Gets the constructor for an index (algebraic datatypes only)
indexConstr :: DataType -> ConIndex -> Constr

-- | Gets the maximum constructor index of an algebraic datatype
maxConstrIndex :: DataType -> ConIndex

-- | Test for a non-representable type
isNorepType :: DataType -> Bool

-- | Representation of constructors. Note that equality on constructors
--   with different types may not work -- i.e. the constructors for
--   <a>False</a> and <a>Nothing</a> may compare equal.
data Constr

-- | Unique index for datatype constructors, counting from 1 in the order
--   they are given in the program text.
type ConIndex = Int

-- | Fixity of constructors
data Fixity
Prefix :: Fixity
Infix :: Fixity

-- | Constructs a constructor
mkConstr :: DataType -> String -> [String] -> Fixity -> Constr

-- | This function is now deprecated. Please use <a>mkIntegralConstr</a>
--   instead.

-- | <i>Deprecated: Use mkIntegralConstr instead </i>
mkIntConstr :: DataType -> Integer -> Constr

-- | This function is now deprecated. Please use <a>mkRealConstr</a>
--   instead.

-- | <i>Deprecated: Use mkRealConstr instead </i>
mkFloatConstr :: DataType -> Double -> Constr
mkIntegralConstr :: (Integral a, Show a) => DataType -> a -> Constr
mkRealConstr :: (Real a, Show a) => DataType -> a -> Constr

-- | This function is now deprecated. Please use <a>mkCharConstr</a>
--   instead.

-- | <i>Deprecated: Use mkCharConstr instead </i>
mkStringConstr :: DataType -> String -> Constr

-- | Makes a constructor for <a>Char</a>.
mkCharConstr :: DataType -> Char -> Constr

-- | Gets the datatype of a constructor
constrType :: Constr -> DataType

-- | Public representation of constructors
data ConstrRep
AlgConstr :: ConIndex -> ConstrRep
IntConstr :: Integer -> ConstrRep
FloatConstr :: Rational -> ConstrRep
CharConstr :: Char -> ConstrRep

-- | Gets the public presentation of constructors
constrRep :: Constr -> ConstrRep

-- | Gets the field labels of a constructor. The list of labels is returned
--   in the same order as they were given in the original constructor
--   declaration.
constrFields :: Constr -> [String]

-- | Gets the fixity of a constructor
constrFixity :: Constr -> Fixity

-- | Gets the index of a constructor (algebraic datatypes only)
constrIndex :: Constr -> ConIndex

-- | Gets the string for a constructor
showConstr :: Constr -> String

-- | Lookup a constructor via a string
readConstr :: DataType -> String -> Maybe Constr

-- | Gets the unqualified type constructor: drop *.*.*... before name
tyconUQname :: String -> String

-- | Gets the module of a type constructor: take *.*.*... before name
tyconModule :: String -> String

-- | Build a term skeleton
fromConstr :: Data a => Constr -> a

-- | Build a term and use a generic function for subterms
fromConstrB :: Data a => (forall d. Data d => d) -> Constr -> a

-- | Monadic variation on <a>fromConstrB</a>
fromConstrM :: (Monad m, Data a) => (forall d. Data d => m d) -> Constr -> m a
instance Eq ConstrRep
instance Show ConstrRep
instance Eq Fixity
instance Show Fixity
instance Show DataType
instance Eq DataRep
instance Show DataRep
instance (Typeable a, Data b, Ix a) => Data (Array a b)
instance Typeable a => Data (ForeignPtr a)
instance Typeable a => Data (Ptr a)
instance (Data a, Data b, Data c, Data d, Data e, Data f, Data g) => Data (a, b, c, d, e, f, g)
instance (Data a, Data b, Data c, Data d, Data e, Data f) => Data (a, b, c, d, e, f)
instance (Data a, Data b, Data c, Data d, Data e) => Data (a, b, c, d, e)
instance (Data a, Data b, Data c, Data d) => Data (a, b, c, d)
instance (Data a, Data b, Data c) => Data (a, b, c)
instance (Data a, Data b) => Data (a, b)
instance Data ()
instance (Data a, Data b) => Data (Either a b)
instance Data Ordering
instance Data a => Data (Maybe a)
instance Data a => Data [a]
instance (Data a, Integral a) => Data (Ratio a)
instance Data Word64
instance Data Word32
instance Data Word16
instance Data Word8
instance Data Word
instance Data Int64
instance Data Int32
instance Data Int16
instance Data Int8
instance Data Integer
instance Data Int
instance Data Double
instance Data Float
instance Data Char
instance Data Bool
instance Eq Constr
instance Show Constr


-- | Monadic zipping (used for monad comprehensions)
module Control.Monad.Zip

-- | <a>MonadZip</a> type class. Minimal definition: <a>mzip</a> or
--   <a>mzipWith</a>
--   
--   Instances should satisfy the laws:
--   
--   <ul>
--   <li>Naturality :</li>
--   </ul>
--   
--   <pre>
--   liftM (f *** g) (mzip ma mb) = mzip (liftM f ma) (liftM g mb)
--   </pre>
--   
--   <ul>
--   <li>Information Preservation:</li>
--   </ul>
--   
--   <pre>
--   liftM (const ()) ma = liftM (const ()) mb
--   ==&gt;
--   munzip (mzip ma mb) = (ma, mb)
--   </pre>
class Monad m => MonadZip m where mzip = mzipWith (,) mzipWith f ma mb = liftM (uncurry f) (mzip ma mb) munzip mab = (liftM fst mab, liftM snd mab)
mzip :: MonadZip m => m a -> m b -> m (a, b)
mzipWith :: MonadZip m => (a -> b -> c) -> m a -> m b -> m c
munzip :: MonadZip m => m (a, b) -> (m a, m b)
instance [safe] MonadZip []


-- | This module provides scalable event notification for file descriptors
--   and timeouts.
--   
--   This module should be considered GHC internal.
--   
--   <ul>
--   
--   <li>---------------------------------------------------------------------------</li>
--   </ul>
module GHC.Event

-- | The event manager state.
data EventManager

-- | Create a new event manager.
new :: IO EventManager

-- | Retrieve the system event manager.
--   
--   This function always returns <a>Just</a> the system event manager when
--   using the threaded RTS and <a>Nothing</a> otherwise.
getSystemEventManager :: IO (Maybe EventManager)

-- | Start handling events. This function loops until told to stop, using
--   <a>shutdown</a>.
--   
--   <i>Note</i>: This loop can only be run once per <a>EventManager</a>,
--   as it closes all of its control resources when it finishes.
loop :: EventManager -> IO ()
step :: EventManager -> TimeoutQueue -> IO (Bool, TimeoutQueue)

-- | Asynchronously shuts down the event manager, if running.
shutdown :: EventManager -> IO ()

-- | An I/O event.
data Event

-- | Data is available to be read.
evtRead :: Event

-- | The file descriptor is ready to accept a write.
evtWrite :: Event

-- | Callback invoked on I/O events.
type IOCallback = FdKey -> Event -> IO ()

-- | A file descriptor registration cookie.
data FdKey

-- | <tt>registerFd mgr cb fd evs</tt> registers interest in the events
--   <tt>evs</tt> on the file descriptor <tt>fd</tt>. <tt>cb</tt> is called
--   for each event that occurs. Returns a cookie that can be handed to
--   <a>unregisterFd</a>.
registerFd :: EventManager -> IOCallback -> Fd -> Event -> IO FdKey

-- | Register interest in the given events, without waking the event
--   manager thread. The <a>Bool</a> return value indicates whether the
--   event manager ought to be woken.
registerFd_ :: EventManager -> IOCallback -> Fd -> Event -> IO (FdKey, Bool)

-- | Drop a previous file descriptor registration.
unregisterFd :: EventManager -> FdKey -> IO ()

-- | Drop a previous file descriptor registration, without waking the event
--   manager thread. The return value indicates whether the event manager
--   ought to be woken.
unregisterFd_ :: EventManager -> FdKey -> IO Bool

-- | Close a file descriptor in a race-safe way.
closeFd :: EventManager -> (Fd -> IO ()) -> Fd -> IO ()

-- | Callback invoked on timeout events.
type TimeoutCallback = IO ()

-- | A timeout registration cookie.
data TimeoutKey

-- | Register a timeout in the given number of microseconds. The returned
--   <a>TimeoutKey</a> can be used to later unregister or update the
--   timeout. The timeout is automatically unregistered after the given
--   time has passed.
registerTimeout :: EventManager -> Int -> TimeoutCallback -> IO TimeoutKey

-- | Update an active timeout to fire in the given number of microseconds.
updateTimeout :: EventManager -> TimeoutKey -> Int -> IO ()

-- | Unregister an active timeout.
unregisterTimeout :: EventManager -> TimeoutKey -> IO ()


-- | NB. the contents of this module are only available on Windows.
--   
--   Installing Win32 console handlers.
module GHC.ConsoleHandler

module GHC.Constants
oFFSET_StgRegTable_rR1 :: Int
oFFSET_StgRegTable_rR2 :: Int
oFFSET_StgRegTable_rR3 :: Int
oFFSET_StgRegTable_rR4 :: Int
oFFSET_StgRegTable_rR5 :: Int
oFFSET_StgRegTable_rR6 :: Int
oFFSET_StgRegTable_rR7 :: Int
oFFSET_StgRegTable_rR8 :: Int
oFFSET_StgRegTable_rR9 :: Int
oFFSET_StgRegTable_rR10 :: Int
oFFSET_StgRegTable_rF1 :: Int
oFFSET_StgRegTable_rF2 :: Int
oFFSET_StgRegTable_rF3 :: Int
oFFSET_StgRegTable_rF4 :: Int
oFFSET_StgRegTable_rD1 :: Int
oFFSET_StgRegTable_rD2 :: Int
oFFSET_StgRegTable_rL1 :: Int
oFFSET_StgRegTable_rSp :: Int
oFFSET_StgRegTable_rSpLim :: Int
oFFSET_StgRegTable_rHp :: Int
oFFSET_StgRegTable_rHpLim :: Int
oFFSET_StgRegTable_rCCCS :: Int
oFFSET_StgRegTable_rCurrentTSO :: Int
oFFSET_StgRegTable_rCurrentNursery :: Int
oFFSET_StgRegTable_rHpAlloc :: Int
oFFSET_StgRegTable_rRet :: Int
oFFSET_StgRegTable_rNursery :: Int
oFFSET_stgEagerBlackholeInfo :: Int
oFFSET_stgGCEnter1 :: Int
oFFSET_stgGCFun :: Int
oFFSET_Capability_r :: Int
oFFSET_Capability_lock :: Int
oFFSET_Capability_no :: Int
oFFSET_Capability_mut_lists :: Int
oFFSET_Capability_context_switch :: Int
oFFSET_Capability_interrupt :: Int
oFFSET_Capability_sparks :: Int
oFFSET_bdescr_start :: Int
oFFSET_bdescr_free :: Int
oFFSET_bdescr_blocks :: Int
oFFSET_bdescr_gen_no :: Int
oFFSET_bdescr_link :: Int
sIZEOF_generation :: Int
oFFSET_generation_n_new_large_words :: Int
sIZEOF_CostCentreStack :: Int
oFFSET_CostCentreStack_ccsID :: Int
oFFSET_CostCentreStack_mem_alloc :: Int
oFFSET_CostCentreStack_scc_count :: Int
oFFSET_CostCentreStack_prevStack :: Int
oFFSET_CostCentre_ccID :: Int
oFFSET_CostCentre_link :: Int
oFFSET_StgHeader_info :: Int
oFFSET_StgHeader_ccs :: Int
oFFSET_StgHeader_ldvw :: Int
sIZEOF_StgSMPThunkHeader :: Int
oFFSET_StgClosure_payload :: Int
oFFSET_StgEntCounter_allocs :: Int
oFFSET_StgEntCounter_registeredp :: Int
oFFSET_StgEntCounter_link :: Int
oFFSET_StgEntCounter_entry_count :: Int
sIZEOF_StgUpdateFrame_NoHdr :: Int
sIZEOF_StgCatchFrame_NoHdr :: Int
sIZEOF_StgStopFrame_NoHdr :: Int
sIZEOF_StgMutArrPtrs_NoHdr :: Int
oFFSET_StgMutArrPtrs_ptrs :: Int
oFFSET_StgMutArrPtrs_size :: Int
sIZEOF_StgArrWords_NoHdr :: Int
oFFSET_StgArrWords_bytes :: Int
oFFSET_StgArrWords_payload :: Int
oFFSET_StgTSO__link :: Int
oFFSET_StgTSO_global_link :: Int
oFFSET_StgTSO_what_next :: Int
oFFSET_StgTSO_why_blocked :: Int
oFFSET_StgTSO_block_info :: Int
oFFSET_StgTSO_blocked_exceptions :: Int
oFFSET_StgTSO_id :: Int
oFFSET_StgTSO_cap :: Int
oFFSET_StgTSO_saved_errno :: Int
oFFSET_StgTSO_trec :: Int
oFFSET_StgTSO_flags :: Int
oFFSET_StgTSO_dirty :: Int
oFFSET_StgTSO_bq :: Int
oFFSET_StgTSO_cccs :: Int
oFFSET_StgTSO_stackobj :: Int
oFFSET_StgStack_sp :: Int
oFFSET_StgStack_stack :: Int
oFFSET_StgStack_stack_size :: Int
oFFSET_StgStack_dirty :: Int
sIZEOF_StgTSOProfInfo :: Int
oFFSET_StgUpdateFrame_updatee :: Int
oFFSET_StgCatchFrame_handler :: Int
oFFSET_StgCatchFrame_exceptions_blocked :: Int
sIZEOF_StgPAP_NoHdr :: Int
oFFSET_StgPAP_n_args :: Int
oFFSET_StgPAP_fun :: Int
oFFSET_StgPAP_arity :: Int
oFFSET_StgPAP_payload :: Int
sIZEOF_StgAP_NoThunkHdr :: Int
sIZEOF_StgAP_NoHdr :: Int
oFFSET_StgAP_n_args :: Int
oFFSET_StgAP_fun :: Int
oFFSET_StgAP_payload :: Int
sIZEOF_StgAP_STACK_NoThunkHdr :: Int
sIZEOF_StgAP_STACK_NoHdr :: Int
oFFSET_StgAP_STACK_size :: Int
oFFSET_StgAP_STACK_fun :: Int
oFFSET_StgAP_STACK_payload :: Int
sIZEOF_StgSelector_NoThunkHdr :: Int
sIZEOF_StgSelector_NoHdr :: Int
oFFSET_StgInd_indirectee :: Int
sIZEOF_StgMutVar_NoHdr :: Int
oFFSET_StgMutVar_var :: Int
sIZEOF_StgAtomicallyFrame_NoHdr :: Int
oFFSET_StgAtomicallyFrame_code :: Int
oFFSET_StgAtomicallyFrame_next_invariant_to_check :: Int
oFFSET_StgAtomicallyFrame_result :: Int
oFFSET_StgInvariantCheckQueue_invariant :: Int
oFFSET_StgInvariantCheckQueue_my_execution :: Int
oFFSET_StgInvariantCheckQueue_next_queue_entry :: Int
oFFSET_StgAtomicInvariant_code :: Int
oFFSET_StgTRecHeader_enclosing_trec :: Int
sIZEOF_StgCatchSTMFrame_NoHdr :: Int
oFFSET_StgCatchSTMFrame_handler :: Int
oFFSET_StgCatchSTMFrame_code :: Int
sIZEOF_StgCatchRetryFrame_NoHdr :: Int
oFFSET_StgCatchRetryFrame_running_alt_code :: Int
oFFSET_StgCatchRetryFrame_first_code :: Int
oFFSET_StgCatchRetryFrame_alt_code :: Int
oFFSET_StgTVarWatchQueue_closure :: Int
oFFSET_StgTVarWatchQueue_next_queue_entry :: Int
oFFSET_StgTVarWatchQueue_prev_queue_entry :: Int
oFFSET_StgTVar_current_value :: Int
sIZEOF_StgWeak_NoHdr :: Int
oFFSET_StgWeak_link :: Int
oFFSET_StgWeak_key :: Int
oFFSET_StgWeak_value :: Int
oFFSET_StgWeak_finalizer :: Int
oFFSET_StgWeak_cfinalizer :: Int
sIZEOF_StgDeadWeak_NoHdr :: Int
oFFSET_StgDeadWeak_link :: Int
sIZEOF_StgMVar_NoHdr :: Int
oFFSET_StgMVar_head :: Int
oFFSET_StgMVar_tail :: Int
oFFSET_StgMVar_value :: Int
sIZEOF_StgMVarTSOQueue_NoHdr :: Int
oFFSET_StgMVarTSOQueue_link :: Int
oFFSET_StgMVarTSOQueue_tso :: Int
sIZEOF_StgBCO_NoHdr :: Int
oFFSET_StgBCO_instrs :: Int
oFFSET_StgBCO_literals :: Int
oFFSET_StgBCO_ptrs :: Int
oFFSET_StgBCO_arity :: Int
oFFSET_StgBCO_size :: Int
oFFSET_StgBCO_bitmap :: Int
sIZEOF_StgStableName_NoHdr :: Int
oFFSET_StgStableName_sn :: Int
sIZEOF_StgBlockingQueue_NoHdr :: Int
oFFSET_StgBlockingQueue_bh :: Int
oFFSET_StgBlockingQueue_owner :: Int
oFFSET_StgBlockingQueue_queue :: Int
oFFSET_StgBlockingQueue_link :: Int
sIZEOF_MessageBlackHole_NoHdr :: Int
oFFSET_MessageBlackHole_link :: Int
oFFSET_MessageBlackHole_tso :: Int
oFFSET_MessageBlackHole_bh :: Int
oFFSET_RtsFlags_ProfFlags_showCCSOnException :: Int
oFFSET_RtsFlags_DebugFlags_apply :: Int
oFFSET_RtsFlags_DebugFlags_sanity :: Int
oFFSET_RtsFlags_DebugFlags_weak :: Int
oFFSET_RtsFlags_GcFlags_initialStkSize :: Int
oFFSET_RtsFlags_MiscFlags_tickInterval :: Int
sIZEOF_StgFunInfoExtraFwd :: Int
oFFSET_StgFunInfoExtraFwd_slow_apply :: Int
oFFSET_StgFunInfoExtraFwd_fun_type :: Int
oFFSET_StgFunInfoExtraFwd_arity :: Int
oFFSET_StgFunInfoExtraFwd_bitmap :: Int
sIZEOF_StgFunInfoExtraRev :: Int
oFFSET_StgFunInfoExtraRev_slow_apply_offset :: Int
oFFSET_StgFunInfoExtraRev_fun_type :: Int
oFFSET_StgFunInfoExtraRev_arity :: Int
oFFSET_StgFunInfoExtraRev_bitmap :: Int
oFFSET_StgLargeBitmap_size :: Int
oFFSET_StgLargeBitmap_bitmap :: Int
sIZEOF_snEntry :: Int
oFFSET_snEntry_sn_obj :: Int
oFFSET_snEntry_addr :: Int
mAX_TUPLE_SIZE :: Int
mAX_CONTEXT_REDUCTION_DEPTH :: Int
mAX_SPEC_THUNK_SIZE :: Int
mAX_SPEC_FUN_SIZE :: Int
mAX_SPEC_CONSTR_SIZE :: Int
mAX_SPEC_SELECTEE_SIZE :: Int
mAX_SPEC_AP_SIZE :: Int
mIN_PAYLOAD_SIZE :: Int
mIN_INTLIKE :: Int
mAX_INTLIKE :: Int
mIN_CHARLIKE :: Int
mAX_CHARLIKE :: Int
mUT_ARR_PTRS_CARD_BITS :: Int
mAX_Vanilla_REG :: Int
mAX_Float_REG :: Int
mAX_Double_REG :: Int
mAX_Long_REG :: Int
mAX_Real_Vanilla_REG :: Int
mAX_Real_Float_REG :: Int
mAX_Real_Double_REG :: Int
mAX_Real_Long_REG :: Int
sTD_HDR_SIZE :: Int
pROF_HDR_SIZE :: Int
dOUBLE_SIZE :: Int
wORD64_SIZE :: Int
iNT64_SIZE :: Int
rESERVED_C_STACK_BYTES :: Int
rESERVED_STACK_WORDS :: Int
aP_STACK_SPLIM :: Int
wORD_SIZE :: Int
wORD_SIZE_IN_BITS :: Int
type TargetInt = Int32
type TargetWord = Word32
tARGET_MIN_INT :: Integer
tARGET_MAX_WORD :: Integer
tARGET_MAX_INT :: Integer
tARGET_MAX_CHAR :: Int
tAG_BITS :: Int
tAG_MASK :: Int
mAX_PTR_TAG :: Int
cINT_SIZE :: Int
cLONG_SIZE :: Int
cLONG_LONG_SIZE :: Int
bLOCK_SIZE :: Int
bLOCK_SIZE_W :: Int
bLOCKS_PER_MBLOCK :: Int
bITMAP_BITS_SHIFT :: Int


module Control.Category

-- | A class for categories. id and (.) must form a monoid.
class Category cat
id :: Category cat => cat a a
(.) :: Category cat => cat b c -> cat a b -> cat a c

-- | Right-to-left composition
(<<<) :: Category cat => cat b c -> cat a b -> cat a c

-- | Left-to-right composition
(>>>) :: Category cat => cat a b -> cat b c -> cat a c
instance Category (->)

module GHC.Environment
getFullArgs :: IO [String]


-- | Access to GHC's call-stack simulation
module GHC.Stack

-- | returns a '[String]' representing the current call stack. This can be
--   useful for debugging.
--   
--   The implementation uses the call-stack simulation maintined by the
--   profiler, so it only works if the program was compiled with
--   <tt>-prof</tt> and contains suitable SCC annotations (e.g. by using
--   <tt>-fprof-auto</tt>). Otherwise, the list returned is likely to be
--   empty or uninformative.
currentCallStack :: IO [String]
whoCreated :: a -> IO [String]
data CostCentreStack
data CostCentre
getCurrentCCS :: dummy -> IO (Ptr CostCentreStack)
getCCSOf :: a -> IO (Ptr CostCentreStack)
ccsCC :: Ptr CostCentreStack -> IO (Ptr CostCentre)
ccsParent :: Ptr CostCentreStack -> IO (Ptr CostCentreStack)
ccLabel :: Ptr CostCentre -> IO CString
ccModule :: Ptr CostCentre -> IO CString
ccSrcSpan :: Ptr CostCentre -> IO CString
ccsToStrings :: Ptr CostCentreStack -> IO [String]
renderStack :: [String] -> String


-- | Functions for tracing and monitoring execution.
--   
--   These can be useful for investigating bugs or performance problems.
--   They should <i>not</i> be used in production code.
module Debug.Trace

-- | The <a>trace</a> function outputs the trace message given as its first
--   argument, before returning the second argument as its result.
--   
--   For example, this returns the value of <tt>f x</tt> but first outputs
--   the message.
--   
--   <pre>
--   trace ("calling f with x = " ++ show x) (f x)
--   </pre>
--   
--   The <a>trace</a> function should <i>only</i> be used for debugging, or
--   for monitoring execution. The function is not referentially
--   transparent: its type indicates that it is a pure function but it has
--   the side effect of outputting the trace message.
trace :: String -> a -> a

-- | Like <a>trace</a>, but uses <a>show</a> on the argument to convert it
--   to a <a>String</a>.
--   
--   This makes it convenient for printing the values of interesting
--   variables or expressions inside a function. For example here we print
--   the value of the variables <tt>x</tt> and <tt>z</tt>:
--   
--   <pre>
--   f x y =
--       traceShow (x, z) $ result
--     where
--       z = ...
--       ...
--   </pre>
traceShow :: Show a => a -> b -> b

-- | like <a>trace</a>, but additionally prints a call stack if one is
--   available.
--   
--   In the current GHC implementation, the call stack is only availble if
--   the program was compiled with <tt>-prof</tt>; otherwise
--   <a>traceStack</a> behaves exactly like <a>trace</a>. Entries in the
--   call stack correspond to <tt>SCC</tt> annotations, so it is a good
--   idea to use <tt>-fprof-auto</tt> or <tt>-fprof-auto-calls</tt> to add
--   SCC annotations automatically.
traceStack :: String -> a -> a

-- | The <a>traceIO</a> function outputs the trace message from the IO
--   monad. This sequences the output with respect to other IO actions.
traceIO :: String -> IO ()

-- | Deprecated. Use <a>traceIO</a>.

-- | <i>Deprecated: Use Debug.Trace.traceIO </i>
putTraceMsg :: String -> IO ()

-- | The <a>traceEvent</a> function behaves like <a>trace</a> with the
--   difference that the message is emitted to the eventlog, if eventlog
--   profiling is available and enabled at runtime.
--   
--   It is suitable for use in pure code. In an IO context use
--   <a>traceEventIO</a> instead.
--   
--   Note that when using GHC's SMP runtime, it is possible (but rare) to
--   get duplicate events emitted if two CPUs simultaneously evaluate the
--   same thunk that uses <a>traceEvent</a>.
traceEvent :: String -> a -> a

-- | The <a>traceEventIO</a> function emits a message to the eventlog, if
--   eventlog profiling is available and enabled at runtime.
--   
--   Compared to <a>traceEvent</a>, <a>traceEventIO</a> sequences the event
--   with respect to other IO actions.
traceEventIO :: String -> IO ()


-- | GHC Extensions: this is the Approved Way to get at GHC-specific
--   extensions.
--   
--   Note: no other base module should import this module.
module GHC.Exts

-- | A fixed-precision integer type with at least the range <tt>[-2^29 ..
--   2^29-1]</tt>. The exact range for a given implementation can be
--   determined by using <a>minBound</a> and <a>maxBound</a> from the
--   <a>Bounded</a> class.
data Int :: *
I# :: Int# -> Int

-- | A <a>Word</a> is an unsigned integral type, with the same size as
--   <a>Int</a>.
data Word :: *
W# :: Word# -> Word

-- | Single-precision floating point numbers. It is desirable that this
--   type be at least equal in range and precision to the IEEE
--   single-precision type.
data Float :: *
F# :: Float# -> Float

-- | Double-precision floating point numbers. It is desirable that this
--   type be at least equal in range and precision to the IEEE
--   double-precision type.
data Double :: *
D# :: Double# -> Double

-- | The character type <a>Char</a> is an enumeration whose values
--   represent Unicode (or equivalently ISO/IEC 10646) characters (see
--   <a>http://www.unicode.org/</a> for details). This set extends the ISO
--   8859-1 (Latin-1) character set (the first 256 characters), which is
--   itself an extension of the ASCII character set (the first 128
--   characters). A character literal in Haskell has type <a>Char</a>.
--   
--   To convert a <a>Char</a> to or from the corresponding <a>Int</a> value
--   defined by Unicode, use <a>toEnum</a> and <a>fromEnum</a> from the
--   <a>Enum</a> class respectively (or equivalently <tt>ord</tt> and
--   <tt>chr</tt>).
data Char :: *
C# :: Char# -> Char

-- | A value of type <tt><a>Ptr</a> a</tt> represents a pointer to an
--   object, or an array of objects, which may be marshalled to or from
--   Haskell values of type <tt>a</tt>.
--   
--   The type <tt>a</tt> will often be an instance of class <a>Storable</a>
--   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 <tt>struct</tt>.
data Ptr a
Ptr :: Addr# -> Ptr a

-- | A value of type <tt><a>FunPtr</a> a</tt> is a pointer to a function
--   callable from foreign code. The type <tt>a</tt> will normally be a
--   <i>foreign type</i>, a function type with zero or more arguments where
--   
--   <ul>
--   <li>the argument types are <i>marshallable foreign types</i>, i.e.
--   <a>Char</a>, <a>Int</a>, <a>Double</a>, <a>Float</a>, <a>Bool</a>,
--   <a>Int8</a>, <a>Int16</a>, <a>Int32</a>, <a>Int64</a>, <a>Word8</a>,
--   <a>Word16</a>, <a>Word32</a>, <a>Word64</a>, <tt><a>Ptr</a> a</tt>,
--   <tt><a>FunPtr</a> a</tt>, <tt><a>StablePtr</a> a</tt> or a renaming of
--   any of these using <tt>newtype</tt>.</li>
--   <li>the return type is either a marshallable foreign type or has the
--   form <tt><a>IO</a> t</tt> where <tt>t</tt> is a marshallable foreign
--   type or <tt>()</tt>.</li>
--   </ul>
--   
--   A value of type <tt><a>FunPtr</a> a</tt> may be a pointer to a foreign
--   function, either returned by another foreign function or imported with
--   a a static address import like
--   
--   <pre>
--   foreign import ccall "stdlib.h &amp;free"
--     p_free :: FunPtr (Ptr a -&gt; IO ())
--   </pre>
--   
--   or a pointer to a Haskell function created using a <i>wrapper</i> stub
--   declared to produce a <a>FunPtr</a> of the correct type. For example:
--   
--   <pre>
--   type Compare = Int -&gt; Int -&gt; Bool
--   foreign import ccall "wrapper"
--     mkCompare :: Compare -&gt; IO (FunPtr Compare)
--   </pre>
--   
--   Calls to wrapper stubs like <tt>mkCompare</tt> allocate storage, which
--   should be released with <a>freeHaskellFunPtr</a> when no longer
--   required.
--   
--   To convert <a>FunPtr</a> values to corresponding Haskell functions,
--   one can define a <i>dynamic</i> stub for the specific foreign type,
--   e.g.
--   
--   <pre>
--   type IntFunction = CInt -&gt; IO ()
--   foreign import ccall "dynamic" 
--     mkFun :: FunPtr IntFunction -&gt; IntFunction
--   </pre>
data FunPtr a
FunPtr :: Addr# -> FunPtr a
maxTupleSize :: Int

-- | Shift the argument left by the specified number of bits (which must be
--   non-negative).
shiftL# :: Word# -> Int# -> Word#

-- | Shift the argument right by the specified number of bits (which must
--   be non-negative).
shiftRL# :: Word# -> Int# -> Word#

-- | Shift the argument left by the specified number of bits (which must be
--   non-negative).
iShiftL# :: Int# -> Int# -> Int#

-- | Shift the argument right (signed) by the specified number of bits
--   (which must be non-negative).
iShiftRA# :: Int# -> Int# -> Int#

-- | Shift the argument right (unsigned) by the specified number of bits
--   (which must be non-negative).
iShiftRL# :: Int# -> Int# -> Int#
uncheckedShiftL64# :: Word64# -> Int# -> Word64#
uncheckedShiftRL64# :: Word64# -> Int# -> Word64#
uncheckedIShiftL64# :: Int64# -> Int# -> Int64#
uncheckedIShiftRA64# :: Int64# -> Int# -> Int64#

-- | A list producer that can be fused with <a>foldr</a>. This function is
--   merely
--   
--   <pre>
--   build g = g (:) []
--   </pre>
--   
--   but GHC's simplifier will transform an expression of the form
--   <tt><a>foldr</a> k z (<a>build</a> g)</tt>, which may arise after
--   inlining, to <tt>g k z</tt>, which avoids producing an intermediate
--   list.
build :: (forall b. (a -> b -> b) -> b -> b) -> [a]

-- | A list producer that can be fused with <a>foldr</a>. This function is
--   merely
--   
--   <pre>
--   augment g xs = g (:) xs
--   </pre>
--   
--   but GHC's simplifier will transform an expression of the form
--   <tt><a>foldr</a> k z (<a>augment</a> g xs)</tt>, which may arise after
--   inlining, to <tt>g k (<a>foldr</a> k z xs)</tt>, which avoids
--   producing an intermediate list.
augment :: (forall b. (a -> b -> b) -> b -> b) -> [a] -> [a]

-- | Class for string-like datastructures; used by the overloaded string
--   extension (-foverloaded-strings in GHC).
class IsString a
fromString :: IsString a => String -> a
breakpoint :: a -> a
breakpointCond :: Bool -> a -> a

-- | The call '(lazy e)' means the same as <tt>e</tt>, but <a>lazy</a> has
--   a magical strictness property: it is lazy in its first argument, even
--   though its semantics is strict.
lazy :: a -> a

-- | The call '(inline f)' reduces to <tt>f</tt>, but <a>inline</a> has a
--   BuiltInRule that tries to inline <tt>f</tt> (if it has an unfolding)
--   unconditionally The <tt>NOINLINE</tt> pragma arranges that inline only
--   gets inlined (and hence eliminated) late in compilation, after the
--   rule has had a good chance to fire.
inline :: a -> a

-- | The <a>Down</a> type allows you to reverse sort order conveniently. A
--   value of type <tt><a>Down</a> a</tt> contains a value of type
--   <tt>a</tt> (represented as <tt><a>Down</a> a</tt>). If <tt>a</tt> has
--   an <tt><a>Ord</a></tt> instance associated with it then comparing two
--   values thus wrapped will give you the opposite of their normal sort
--   order. This is particularly useful when sorting in generalised list
--   comprehensions, as in: <tt>then sortWith by <a>Down</a> x</tt>
newtype Down a
Down :: a -> Down a

-- | The <a>groupWith</a> function uses the user supplied function which
--   projects an element out of every list element in order to first sort
--   the input list and then to form groups by equality on these projected
--   elements
groupWith :: Ord b => (a -> b) -> [a] -> [[a]]

-- | The <a>sortWith</a> function sorts a list of elements using the user
--   supplied function to project something out of each element
sortWith :: Ord b => (a -> b) -> [a] -> [a]

-- | <a>the</a> ensures that all the elements of the list are identical and
--   then returns that unique element
the :: Eq a => [a] -> a

-- | <i>Deprecated: Use Debug.Trace.traceEvent or Debug.Trace.traceEventIO
--   </i>
traceEvent :: String -> IO ()
data SpecConstrAnnotation
NoSpecConstr :: SpecConstrAnnotation
ForceSpecConstr :: SpecConstrAnnotation

-- | returns a '[String]' representing the current call stack. This can be
--   useful for debugging.
--   
--   The implementation uses the call-stack simulation maintined by the
--   profiler, so it only works if the program was compiled with
--   <tt>-prof</tt> and contains suitable SCC annotations (e.g. by using
--   <tt>-fprof-auto</tt>). Otherwise, the list returned is likely to be
--   empty or uninformative.
currentCallStack :: IO [String]
data Constraint :: BOX
instance Typeable SpecConstrAnnotation
instance Data SpecConstrAnnotation
instance Eq SpecConstrAnnotation


-- | This module provides access to internal garbage collection and memory
--   usage statistics. These statistics are not available unless a program
--   is run with the <tt>-T</tt> RTS flag.
--   
--   This module is GHC-only and should not be considered portable.
module GHC.Stats

-- | Global garbage collection and memory statistics.
data GCStats
GCStats :: !Int64 -> !Int64 -> !Int64 -> !Int64 -> !Int64 -> !Int64 -> !Int64 -> !Int64 -> !Int64 -> !Int64 -> !Double -> !Double -> !Double -> !Double -> !Double -> !Double -> !Int64 -> !Int64 -> GCStats

-- | Total number of bytes allocated
bytesAllocated :: GCStats -> !Int64

-- | Number of garbage collections performed
numGcs :: GCStats -> !Int64

-- | Maximum number of live bytes seen so far
maxBytesUsed :: GCStats -> !Int64

-- | Number of byte usage samples taken | Sum of all byte usage samples,
--   can be used with <a>numByteUsageSamples</a> to calculate averages with
--   arbitrary weighting (if you are sampling this record multiple times).
numByteUsageSamples :: GCStats -> !Int64
cumulativeBytesUsed :: GCStats -> !Int64

-- | Number of bytes copied during GC
bytesCopied :: GCStats -> !Int64

-- | Current number of live bytes
currentBytesUsed :: GCStats -> !Int64

-- | Current number of bytes lost to slop
currentBytesSlop :: GCStats -> !Int64

-- | Maximum number of bytes lost to slop at any one time so far
maxBytesSlop :: GCStats -> !Int64

-- | Maximum number of megabytes allocated | CPU time spent running mutator
--   threads. This does not include any profiling overhead or
--   initialization.
peakMegabytesAllocated :: GCStats -> !Int64
mutatorCpuSeconds :: GCStats -> !Double

-- | Wall clock time spent running mutator threads. This does not include
--   initialization.
mutatorWallSeconds :: GCStats -> !Double

-- | CPU time spent running GC
gcCpuSeconds :: GCStats -> !Double

-- | Wall clock time spent running GC
gcWallSeconds :: GCStats -> !Double

-- | Total CPU time elapsed since program start
cpuSeconds :: GCStats -> !Double

-- | Total wall clock time elapsed since start | Number of bytes copied
--   during GC, minus space held by mutable lists held by the capabilities.
--   Can be used with <a>parMaxBytesCopied</a> to determine how well
--   parallel GC utilized all cores.
wallSeconds :: GCStats -> !Double
parTotBytesCopied :: GCStats -> !Int64

-- | Sum of number of bytes copied each GC by the most active GC thread
--   each GC. The ratio of <a>parTotBytesCopied</a> divided by
--   <a>parMaxBytesCopied</a> approaches 1 for a maximally sequential run
--   and approaches the number of threads (set by the RTS flag <tt>-N</tt>)
--   for a maximally parallel run.
parMaxBytesCopied :: GCStats -> !Int64

-- | Retrieves garbage collection and memory statistics as of the last
--   garbage collection. If you would like your statistics as recent as
--   possible, first run a <a>performGC</a>.
getGCStats :: IO GCStats
getGCStatsEnabled :: IO Bool
instance [safe] Show GCStats
instance [safe] Read GCStats


-- | An abstract interface to a unique symbol generator.
module Data.Unique

-- | An abstract unique object. Objects of type <a>Unique</a> may be
--   compared for equality and ordering and hashed into <a>Int</a>.
data Unique

-- | Creates a new object of type <a>Unique</a>. The value returned will
--   not compare equal to any other value of type <a>Unique</a> returned by
--   previous calls to <a>newUnique</a>. There is no limit on the number of
--   times <a>newUnique</a> may be called.
newUnique :: IO Unique

-- | Hashes a <a>Unique</a> into an <a>Int</a>. Two <a>Unique</a>s may hash
--   to the same value, although in practice this is unlikely. The
--   <a>Int</a> returned makes a good hash key.
hashUnique :: Unique -> Int
instance Typeable Unique
instance Eq Unique
instance Ord Unique


-- | Functors: uniform action over a parameterized type, generalizing the
--   <a>map</a> function on lists.
module Data.Functor

-- | The <a>Functor</a> class is used for types that can be mapped over.
--   Instances of <a>Functor</a> should satisfy the following laws:
--   
--   <pre>
--   fmap id  ==  id
--   fmap (f . g)  ==  fmap f . fmap g
--   </pre>
--   
--   The instances of <a>Functor</a> for lists, <a>Maybe</a> and <a>IO</a>
--   satisfy these laws.
class Functor f where <$ = fmap . const
fmap :: Functor f => (a -> b) -> f a -> f b
(<$) :: Functor f => a -> f b -> f a

-- | An infix synonym for <a>fmap</a>.
(<$>) :: Functor f => (a -> b) -> f a -> f b


-- | Unbounded channels.
module Control.Concurrent.Chan

-- | <a>Chan</a> is an abstract type representing an unbounded FIFO
--   channel.
data Chan a

-- | Build and returns a new instance of <a>Chan</a>.
newChan :: IO (Chan a)

-- | Write a value to a <a>Chan</a>.
writeChan :: Chan a -> a -> IO ()

-- | Read the next value from the <a>Chan</a>.
readChan :: Chan a -> IO a

-- | Duplicate a <a>Chan</a>: the duplicate channel begins empty, but data
--   written to either channel from then on will be available from both.
--   Hence this creates a kind of broadcast channel, where data written by
--   anyone is seen by everyone else.
--   
--   (Note that a duplicated channel is not equal to its original. So:
--   <tt>fmap (c /=) $ dupChan c</tt> returns <tt>True</tt> for all
--   <tt>c</tt>.)
dupChan :: Chan a -> IO (Chan a)

-- | Put a data item back onto a channel, where it will be the next item
--   read.

-- | <i>Deprecated: if you need this operation, use
--   Control.Concurrent.STM.TChan instead. See
--   http:<i></i>hackage.haskell.org<i>trac</i>ghc<i>ticket</i>4154 for
--   details </i>
unGetChan :: Chan a -> a -> IO ()

-- | Returns <a>True</a> if the supplied <a>Chan</a> is empty.

-- | <i>Deprecated: if you need this operation, use
--   Control.Concurrent.STM.TChan instead. See
--   http:<i></i>hackage.haskell.org<i>trac</i>ghc<i>ticket</i>4154 for
--   details </i>
isEmptyChan :: Chan a -> IO Bool

-- | Return a lazy list representing the contents of the supplied
--   <a>Chan</a>, much like <a>hGetContents</a>.
getChanContents :: Chan a -> IO [a]

-- | Write an entire list of items to a <a>Chan</a>.
writeList2Chan :: Chan a -> [a] -> IO ()
instance Typeable1 Chan
instance Eq (Chan a)


-- | Simple quantity semaphores.

-- | <i>Deprecated: Control.Concurrent.QSem will be removed in GHC 7.8.
--   Please use an alternative, e.g. the SafeSemaphore package, instead.
--   </i>
module Control.Concurrent.QSem

-- | A <a>QSem</a> is a simple quantity semaphore, in which the available
--   "quantity" is always dealt with in units of one.
data QSem

-- | Build a new <a>QSem</a> with a supplied initial quantity. The initial
--   quantity must be at least 0.
newQSem :: Int -> IO QSem

-- | Wait for a unit to become available
waitQSem :: QSem -> IO ()

-- | Signal that a unit of the <a>QSem</a> is available
signalQSem :: QSem -> IO ()
instance Typeable QSem
instance Eq QSem


-- | Quantity semaphores in which each thread may wait for an arbitrary
--   "amount".

-- | <i>Deprecated: Control.Concurrent.QSemN will be removed in GHC 7.8.
--   Please use an alternative, e.g. the SafeSemaphore package, instead.
--   </i>
module Control.Concurrent.QSemN

-- | A <a>QSemN</a> is a quantity semaphore, in which the available
--   "quantity" may be signalled or waited for in arbitrary amounts.
data QSemN

-- | Build a new <a>QSemN</a> with a supplied initial quantity. The initial
--   quantity must be at least 0.
newQSemN :: Int -> IO QSemN

-- | Wait for the specified quantity to become available
waitQSemN :: QSemN -> Int -> IO ()

-- | Signal that a given quantity is now available from the <a>QSemN</a>.
signalQSemN :: QSemN -> Int -> IO ()
instance Typeable QSemN
instance Eq QSemN


-- | Sample variables

-- | <i>Deprecated: Control.Concurrent.SampleVar will be removed in GHC
--   7.8. Please use an alternative, e.g. the SafeSemaphore package,
--   instead. </i>
module Control.Concurrent.SampleVar

-- | Sample variables are slightly different from a normal <a>MVar</a>:
--   
--   <ul>
--   <li>Reading an empty <a>SampleVar</a> causes the reader to block.
--   (same as <a>takeMVar</a> on empty <a>MVar</a>)</li>
--   <li>Reading a filled <a>SampleVar</a> empties it and returns value.
--   (same as <a>takeMVar</a>)</li>
--   <li>Writing to an empty <a>SampleVar</a> fills it with a value, and
--   potentially, wakes up a blocked reader (same as for <a>putMVar</a> on
--   empty <a>MVar</a>).</li>
--   <li>Writing to a filled <a>SampleVar</a> overwrites the current value.
--   (different from <a>putMVar</a> on full <a>MVar</a>.)</li>
--   </ul>
data SampleVar a

-- | Build a new, empty, <a>SampleVar</a>
newEmptySampleVar :: IO (SampleVar a)

-- | Build a <a>SampleVar</a> with an initial value.
newSampleVar :: a -> IO (SampleVar a)

-- | If the SampleVar is full, leave it empty. Otherwise, do nothing.
emptySampleVar :: SampleVar a -> IO ()

-- | Wait for a value to become available, then take it and return.
readSampleVar :: SampleVar a -> IO a

-- | Write a value into the <a>SampleVar</a>, overwriting any previous
--   value that was there.
writeSampleVar :: SampleVar a -> a -> IO ()

-- | Returns <a>True</a> if the <a>SampleVar</a> is currently empty.
--   
--   Note that this function is only useful if you know that no other
--   threads can be modifying the state of the <a>SampleVar</a>, because
--   otherwise the state of the <a>SampleVar</a> may have changed by the
--   time you see the result of <a>isEmptySampleVar</a>.
isEmptySampleVar :: SampleVar a -> IO Bool
instance Typeable1 SampleVar
instance Eq (SampleVar a)


-- | A common interface to a collection of useful concurrency abstractions.
module Control.Concurrent

-- | A <a>ThreadId</a> is an abstract type representing a handle to a
--   thread. <a>ThreadId</a> is an instance of <a>Eq</a>, <a>Ord</a> and
--   <a>Show</a>, where the <a>Ord</a> instance implements an arbitrary
--   total ordering over <a>ThreadId</a>s. The <a>Show</a> instance lets
--   you convert an arbitrary-valued <a>ThreadId</a> to string form;
--   showing a <a>ThreadId</a> value is occasionally useful when debugging
--   or diagnosing the behaviour of a concurrent program.
--   
--   <i>Note</i>: in GHC, if you have a <a>ThreadId</a>, you essentially
--   have a pointer to the thread itself. This means the thread itself
--   can't be garbage collected until you drop the <a>ThreadId</a>. This
--   misfeature will hopefully be corrected at a later date.
--   
--   <i>Note</i>: Hugs does not provide any operations on other threads; it
--   defines <a>ThreadId</a> as a synonym for ().
data ThreadId

-- | Returns the <a>ThreadId</a> of the calling thread (GHC only).
myThreadId :: IO ThreadId

-- | Sparks off a new thread to run the <a>IO</a> computation passed as the
--   first argument, and returns the <a>ThreadId</a> of the newly created
--   thread.
--   
--   The new thread will be a lightweight thread; if you want to use a
--   foreign library that uses thread-local storage, use <a>forkOS</a>
--   instead.
--   
--   GHC note: the new thread inherits the <i>masked</i> state of the
--   parent (see <a>mask</a>).
--   
--   The newly created thread has an exception handler that discards the
--   exceptions <a>BlockedIndefinitelyOnMVar</a>,
--   <a>BlockedIndefinitelyOnSTM</a>, and <a>ThreadKilled</a>, and passes
--   all other exceptions to the uncaught exception handler.
forkIO :: 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.
--   
--   <pre>
--   forkFinally action and_then =
--     mask $ \restore -&gt;
--       forkIO $ try (restore action) &gt;&gt;= and_then
--   </pre>
--   
--   This function is useful for informing the parent when a child
--   terminates, for example.
forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId

-- | Like <a>forkIO</a>, but the child thread is passed a function that can
--   be used to unmask asynchronous exceptions. This function is typically
--   used in the following way
--   
--   <pre>
--   ... mask_ $ forkIOWithUnmask $ \unmask -&gt;
--                  catch (unmask ...) handler
--   </pre>
--   
--   so that the exception handler in the child thread is established with
--   asynchronous exceptions masked, meanwhile the main body of the child
--   thread is executed in the unmasked state.
--   
--   Note that the unmask function passed to the child thread should only
--   be used in that thread; the behaviour is undefined if it is invoked in
--   a different thread.
forkIOWithUnmask :: ((forall a. IO a -> IO a) -> IO ()) -> IO ThreadId

-- | <a>killThread</a> raises the <a>ThreadKilled</a> exception in the
--   given thread (GHC only).
--   
--   <pre>
--   killThread tid = throwTo tid ThreadKilled
--   </pre>
killThread :: ThreadId -> IO ()

-- | <a>throwTo</a> raises an arbitrary exception in the target thread (GHC
--   only).
--   
--   <a>throwTo</a> does not return until the exception has been raised in
--   the target thread. The calling thread can thus be certain that the
--   target thread has received the exception. This is a useful property to
--   know when dealing with race conditions: eg. if there are two threads
--   that can kill each other, it is guaranteed that only one of the
--   threads will get to kill the other.
--   
--   Whatever work the target thread was doing when the exception was
--   raised is not lost: the computation is suspended until required by
--   another thread.
--   
--   If the target thread is currently making a foreign call, then the
--   exception will not be raised (and hence <a>throwTo</a> will not
--   return) until the call has completed. This is the case regardless of
--   whether the call is inside a <a>mask</a> or not. However, in GHC a
--   foreign call can be annotated as <tt>interruptible</tt>, in which case
--   a <a>throwTo</a> will cause the RTS to attempt to cause the call to
--   return; see the GHC documentation for more details.
--   
--   Important note: the behaviour of <a>throwTo</a> differs from that
--   described in the paper "Asynchronous exceptions in Haskell"
--   (<a>http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm</a>).
--   In the paper, <a>throwTo</a> is non-blocking; but the library
--   implementation adopts a more synchronous design in which
--   <a>throwTo</a> does not return until the exception is received by the
--   target thread. The trade-off is discussed in Section 9 of the paper.
--   Like any blocking operation, <a>throwTo</a> is therefore interruptible
--   (see Section 5.3 of the paper). Unlike other interruptible operations,
--   however, <a>throwTo</a> is <i>always</i> interruptible, even if it
--   does not actually block.
--   
--   There is no guarantee that the exception will be delivered promptly,
--   although the runtime will endeavour to ensure that arbitrary delays
--   don't occur. In GHC, an exception can only be raised when a thread
--   reaches a <i>safe point</i>, where a safe point is where memory
--   allocation occurs. Some loops do not perform any memory allocation
--   inside the loop and therefore cannot be interrupted by a
--   <a>throwTo</a>.
--   
--   If the target of <a>throwTo</a> is the calling thread, then the
--   behaviour is the same as <a>throwIO</a>, except that the exception is
--   thrown as an asynchronous exception. This means that if there is an
--   enclosing pure computation, which would be the case if the current IO
--   operation is inside <a>unsafePerformIO</a> or
--   <a>unsafeInterleaveIO</a>, that computation is not permanently
--   replaced by the exception, but is suspended as if it had received an
--   asynchronous exception.
--   
--   Note that if <a>throwTo</a> is called with the current thread as the
--   target, the exception will be thrown even if the thread is currently
--   inside <a>mask</a> or <a>uninterruptibleMask</a>.
throwTo :: Exception e => ThreadId -> e -> IO ()

-- | Like <a>forkIO</a>, but lets you specify on which processor the thread
--   should run. Unlike a <a>forkIO</a> thread, a thread created by
--   <a>forkOn</a> will stay on the same processor for its entire lifetime
--   (<a>forkIO</a> threads can migrate between processors according to the
--   scheduling policy). <a>forkOn</a> is useful for overriding the
--   scheduling policy when you know in advance how best to distribute the
--   threads.
--   
--   The <a>Int</a> argument specifies a <i>capability number</i> (see
--   <a>getNumCapabilities</a>). Typically capabilities correspond to
--   physical processors, but the exact behaviour is
--   implementation-dependent. The value passed to <a>forkOn</a> is
--   interpreted modulo the total number of capabilities as returned by
--   <a>getNumCapabilities</a>.
--   
--   GHC note: the number of capabilities is specified by the <tt>+RTS
--   -N</tt> option when the program is started. Capabilities can be fixed
--   to actual processor cores with <tt>+RTS -qa</tt> if the underlying
--   operating system supports that, although in practice this is usually
--   unnecessary (and may actually degrade perforamnce in some cases -
--   experimentation is recommended).
forkOn :: Int -> IO () -> IO ThreadId

-- | Like <a>forkIOWithUnmask</a>, but the child thread is pinned to the
--   given CPU, as with <a>forkOn</a>.
forkOnWithUnmask :: Int -> ((forall a. IO a -> IO a) -> IO ()) -> IO ThreadId

-- | Returns the number of Haskell threads that can run truly
--   simultaneously (on separate physical processors) at any given time. To
--   change this value, use <a>setNumCapabilities</a>.
getNumCapabilities :: IO Int

-- | Set the number of Haskell threads that can run truly simultaneously
--   (on separate physical processors) at any given time. The number passed
--   to <a>forkOn</a> is interpreted modulo this value. The initial value
--   is given by the <tt>+RTS -N</tt> runtime flag.
--   
--   This is also the number of threads that will participate in parallel
--   garbage collection. It is strongly recommended that the number of
--   capabilities is not set larger than the number of physical processor
--   cores, and it may often be beneficial to leave one or more cores free
--   to avoid contention with other processes in the machine.
setNumCapabilities :: Int -> IO ()

-- | returns the number of the capability on which the thread is currently
--   running, and a boolean indicating whether the thread is locked to that
--   capability or not. A thread is locked to a capability if it was
--   created with <tt>forkOn</tt>.
threadCapability :: ThreadId -> IO (Int, Bool)

-- | The <a>yield</a> action allows (forces, in a co-operative multitasking
--   implementation) a context-switch to any other currently runnable
--   threads (if any), and is occasionally useful when implementing
--   concurrency abstractions.
yield :: IO ()

-- | Suspends the current thread for a given number of microseconds (GHC
--   only).
--   
--   There is no guarantee that the thread will be rescheduled promptly
--   when the delay has expired, but the thread will never continue to run
--   <i>earlier</i> than specified.
threadDelay :: Int -> IO ()

-- | Block the current thread until data is available to read on the given
--   file descriptor (GHC only).
--   
--   This will throw an <a>IOError</a> if the file descriptor was closed
--   while this thread was blocked. To safely close a file descriptor that
--   has been used with <a>threadWaitRead</a>, use <a>closeFdWith</a>.
threadWaitRead :: Fd -> IO ()

-- | Block the current thread until data can be written to the given file
--   descriptor (GHC only).
--   
--   This will throw an <a>IOError</a> if the file descriptor was closed
--   while this thread was blocked. To safely close a file descriptor that
--   has been used with <a>threadWaitWrite</a>, use <a>closeFdWith</a>.
threadWaitWrite :: Fd -> IO ()

-- | <i>Deprecated: Control.Concurrent.mergeIO will be removed in GHC 7.8.
--   Please use an alternative, e.g. the SafeSemaphore package, instead.
--   </i>
mergeIO :: [a] -> [a] -> IO [a]

-- | <i>Deprecated: Control.Concurrent.nmergeIO will be removed in GHC 7.8.
--   Please use an alternative, e.g. the SafeSemaphore package, instead.
--   </i>
nmergeIO :: [[a]] -> IO [a]

-- | <a>True</a> if bound threads are supported. If
--   <tt>rtsSupportsBoundThreads</tt> is <a>False</a>,
--   <a>isCurrentThreadBound</a> will always return <a>False</a> and both
--   <a>forkOS</a> and <a>runInBoundThread</a> will fail.
rtsSupportsBoundThreads :: Bool

-- | Like <a>forkIO</a>, this sparks off a new thread to run the <a>IO</a>
--   computation passed as the first argument, and returns the
--   <a>ThreadId</a> of the newly created thread.
--   
--   However, <a>forkOS</a> creates a <i>bound</i> thread, which is
--   necessary if you need to call foreign (non-Haskell) libraries that
--   make use of thread-local state, such as OpenGL (see
--   <a>Control.Concurrent#boundthreads</a>).
--   
--   Using <a>forkOS</a> instead of <a>forkIO</a> makes no difference at
--   all to the scheduling behaviour of the Haskell runtime system. It is a
--   common misconception that you need to use <a>forkOS</a> instead of
--   <a>forkIO</a> to avoid blocking all the Haskell threads when making a
--   foreign call; this isn't the case. To allow foreign calls to be made
--   without blocking all the Haskell threads (with GHC), it is only
--   necessary to use the <tt>-threaded</tt> option when linking your
--   program, and to make sure the foreign import is not marked
--   <tt>unsafe</tt>.
forkOS :: IO () -> IO ThreadId

-- | Returns <a>True</a> if the calling thread is <i>bound</i>, that is, if
--   it is safe to use foreign libraries that rely on thread-local state
--   from the calling thread.
isCurrentThreadBound :: IO Bool

-- | Run the <a>IO</a> computation passed as the first argument. If the
--   calling thread is not <i>bound</i>, a bound thread is created
--   temporarily. <tt>runInBoundThread</tt> doesn't finish until the
--   <a>IO</a> computation finishes.
--   
--   You can wrap a series of foreign function calls that rely on
--   thread-local state with <tt>runInBoundThread</tt> so that you can use
--   them without knowing whether the current thread is <i>bound</i>.
runInBoundThread :: IO a -> IO a

-- | Run the <a>IO</a> computation passed as the first argument. If the
--   calling thread is <i>bound</i>, an unbound thread is created
--   temporarily using <a>forkIO</a>. <tt>runInBoundThread</tt> doesn't
--   finish until the <a>IO</a> computation finishes.
--   
--   Use this function <i>only</i> in the rare case that you have actually
--   observed a performance loss due to the use of bound threads. A program
--   that doesn't need it's main thread to be bound and makes <i>heavy</i>
--   use of concurrency (e.g. a web server), might want to wrap it's
--   <tt>main</tt> action in <tt>runInUnboundThread</tt>.
--   
--   Note that exceptions which are thrown to the current thread are thrown
--   in turn to the thread that is executing the given computation. This
--   ensures there's always a way of killing the forked thread.
runInUnboundThread :: IO a -> IO a

-- | make a weak pointer to a <a>ThreadId</a>. It can be important to do
--   this if you want to hold a reference to a <a>ThreadId</a> while still
--   allowing the thread to receive the <tt>BlockedIndefinitely</tt> family
--   of exceptions (e.g. <a>BlockedIndefinitelyOnMVar</a>). Holding a
--   normal <a>ThreadId</a> reference will prevent the delivery of
--   <tt>BlockedIndefinitely</tt> exceptions because the reference could be
--   used as the target of <a>throwTo</a> at any time, which would unblock
--   the thread.
--   
--   Holding a <tt>Weak ThreadId</tt>, on the other hand, will not prevent
--   the thread from receiving <tt>BlockedIndefinitely</tt> exceptions. It
--   is still possible to throw an exception to a <tt>Weak ThreadId</tt>,
--   but the caller must use <tt>deRefWeak</tt> first to determine whether
--   the thread still exists.
mkWeakThreadId :: ThreadId -> IO (Weak ThreadId)

-- | This function is deprecated; use <a>forkIOWithUnmask</a> instead

-- | <i>Deprecated: use forkIOWithUnmask instead </i>
forkIOUnmasked :: IO () -> IO ThreadId


-- | Attach a timeout event to arbitrary <a>IO</a> computations.
module System.Timeout

-- | Wrap an <a>IO</a> computation to time out and return <tt>Nothing</tt>
--   in case no result is available within <tt>n</tt> microseconds
--   (<tt>1/10^6</tt> seconds). In case a result is available before the
--   timeout expires, <tt>Just a</tt> is returned. A negative timeout
--   interval means "wait indefinitely". When specifying long timeouts, be
--   careful not to exceed <tt>maxBound :: Int</tt>.
--   
--   The design of this combinator was guided by the objective that
--   <tt>timeout n f</tt> should behave exactly the same as <tt>f</tt> as
--   long as <tt>f</tt> doesn't time out. This means that <tt>f</tt> has
--   the same <a>myThreadId</a> it would have without the timeout wrapper.
--   Any exceptions <tt>f</tt> might throw cancel the timeout and propagate
--   further up. It also possible for <tt>f</tt> to receive exceptions
--   thrown to it by another thread.
--   
--   A tricky implementation detail is the question of how to abort an
--   <tt>IO</tt> computation. This combinator relies on asynchronous
--   exceptions internally. 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 <tt>timeout</tt>
--   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
--   <a>hGetBuf</a>, <a>hPutBuf</a>, Network.Socket.accept, or
--   <a>hWaitForInput</a> appear to be blocking, but they really don't
--   because the runtime system uses scheduling mechanisms like
--   <tt>select(2)</tt> to perform asynchronous I/O, so it is possible to
--   interrupt standard socket I/O or file I/O using this combinator.
timeout :: Int -> IO a -> IO (Maybe a)
instance Typeable Timeout
instance Eq Timeout
instance Exception Timeout
instance Show Timeout


-- | Simple combinators working solely on and with functions.
module Data.Function

-- | Identity function.
id :: a -> a

-- | Constant function.
const :: a -> b -> a

-- | Function composition.
(.) :: (b -> c) -> (a -> b) -> a -> c

-- | <tt><a>flip</a> f</tt> takes its (first) two arguments in the reverse
--   order of <tt>f</tt>.
flip :: (a -> b -> c) -> b -> a -> c

-- | Application operator. This operator is redundant, since ordinary
--   application <tt>(f x)</tt> means the same as <tt>(f <a>$</a> x)</tt>.
--   However, <a>$</a> has low, right-associative binding precedence, so it
--   sometimes allows parentheses to be omitted; for example:
--   
--   <pre>
--   f $ g $ h x  =  f (g (h x))
--   </pre>
--   
--   It is also useful in higher-order situations, such as <tt><a>map</a>
--   (<a>$</a> 0) xs</tt>, or <tt><a>zipWith</a> (<a>$</a>) fs xs</tt>.
($) :: (a -> b) -> a -> b

-- | <tt><a>fix</a> f</tt> is the least fixed point of the function
--   <tt>f</tt>, i.e. the least defined <tt>x</tt> such that <tt>f x =
--   x</tt>.
fix :: (a -> a) -> a

-- | <tt>(*) `on` f = \x y -&gt; f x * f y</tt>.
--   
--   Typical usage: <tt><a>sortBy</a> (<a>compare</a> `on`
--   <a>fst</a>)</tt>.
--   
--   Algebraic properties:
--   
--   <ul>
--   <li><tt>(*) `on` <a>id</a> = (*)</tt> (if <tt>(*) ∉ {⊥, <a>const</a>
--   ⊥}</tt>)</li>
--   <li><pre>((*) `on` f) `on` g = (*) `on` (f . g)</pre></li>
--   <li><pre><a>flip</a> on f . <a>flip</a> on g = <a>flip</a> on (g .
--   f)</pre></li>
--   </ul>
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c


-- | Monadic fixpoints.
--   
--   For a detailed discussion, see Levent Erkok's thesis, <i>Value
--   Recursion in Monadic Computations</i>, Oregon Graduate Institute,
--   2002.
module Control.Monad.Fix

-- | Monads having fixed points with a 'knot-tying' semantics. Instances of
--   <a>MonadFix</a> should satisfy the following laws:
--   
--   <ul>
--   <li><i><i>purity</i></i> <tt><a>mfix</a> (<a>return</a> . h) =
--   <a>return</a> (<a>fix</a> h)</tt></li>
--   <li><i><i>left shrinking</i> (or <i>tightening</i>)</i>
--   <tt><a>mfix</a> (\x -&gt; a &gt;&gt;= \y -&gt; f x y) = a &gt;&gt;= \y
--   -&gt; <a>mfix</a> (\x -&gt; f x y)</tt></li>
--   <li><i><i>sliding</i></i> <tt><a>mfix</a> (<a>liftM</a> h . f) =
--   <a>liftM</a> h (<a>mfix</a> (f . h))</tt>, for strict <tt>h</tt>.</li>
--   <li><i><i>nesting</i></i> <tt><a>mfix</a> (\x -&gt; <a>mfix</a> (\y
--   -&gt; f x y)) = <a>mfix</a> (\x -&gt; f x x)</tt></li>
--   </ul>
--   
--   This class is used in the translation of the recursive <tt>do</tt>
--   notation supported by GHC and Hugs.
class Monad m => MonadFix m
mfix :: MonadFix m => (a -> m a) -> m a

-- | <tt><a>fix</a> f</tt> is the least fixed point of the function
--   <tt>f</tt>, i.e. the least defined <tt>x</tt> such that <tt>f x =
--   x</tt>.
fix :: (a -> a) -> a
instance MonadFix (ST s)
instance MonadFix (Either e)
instance MonadFix ((->) r)
instance MonadFix IO
instance MonadFix []
instance MonadFix Maybe


-- | Basic arrow definitions, based on * <i>Generalising Monads to
--   Arrows</i>, by John Hughes, <i>Science of Computer Programming</i> 37,
--   pp67-111, May 2000. plus a couple of definitions (<a>returnA</a> and
--   <a>loop</a>) from * <i>A New Notation for Arrows</i>, by Ross
--   Paterson, in <i>ICFP 2001</i>, Firenze, Italy, pp229-240. These papers
--   and more information on arrows can be found at
--   <a>http://www.haskell.org/arrows/</a>.
module Control.Arrow

-- | The basic arrow class.
--   
--   Minimal complete definition: <a>arr</a> and <a>first</a>, satisfying
--   the laws
--   
--   <ul>
--   <li><pre><a>arr</a> id = <a>id</a></pre></li>
--   <li><pre><a>arr</a> (f &gt;&gt;&gt; g) = <a>arr</a> f &gt;&gt;&gt;
--   <a>arr</a> g</pre></li>
--   <li><pre><a>first</a> (<a>arr</a> f) = <a>arr</a> (<a>first</a>
--   f)</pre></li>
--   <li><pre><a>first</a> (f &gt;&gt;&gt; g) = <a>first</a> f &gt;&gt;&gt;
--   <a>first</a> g</pre></li>
--   <li><pre><a>first</a> f &gt;&gt;&gt; <a>arr</a> <a>fst</a> =
--   <a>arr</a> <a>fst</a> &gt;&gt;&gt; f</pre></li>
--   <li><pre><a>first</a> f &gt;&gt;&gt; <a>arr</a> (<a>id</a> *** g) =
--   <a>arr</a> (<a>id</a> *** g) &gt;&gt;&gt; <a>first</a> f</pre></li>
--   <li><pre><a>first</a> (<a>first</a> f) &gt;&gt;&gt; <a>arr</a>
--   <tt>assoc</tt> = <a>arr</a> <tt>assoc</tt> &gt;&gt;&gt; <a>first</a>
--   f</pre></li>
--   </ul>
--   
--   where
--   
--   <pre>
--   assoc ((a,b),c) = (a,(b,c))
--   </pre>
--   
--   The other combinators have sensible default definitions, which may be
--   overridden for efficiency.
class Category a => Arrow a where second f = arr swap >>> first f >>> arr swap where swap :: (x, y) -> (y, x) swap ~(x, y) = (y, x) f *** g = first f >>> second g f &&& g = arr (\ b -> (b, b)) >>> f *** g
arr :: Arrow a => (b -> c) -> a b c
first :: Arrow a => a b c -> a (b, d) (c, d)
second :: Arrow a => a b c -> a (d, b) (d, c)
(***) :: Arrow a => a b c -> a b' c' -> a (b, b') (c, c')
(&&&) :: Arrow a => a b c -> a b c' -> a b (c, c')

-- | Kleisli arrows of a monad.
newtype Kleisli m a b
Kleisli :: (a -> m b) -> Kleisli m a b
runKleisli :: Kleisli m a b -> a -> m b

-- | The identity arrow, which plays the role of <a>return</a> in arrow
--   notation.
returnA :: Arrow a => a b b

-- | Precomposition with a pure function.
(^>>) :: Arrow a => (b -> c) -> a c d -> a b d

-- | Postcomposition with a pure function.
(>>^) :: Arrow a => a b c -> (c -> d) -> a b d

-- | Left-to-right composition
(>>>) :: Category cat => cat a b -> cat b c -> cat a c

-- | Right-to-left composition
(<<<) :: Category cat => cat b c -> cat a b -> cat a c

-- | Precomposition with a pure function (right-to-left variant).
(<<^) :: Arrow a => a c d -> (b -> c) -> a b d

-- | Postcomposition with a pure function (right-to-left variant).
(^<<) :: Arrow a => (c -> d) -> a b c -> a b d
class Arrow a => ArrowZero a
zeroArrow :: ArrowZero a => a b c

-- | A monoid on arrows.
class ArrowZero a => ArrowPlus a
(<+>) :: ArrowPlus a => a b c -> a b c -> a b c

-- | Choice, for arrows that support it. This class underlies the
--   <tt>if</tt> and <tt>case</tt> constructs in arrow notation. Minimal
--   complete definition: <a>left</a>, satisfying the laws
--   
--   <ul>
--   <li><pre><a>left</a> (<a>arr</a> f) = <a>arr</a> (<a>left</a>
--   f)</pre></li>
--   <li><pre><a>left</a> (f &gt;&gt;&gt; g) = <a>left</a> f &gt;&gt;&gt;
--   <a>left</a> g</pre></li>
--   <li><pre>f &gt;&gt;&gt; <a>arr</a> <a>Left</a> = <a>arr</a>
--   <a>Left</a> &gt;&gt;&gt; <a>left</a> f</pre></li>
--   <li><pre><a>left</a> f &gt;&gt;&gt; <a>arr</a> (<a>id</a> +++ g) =
--   <a>arr</a> (<a>id</a> +++ g) &gt;&gt;&gt; <a>left</a> f</pre></li>
--   <li><pre><a>left</a> (<a>left</a> f) &gt;&gt;&gt; <a>arr</a>
--   <tt>assocsum</tt> = <a>arr</a> <tt>assocsum</tt> &gt;&gt;&gt;
--   <a>left</a> f</pre></li>
--   </ul>
--   
--   where
--   
--   <pre>
--   assocsum (Left (Left x)) = Left x
--   assocsum (Left (Right y)) = Right (Left y)
--   assocsum (Right z) = Right (Right z)
--   </pre>
--   
--   The other combinators have sensible default definitions, which may be
--   overridden for efficiency.
class Arrow a => ArrowChoice a where right f = arr mirror >>> left f >>> arr mirror where mirror :: Either x y -> Either y x mirror (Left x) = Right x mirror (Right y) = Left y f +++ g = left f >>> right g f ||| g = f +++ g >>> arr untag where untag (Left x) = x untag (Right y) = y
left :: ArrowChoice a => a b c -> a (Either b d) (Either c d)
right :: ArrowChoice a => a b c -> a (Either d b) (Either d c)
(+++) :: ArrowChoice a => a b c -> a b' c' -> a (Either b b') (Either c c')
(|||) :: ArrowChoice a => a b d -> a c d -> a (Either b c) d

-- | Some arrows allow application of arrow inputs to other inputs.
--   Instances should satisfy the following laws:
--   
--   <ul>
--   <li><pre><a>first</a> (<a>arr</a> (\x -&gt; <a>arr</a> (\y -&gt;
--   (x,y)))) &gt;&gt;&gt; <a>app</a> = <a>id</a></pre></li>
--   <li><pre><a>first</a> (<a>arr</a> (g &gt;&gt;&gt;)) &gt;&gt;&gt;
--   <a>app</a> = <a>second</a> g &gt;&gt;&gt; <a>app</a></pre></li>
--   <li><pre><a>first</a> (<a>arr</a> (&gt;&gt;&gt; h)) &gt;&gt;&gt;
--   <a>app</a> = <a>app</a> &gt;&gt;&gt; h</pre></li>
--   </ul>
--   
--   Such arrows are equivalent to monads (see <a>ArrowMonad</a>).
class Arrow a => ArrowApply a
app :: ArrowApply a => a (a b c, b) c

-- | The <a>ArrowApply</a> class is equivalent to <a>Monad</a>: any monad
--   gives rise to a <a>Kleisli</a> arrow, and any instance of
--   <a>ArrowApply</a> defines a monad.
newtype ArrowMonad a b
ArrowMonad :: (a () b) -> ArrowMonad a b

-- | Any instance of <a>ArrowApply</a> can be made into an instance of
--   <a>ArrowChoice</a> by defining <a>left</a> = <a>leftApp</a>.
leftApp :: ArrowApply a => a b c -> a (Either b d) (Either c d)

-- | The <a>loop</a> operator expresses computations in which an output
--   value is fed back as input, although the computation occurs only once.
--   It underlies the <tt>rec</tt> value recursion construct in arrow
--   notation. <a>loop</a> should satisfy the following laws:
--   
--   <ul>
--   <li><i><i>extension</i></i> <tt><a>loop</a> (<a>arr</a> f) =
--   <a>arr</a> (\ b -&gt; <a>fst</a> (<a>fix</a> (\ (c,d) -&gt; f
--   (b,d))))</tt></li>
--   <li><i><i>left tightening</i></i> <tt><a>loop</a> (<a>first</a> h
--   &gt;&gt;&gt; f) = h &gt;&gt;&gt; <a>loop</a> f</tt></li>
--   <li><i><i>right tightening</i></i> <tt><a>loop</a> (f &gt;&gt;&gt;
--   <a>first</a> h) = <a>loop</a> f &gt;&gt;&gt; h</tt></li>
--   <li><i><i>sliding</i></i> <tt><a>loop</a> (f &gt;&gt;&gt; <a>arr</a>
--   (<a>id</a> *** k)) = <a>loop</a> (<a>arr</a> (<a>id</a> *** k)
--   &gt;&gt;&gt; f)</tt></li>
--   <li><i><i>vanishing</i></i> <tt><a>loop</a> (<a>loop</a> f) =
--   <a>loop</a> (<a>arr</a> unassoc &gt;&gt;&gt; f &gt;&gt;&gt; <a>arr</a>
--   assoc)</tt></li>
--   <li><i><i>superposing</i></i> <tt><a>second</a> (<a>loop</a> f) =
--   <a>loop</a> (<a>arr</a> assoc &gt;&gt;&gt; <a>second</a> f
--   &gt;&gt;&gt; <a>arr</a> unassoc)</tt></li>
--   </ul>
--   
--   where
--   
--   <pre>
--   assoc ((a,b),c) = (a,(b,c))
--   unassoc (a,(b,c)) = ((a,b),c)
--   </pre>
class Arrow a => ArrowLoop a
loop :: ArrowLoop a => a (b, d) (c, d) -> a b c
instance MonadFix m => ArrowLoop (Kleisli m)
instance ArrowLoop (->)
instance (ArrowApply a, ArrowPlus a) => MonadPlus (ArrowMonad a)
instance ArrowApply a => Monad (ArrowMonad a)
instance Arrow a => Functor (ArrowMonad a)
instance Monad m => ArrowApply (Kleisli m)
instance ArrowApply (->)
instance Monad m => ArrowChoice (Kleisli m)
instance ArrowChoice (->)
instance MonadPlus m => ArrowPlus (Kleisli m)
instance MonadPlus m => ArrowZero (Kleisli m)
instance Monad m => Arrow (Kleisli m)
instance Monad m => Category (Kleisli m)
instance Arrow (->)


-- | Support code for desugaring in GHC
module GHC.Desugar
(>>>) :: Arrow arr => forall a b c. arr a b -> arr b c -> arr a c
data AnnotationWrapper
AnnotationWrapper :: a -> AnnotationWrapper
toAnnotationWrapper :: Data a => a -> AnnotationWrapper


-- | <i>This module is DEPRECATED and will be removed in the future!</i>
--   
--   <a>Functor</a> and <a>Monad</a> instances for <tt>(-&gt;) r</tt> and
--   <a>Functor</a> instances for <tt>(,) a</tt> and <tt><a>Either</a>
--   a</tt>.
module Control.Monad.Instances

-- | The <a>Functor</a> class is used for types that can be mapped over.
--   Instances of <a>Functor</a> should satisfy the following laws:
--   
--   <pre>
--   fmap id  ==  id
--   fmap (f . g)  ==  fmap f . fmap g
--   </pre>
--   
--   The instances of <a>Functor</a> for lists, <a>Maybe</a> and <a>IO</a>
--   satisfy these laws.
class Functor f where <$ = fmap . const
fmap :: Functor f => (a -> b) -> f a -> f b

-- | The <a>Monad</a> class defines the basic operations over a
--   <i>monad</i>, a concept from a branch of mathematics known as
--   <i>category theory</i>. From the perspective of a Haskell programmer,
--   however, it is best to think of a monad as an <i>abstract datatype</i>
--   of actions. Haskell's <tt>do</tt> expressions provide a convenient
--   syntax for writing monadic expressions.
--   
--   Minimal complete definition: <a>&gt;&gt;=</a> and <a>return</a>.
--   
--   Instances of <a>Monad</a> should satisfy the following laws:
--   
--   <pre>
--   return a &gt;&gt;= k  ==  k a
--   m &gt;&gt;= return  ==  m
--   m &gt;&gt;= (\x -&gt; k x &gt;&gt;= h)  ==  (m &gt;&gt;= k) &gt;&gt;= h
--   </pre>
--   
--   Instances of both <a>Monad</a> and <a>Functor</a> should additionally
--   satisfy the law:
--   
--   <pre>
--   fmap f xs  ==  xs &gt;&gt;= return . f
--   </pre>
--   
--   The instances of <a>Monad</a> for lists, <a>Maybe</a> and <a>IO</a>
--   defined in the <a>Prelude</a> satisfy these laws.
class Monad m where m >> k = m >>= \ _ -> k fail s = error s
(>>=) :: Monad m => m a -> (a -> m b) -> m b
(>>) :: Monad m => m a -> m b -> m b
return :: Monad m => a -> m a
fail :: Monad m => String -> m a


-- | This library provides support for <i>strict</i> state threads, as
--   described in the PLDI '94 paper by John Launchbury and Simon Peyton
--   Jones <i>Lazy Functional State Threads</i>.
--   
--   Safe API Only.
module Control.Monad.ST.Safe

-- | The strict state-transformer monad. A computation of type
--   <tt><a>ST</a> s a</tt> transforms an internal state indexed by
--   <tt>s</tt>, and returns a value of type <tt>a</tt>. The <tt>s</tt>
--   parameter is either
--   
--   <ul>
--   <li>an uninstantiated type variable (inside invocations of
--   <a>runST</a>), or</li>
--   <li><a>RealWorld</a> (inside invocations of <a>stToIO</a>).</li>
--   </ul>
--   
--   It serves to keep the internal states of different invocations of
--   <a>runST</a> separate from each other and from invocations of
--   <a>stToIO</a>.
--   
--   The <a>&gt;&gt;=</a> and <a>&gt;&gt;</a> operations are strict in the
--   state (though not in values stored in the state). For example,
--   
--   <pre>
--   <a>runST</a> (writeSTRef _|_ v &gt;&gt;= f) = _|_
--   </pre>
data ST s a

-- | Return the value computed by a state transformer computation. The
--   <tt>forall</tt> ensures that the internal state used by the <a>ST</a>
--   computation is inaccessible to the rest of the program.
runST :: (forall s. ST s a) -> a

-- | Allow the result of a state transformer computation to be used
--   (lazily) inside the computation. Note that if <tt>f</tt> is strict,
--   <tt><a>fixST</a> f = _|_</tt>.
fixST :: (a -> ST s a) -> ST s a

-- | <tt>RealWorld</tt> is deeply magical. It is <i>primitive</i>, but it
--   is not <i>unlifted</i> (hence <tt>ptrArg</tt>). We never manipulate
--   values of type <tt>RealWorld</tt>; it's only used in the type system,
--   to parameterise <tt>State#</tt>.
data RealWorld :: *

-- | A monad transformer embedding strict state transformers in the
--   <a>IO</a> monad. The <a>RealWorld</a> parameter indicates that the
--   internal state used by the <a>ST</a> computation is a special one
--   supplied by the <a>IO</a> monad, and thus distinct from those used by
--   invocations of <a>runST</a>.
stToIO :: ST RealWorld a -> IO a


-- | This library provides support for <i>strict</i> state threads, as
--   described in the PLDI '94 paper by John Launchbury and Simon Peyton
--   Jones <i>Lazy Functional State Threads</i>.
--   
--   Unsafe API.
module Control.Monad.ST.Unsafe
unsafeInterleaveST :: ST s a -> ST s a
unsafeIOToST :: IO a -> ST s a
unsafeSTToIO :: ST s a -> IO a


-- | This library provides support for <i>strict</i> state threads, as
--   described in the PLDI '94 paper by John Launchbury and Simon Peyton
--   Jones <i>Lazy Functional State Threads</i>.
module Control.Monad.ST

-- | The strict state-transformer monad. A computation of type
--   <tt><a>ST</a> s a</tt> transforms an internal state indexed by
--   <tt>s</tt>, and returns a value of type <tt>a</tt>. The <tt>s</tt>
--   parameter is either
--   
--   <ul>
--   <li>an uninstantiated type variable (inside invocations of
--   <a>runST</a>), or</li>
--   <li><a>RealWorld</a> (inside invocations of <a>stToIO</a>).</li>
--   </ul>
--   
--   It serves to keep the internal states of different invocations of
--   <a>runST</a> separate from each other and from invocations of
--   <a>stToIO</a>.
--   
--   The <a>&gt;&gt;=</a> and <a>&gt;&gt;</a> operations are strict in the
--   state (though not in values stored in the state). For example,
--   
--   <pre>
--   <a>runST</a> (writeSTRef _|_ v &gt;&gt;= f) = _|_
--   </pre>
data ST s a

-- | Return the value computed by a state transformer computation. The
--   <tt>forall</tt> ensures that the internal state used by the <a>ST</a>
--   computation is inaccessible to the rest of the program.
runST :: (forall s. ST s a) -> a

-- | Allow the result of a state transformer computation to be used
--   (lazily) inside the computation. Note that if <tt>f</tt> is strict,
--   <tt><a>fixST</a> f = _|_</tt>.
fixST :: (a -> ST s a) -> ST s a

-- | <tt>RealWorld</tt> is deeply magical. It is <i>primitive</i>, but it
--   is not <i>unlifted</i> (hence <tt>ptrArg</tt>). We never manipulate
--   values of type <tt>RealWorld</tt>; it's only used in the type system,
--   to parameterise <tt>State#</tt>.
data RealWorld :: *

-- | A monad transformer embedding strict state transformers in the
--   <a>IO</a> monad. The <a>RealWorld</a> parameter indicates that the
--   internal state used by the <a>ST</a> computation is a special one
--   supplied by the <a>IO</a> monad, and thus distinct from those used by
--   invocations of <a>runST</a>.
stToIO :: ST RealWorld a -> IO a

-- | <i>Deprecated: Please import from Control.Monad.ST.Unsafe instead;
--   This will be removed in the next release </i>
unsafeInterleaveST :: ST s a -> ST s a

-- | <i>Deprecated: Please import from Control.Monad.ST.Unsafe instead;
--   This will be removed in the next release </i>
unsafeIOToST :: IO a -> ST s a

-- | <i>Deprecated: Please import from Control.Monad.ST.Unsafe instead;
--   This will be removed in the next release </i>
unsafeSTToIO :: ST s a -> IO a


-- | This module presents an identical interface to
--   <a>Control.Monad.ST</a>, except that the monad delays evaluation of
--   state operations until a value depending on them is required.
--   
--   Safe API only.
module Control.Monad.ST.Lazy.Safe

-- | The lazy state-transformer monad. A computation of type <tt><a>ST</a>
--   s a</tt> transforms an internal state indexed by <tt>s</tt>, and
--   returns a value of type <tt>a</tt>. The <tt>s</tt> parameter is either
--   
--   <ul>
--   <li>an unstantiated type variable (inside invocations of
--   <a>runST</a>), or</li>
--   <li><a>RealWorld</a> (inside invocations of <a>stToIO</a>).</li>
--   </ul>
--   
--   It serves to keep the internal states of different invocations of
--   <a>runST</a> separate from each other and from invocations of
--   <a>stToIO</a>.
--   
--   The <a>&gt;&gt;=</a> and <a>&gt;&gt;</a> operations are not strict in
--   the state. For example,
--   
--   <pre>
--   <a>runST</a> (writeSTRef _|_ v &gt;&gt;= readSTRef _|_ &gt;&gt; return 2) = 2
--   </pre>
data ST s a

-- | Return the value computed by a state transformer computation. The
--   <tt>forall</tt> ensures that the internal state used by the <a>ST</a>
--   computation is inaccessible to the rest of the program.
runST :: (forall s. ST s a) -> a

-- | Allow the result of a state transformer computation to be used
--   (lazily) inside the computation. Note that if <tt>f</tt> is strict,
--   <tt><a>fixST</a> f = _|_</tt>.
fixST :: (a -> ST s a) -> ST s a

-- | Convert a strict <a>ST</a> computation into a lazy one. The strict
--   state thread passed to <a>strictToLazyST</a> is not performed until
--   the result of the lazy state thread it returns is demanded.
strictToLazyST :: ST s a -> ST s a

-- | Convert a lazy <a>ST</a> computation into a strict one.
lazyToStrictST :: ST s a -> ST s a

-- | <tt>RealWorld</tt> is deeply magical. It is <i>primitive</i>, but it
--   is not <i>unlifted</i> (hence <tt>ptrArg</tt>). We never manipulate
--   values of type <tt>RealWorld</tt>; it's only used in the type system,
--   to parameterise <tt>State#</tt>.
data RealWorld :: *

-- | A monad transformer embedding lazy state transformers in the <a>IO</a>
--   monad. The <a>RealWorld</a> parameter indicates that the internal
--   state used by the <a>ST</a> computation is a special one supplied by
--   the <a>IO</a> monad, and thus distinct from those used by invocations
--   of <a>runST</a>.
stToIO :: ST RealWorld a -> IO a


-- | This module describes a structure intermediate between a functor and a
--   monad (technically, a strong lax monoidal functor). Compared with
--   monads, this interface lacks the full power of the binding operation
--   <a>&gt;&gt;=</a>, but
--   
--   <ul>
--   <li>it has more instances.</li>
--   <li>it is sufficient for many uses, e.g. context-free parsing, or the
--   <a>Traversable</a> class.</li>
--   <li>instances can perform analysis of computations before they are
--   executed, and thus produce shared optimizations.</li>
--   </ul>
--   
--   This interface was introduced for parsers by Niklas Röjemo, because it
--   admits more sharing than the monadic interface. The names here are
--   mostly based on parsing work by Doaitse Swierstra.
--   
--   For more details, see <i>Applicative Programming with Effects</i>, by
--   Conor McBride and Ross Paterson, online at
--   <a>http://www.soi.city.ac.uk/~ross/papers/Applicative.html</a>.
module Control.Applicative

-- | A functor with application, providing operations to
--   
--   <ul>
--   <li>embed pure expressions (<a>pure</a>), and</li>
--   <li>sequence computations and combine their results
--   (<a>&lt;*&gt;</a>).</li>
--   </ul>
--   
--   A minimal complete definition must include implementations of these
--   functions satisfying the following laws:
--   
--   <ul>
--   <li><i><i>identity</i></i> <tt><a>pure</a> <a>id</a> <a>&lt;*&gt;</a>
--   v = v</tt></li>
--   <li><i><i>composition</i></i> <tt><a>pure</a> (.) <a>&lt;*&gt;</a> u
--   <a>&lt;*&gt;</a> v <a>&lt;*&gt;</a> w = u <a>&lt;*&gt;</a> (v
--   <a>&lt;*&gt;</a> w)</tt></li>
--   <li><i><i>homomorphism</i></i> <tt><a>pure</a> f <a>&lt;*&gt;</a>
--   <a>pure</a> x = <a>pure</a> (f x)</tt></li>
--   <li><i><i>interchange</i></i> <tt>u <a>&lt;*&gt;</a> <a>pure</a> y =
--   <a>pure</a> (<a>$</a> y) <a>&lt;*&gt;</a> u</tt></li>
--   </ul>
--   
--   The other methods have the following default definitions, which may be
--   overridden with equivalent specialized implementations:
--   
--   <pre>
--   u <a>*&gt;</a> v = <a>pure</a> (<a>const</a> <a>id</a>) <a>&lt;*&gt;</a> u <a>&lt;*&gt;</a> v
--   u <a>&lt;*</a> v = <a>pure</a> <a>const</a> <a>&lt;*&gt;</a> u <a>&lt;*&gt;</a> v
--   </pre>
--   
--   As a consequence of these laws, the <a>Functor</a> instance for
--   <tt>f</tt> will satisfy
--   
--   <pre>
--   <a>fmap</a> f x = <a>pure</a> f <a>&lt;*&gt;</a> x
--   </pre>
--   
--   If <tt>f</tt> is also a <a>Monad</a>, it should satisfy
--   <tt><a>pure</a> = <a>return</a></tt> and <tt>(<a>&lt;*&gt;</a>) =
--   <a>ap</a></tt> (which implies that <a>pure</a> and <a>&lt;*&gt;</a>
--   satisfy the applicative functor laws).
class Functor f => Applicative f where *> = liftA2 (const id) <* = liftA2 const
pure :: Applicative f => a -> f a
(<*>) :: Applicative f => f (a -> b) -> f a -> f b
(*>) :: Applicative f => f a -> f b -> f b
(<*) :: Applicative f => f a -> f b -> f a

-- | A monoid on applicative functors.
--   
--   Minimal complete definition: <a>empty</a> and <a>&lt;|&gt;</a>.
--   
--   If defined, <a>some</a> and <a>many</a> should be the least solutions
--   of the equations:
--   
--   <ul>
--   <li><pre>some v = (:) <a>&lt;$&gt;</a> v <a>&lt;*&gt;</a> many
--   v</pre></li>
--   <li><pre>many v = some v <a>&lt;|&gt;</a> <a>pure</a> []</pre></li>
--   </ul>
class Applicative f => Alternative f where some v = some_v where many_v = some_v <|> pure [] some_v = (:) <$> v <*> many_v many v = many_v where many_v = some_v <|> pure [] some_v = (:) <$> v <*> many_v
empty :: Alternative f => f a
(<|>) :: Alternative f => f a -> f a -> f a
some :: Alternative f => f a -> f [a]
many :: Alternative f => f a -> f [a]
newtype Const a b
Const :: a -> Const a b
getConst :: Const a b -> a
newtype WrappedMonad m a
WrapMonad :: m a -> WrappedMonad m a
unwrapMonad :: WrappedMonad m a -> m a
newtype WrappedArrow a b c
WrapArrow :: a b c -> WrappedArrow a b c
unwrapArrow :: WrappedArrow a b c -> a b c

-- | Lists, but with an <a>Applicative</a> functor based on zipping, so
--   that
--   
--   <pre>
--   f <a>&lt;$&gt;</a> <a>ZipList</a> xs1 <a>&lt;*&gt;</a> ... <a>&lt;*&gt;</a> <a>ZipList</a> xsn = <a>ZipList</a> (zipWithn f xs1 ... xsn)
--   </pre>
newtype ZipList a
ZipList :: [a] -> ZipList a
getZipList :: ZipList a -> [a]

-- | An infix synonym for <a>fmap</a>.
(<$>) :: Functor f => (a -> b) -> f a -> f b

-- | Replace all locations in the input with the same value. The default
--   definition is <tt><a>fmap</a> . <a>const</a></tt>, but this may be
--   overridden with a more efficient version.
(<$) :: Functor f => a -> f b -> f a

-- | A variant of <a>&lt;*&gt;</a> with the arguments reversed.
(<**>) :: Applicative f => f a -> f (a -> b) -> f b

-- | Lift a function to actions. This function may be used as a value for
--   <a>fmap</a> in a <a>Functor</a> instance.
liftA :: Applicative f => (a -> b) -> f a -> f b

-- | Lift a binary function to actions.
liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c

-- | Lift a ternary function to actions.
liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d

-- | One or none.
optional :: Alternative f => f a -> f (Maybe a)
instance Applicative ZipList
instance Functor ZipList
instance (ArrowZero a, ArrowPlus a) => Alternative (WrappedArrow a b)
instance Arrow a => Applicative (WrappedArrow a b)
instance Arrow a => Functor (WrappedArrow a b)
instance MonadPlus m => Alternative (WrappedMonad m)
instance Monad m => Applicative (WrappedMonad m)
instance Monad m => Functor (WrappedMonad m)
instance Monoid m => Applicative (Const m)
instance Functor (Const m)
instance ArrowPlus a => Alternative (ArrowMonad a)
instance Arrow a => Applicative (ArrowMonad a)
instance Alternative ReadPrec
instance Applicative ReadPrec
instance Alternative ReadP
instance Applicative ReadP
instance Applicative (Either e)
instance Monoid a => Applicative ((,) a)
instance Applicative ((->) a)
instance Alternative STM
instance Applicative STM
instance Applicative (ST s)
instance Applicative (ST s)
instance Applicative IO
instance Alternative []
instance Applicative []
instance Alternative Maybe
instance Applicative Maybe


-- | Class of data structures that can be folded to a summary value.
--   
--   Many of these functions generalize <a>Prelude</a>,
--   <a>Control.Monad</a> and <a>Data.List</a> functions of the same names
--   from lists to any <a>Foldable</a> functor. To avoid ambiguity, either
--   import those modules hiding these names or qualify uses of these
--   function names with an alias for this module.
module Data.Foldable

-- | Data structures that can be folded.
--   
--   Minimal complete definition: <a>foldMap</a> or <a>foldr</a>.
--   
--   For example, given a data type
--   
--   <pre>
--   data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
--   </pre>
--   
--   a suitable instance would be
--   
--   <pre>
--   instance Foldable Tree where
--      foldMap f Empty = mempty
--      foldMap f (Leaf x) = f x
--      foldMap f (Node l k r) = foldMap f l `mappend` f k `mappend` foldMap f r
--   </pre>
--   
--   This is suitable even for abstract types, as the monoid is assumed to
--   satisfy the monoid laws. Alternatively, one could define
--   <tt>foldr</tt>:
--   
--   <pre>
--   instance Foldable Tree where
--      foldr f z Empty = z
--      foldr f z (Leaf x) = f x z
--      foldr f z (Node l k r) = foldr f (f k (foldr f z r)) l
--   </pre>
class Foldable t where fold = foldMap id foldMap f = foldr (mappend . f) mempty foldr f z t = appEndo (foldMap (Endo . f) t) z foldr' f z0 xs = foldl f' id xs z0 where f' k x z = k $! f x z foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z foldl' f z0 xs = foldr f' id xs z0 where f' x k z = k $! f z x foldr1 f xs = fromMaybe (error "foldr1: empty structure") (foldr mf Nothing xs) where mf x Nothing = Just x mf x (Just y) = Just (f x y) foldl1 f xs = fromMaybe (error "foldl1: empty structure") (foldl mf Nothing xs) where mf Nothing y = Just y mf (Just x) y = Just (f x y)
fold :: (Foldable t, Monoid m) => t m -> m
foldMap :: (Foldable t, Monoid m) => (a -> m) -> t a -> m
foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b
foldr' :: Foldable t => (a -> b -> b) -> b -> t a -> b
foldl :: Foldable t => (a -> b -> a) -> a -> t b -> a
foldl' :: Foldable t => (a -> b -> a) -> a -> t b -> a
foldr1 :: Foldable t => (a -> a -> a) -> t a -> a
foldl1 :: Foldable t => (a -> a -> a) -> t a -> a

-- | Monadic fold over the elements of a structure, associating to the
--   right, i.e. from right to left.
foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b

-- | Monadic fold over the elements of a structure, associating to the
--   left, i.e. from left to right.
foldlM :: (Foldable t, Monad m) => (a -> b -> m a) -> a -> t b -> m a

-- | Map each element of a structure to an action, evaluate these actions
--   from left to right, and ignore the results.
traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()

-- | <a>for_</a> is <a>traverse_</a> with its arguments flipped.
for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f ()

-- | Evaluate each action in the structure from left to right, and ignore
--   the results.
sequenceA_ :: (Foldable t, Applicative f) => t (f a) -> f ()

-- | The sum of a collection of actions, generalizing <a>concat</a>.
asum :: (Foldable t, Alternative f) => t (f a) -> f a

-- | Map each element of a structure to a monadic action, evaluate these
--   actions from left to right, and ignore the results.
mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()

-- | <a>forM_</a> is <a>mapM_</a> with its arguments flipped.
forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m ()

-- | Evaluate each monadic action in the structure from left to right, and
--   ignore the results.
sequence_ :: (Foldable t, Monad m) => t (m a) -> m ()

-- | The sum of a collection of actions, generalizing <a>concat</a>.
msum :: (Foldable t, MonadPlus m) => t (m a) -> m a

-- | List of elements of a structure.
toList :: Foldable t => t a -> [a]

-- | The concatenation of all the elements of a container of lists.
concat :: Foldable t => t [a] -> [a]

-- | Map a function over all the elements of a container and concatenate
--   the resulting lists.
concatMap :: Foldable t => (a -> [b]) -> t a -> [b]

-- | <a>and</a> returns the conjunction of a container of Bools. For the
--   result to be <a>True</a>, the container must be finite; <a>False</a>,
--   however, results from a <a>False</a> value finitely far from the left
--   end.
and :: Foldable t => t Bool -> Bool

-- | <a>or</a> returns the disjunction of a container of Bools. For the
--   result to be <a>False</a>, the container must be finite; <a>True</a>,
--   however, results from a <a>True</a> value finitely far from the left
--   end.
or :: Foldable t => t Bool -> Bool

-- | Determines whether any element of the structure satisfies the
--   predicate.
any :: Foldable t => (a -> Bool) -> t a -> Bool

-- | Determines whether all elements of the structure satisfy the
--   predicate.
all :: Foldable t => (a -> Bool) -> t a -> Bool

-- | The <a>sum</a> function computes the sum of the numbers of a
--   structure.
sum :: (Foldable t, Num a) => t a -> a

-- | The <a>product</a> function computes the product of the numbers of a
--   structure.
product :: (Foldable t, Num a) => t a -> a

-- | The largest element of a non-empty structure.
maximum :: (Foldable t, Ord a) => t a -> a

-- | The largest element of a non-empty structure with respect to the given
--   comparison function.
maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a

-- | The least element of a non-empty structure.
minimum :: (Foldable t, Ord a) => t a -> a

-- | The least element of a non-empty structure with respect to the given
--   comparison function.
minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a

-- | Does the element occur in the structure?
elem :: (Foldable t, Eq a) => a -> t a -> Bool

-- | <a>notElem</a> is the negation of <a>elem</a>.
notElem :: (Foldable t, Eq a) => a -> t a -> Bool

-- | The <a>find</a> function takes a predicate and a structure and returns
--   the leftmost element of the structure matching the predicate, or
--   <a>Nothing</a> if there is no such element.
find :: Foldable t => (a -> Bool) -> t a -> Maybe a
instance Ix i => Foldable (Array i)
instance Foldable []
instance Foldable Maybe


-- | Class of data structures that can be traversed from left to right,
--   performing an action on each element.
--   
--   See also
--   
--   <ul>
--   <li><i>Applicative Programming with Effects</i>, by Conor McBride and
--   Ross Paterson, online at
--   <a>http://www.soi.city.ac.uk/~ross/papers/Applicative.html</a>.</li>
--   <li><i>The Essence of the Iterator Pattern</i>, by Jeremy Gibbons and
--   Bruno Oliveira, in <i>Mathematically-Structured Functional
--   Programming</i>, 2006, and online at
--   <a>http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/#iterator</a>.</li>
--   </ul>
--   
--   Note that the functions <a>mapM</a> and <a>sequence</a> generalize
--   <a>Prelude</a> functions of the same names from lists to any
--   <a>Traversable</a> functor. To avoid ambiguity, either import the
--   <a>Prelude</a> hiding these names or qualify uses of these function
--   names with an alias for this module.
module Data.Traversable

-- | Functors representing data structures that can be traversed from left
--   to right.
--   
--   Minimal complete definition: <a>traverse</a> or <a>sequenceA</a>.
--   
--   Instances are similar to <a>Functor</a>, e.g. given a data type
--   
--   <pre>
--   data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
--   </pre>
--   
--   a suitable instance would be
--   
--   <pre>
--   instance Traversable Tree where
--      traverse f Empty = pure Empty
--      traverse f (Leaf x) = Leaf &lt;$&gt; f x
--      traverse f (Node l k r) = Node &lt;$&gt; traverse f l &lt;*&gt; f k &lt;*&gt; traverse f r
--   </pre>
--   
--   This is suitable even for abstract types, as the laws for
--   <a>&lt;*&gt;</a> imply a form of associativity.
--   
--   The superclass instances should satisfy the following:
--   
--   <ul>
--   <li>In the <a>Functor</a> instance, <a>fmap</a> should be equivalent
--   to traversal with the identity applicative functor
--   (<a>fmapDefault</a>).</li>
--   <li>In the <a>Foldable</a> instance, <a>foldMap</a> should be
--   equivalent to traversal with a constant applicative functor
--   (<a>foldMapDefault</a>).</li>
--   </ul>
class (Functor t, Foldable t) => Traversable t where traverse f = sequenceA . fmap f sequenceA = traverse id mapM f = unwrapMonad . traverse (WrapMonad . f) sequence = mapM id
traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b)
sequenceA :: (Traversable t, Applicative f) => t (f a) -> f (t a)
mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b)
sequence :: (Traversable t, Monad m) => t (m a) -> m (t a)

-- | <a>for</a> is <a>traverse</a> with its arguments flipped.
for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b)

-- | <a>forM</a> is <a>mapM</a> with its arguments flipped.
forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b)

-- | The <a>mapAccumL</a> function behaves like a combination of
--   <a>fmap</a> and <a>foldl</a>; it applies a function to each element of
--   a structure, passing an accumulating parameter from left to right, and
--   returning a final value of this accumulator together with the new
--   structure.
mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)

-- | The <a>mapAccumR</a> function behaves like a combination of
--   <a>fmap</a> and <tt>foldr</tt>; it applies a function to each element
--   of a structure, passing an accumulating parameter from right to left,
--   and returning a final value of this accumulator together with the new
--   structure.
mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)

-- | This function may be used as a value for <a>fmap</a> in a
--   <a>Functor</a> instance, provided that <a>traverse</a> is defined.
--   (Using <a>fmapDefault</a> with a <a>Traversable</a> instance defined
--   only by <a>sequenceA</a> will result in infinite recursion.)
fmapDefault :: Traversable t => (a -> b) -> t a -> t b

-- | This function may be used as a value for <a>foldMap</a> in a
--   <a>Foldable</a> instance.
foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m
instance Applicative Id
instance Functor Id
instance Applicative (StateR s)
instance Functor (StateR s)
instance Applicative (StateL s)
instance Functor (StateL s)
instance Ix i => Traversable (Array i)
instance Traversable []
instance Traversable Maybe


-- | This module presents an identical interface to
--   <a>Control.Monad.ST</a>, except that the monad delays evaluation of
--   state operations until a value depending on them is required.
--   
--   Unsafe API.
module Control.Monad.ST.Lazy.Unsafe
unsafeInterleaveST :: ST s a -> ST s a
unsafeIOToST :: IO a -> ST s a


-- | This module presents an identical interface to
--   <a>Control.Monad.ST</a>, except that the monad delays evaluation of
--   state operations until a value depending on them is required.
module Control.Monad.ST.Lazy

-- | The lazy state-transformer monad. A computation of type <tt><a>ST</a>
--   s a</tt> transforms an internal state indexed by <tt>s</tt>, and
--   returns a value of type <tt>a</tt>. The <tt>s</tt> parameter is either
--   
--   <ul>
--   <li>an unstantiated type variable (inside invocations of
--   <a>runST</a>), or</li>
--   <li><a>RealWorld</a> (inside invocations of <a>stToIO</a>).</li>
--   </ul>
--   
--   It serves to keep the internal states of different invocations of
--   <a>runST</a> separate from each other and from invocations of
--   <a>stToIO</a>.
--   
--   The <a>&gt;&gt;=</a> and <a>&gt;&gt;</a> operations are not strict in
--   the state. For example,
--   
--   <pre>
--   <a>runST</a> (writeSTRef _|_ v &gt;&gt;= readSTRef _|_ &gt;&gt; return 2) = 2
--   </pre>
data ST s a

-- | Return the value computed by a state transformer computation. The
--   <tt>forall</tt> ensures that the internal state used by the <a>ST</a>
--   computation is inaccessible to the rest of the program.
runST :: (forall s. ST s a) -> a

-- | Allow the result of a state transformer computation to be used
--   (lazily) inside the computation. Note that if <tt>f</tt> is strict,
--   <tt><a>fixST</a> f = _|_</tt>.
fixST :: (a -> ST s a) -> ST s a

-- | Convert a strict <a>ST</a> computation into a lazy one. The strict
--   state thread passed to <a>strictToLazyST</a> is not performed until
--   the result of the lazy state thread it returns is demanded.
strictToLazyST :: ST s a -> ST s a

-- | Convert a lazy <a>ST</a> computation into a strict one.
lazyToStrictST :: ST s a -> ST s a

-- | <tt>RealWorld</tt> is deeply magical. It is <i>primitive</i>, but it
--   is not <i>unlifted</i> (hence <tt>ptrArg</tt>). We never manipulate
--   values of type <tt>RealWorld</tt>; it's only used in the type system,
--   to parameterise <tt>State#</tt>.
data RealWorld :: *

-- | A monad transformer embedding lazy state transformers in the <a>IO</a>
--   monad. The <a>RealWorld</a> parameter indicates that the internal
--   state used by the <a>ST</a> computation is a special one supplied by
--   the <a>IO</a> monad, and thus distinct from those used by invocations
--   of <a>runST</a>.
stToIO :: ST RealWorld a -> IO a

-- | <i>Deprecated: Please import from Control.Monad.ST.Lazy.Unsafe
--   instead; This will be removed in the next release </i>
unsafeInterleaveST :: ST s a -> ST s a

-- | <i>Deprecated: Please import from Control.Monad.ST.Lazy.Unsafe
--   instead; This will be removed in the next release </i>
unsafeIOToST :: IO a -> ST s a


-- | The strict ST monad (re-export of <a>Control.Monad.ST</a>)
module Control.Monad.ST.Strict


-- | Complex numbers.
module Data.Complex

-- | Complex numbers are an algebraic type.
--   
--   For a complex number <tt>z</tt>, <tt><a>abs</a> z</tt> is a number
--   with the magnitude of <tt>z</tt>, but oriented in the positive real
--   direction, whereas <tt><a>signum</a> z</tt> has the phase of
--   <tt>z</tt>, but unit magnitude.
data Complex a

-- | forms a complex number from its real and imaginary rectangular
--   components.
(:+) :: !a -> !a -> Complex a

-- | Extracts the real part of a complex number.
realPart :: RealFloat a => Complex a -> a

-- | Extracts the imaginary part of a complex number.
imagPart :: RealFloat a => Complex a -> a

-- | Form a complex number from polar components of magnitude and phase.
mkPolar :: RealFloat a => a -> a -> Complex a

-- | <tt><a>cis</a> t</tt> is a complex value with magnitude <tt>1</tt> and
--   phase <tt>t</tt> (modulo <tt>2*<a>pi</a></tt>).
cis :: RealFloat a => a -> Complex a

-- | The function <a>polar</a> takes a complex number and returns a
--   (magnitude, phase) pair in canonical form: the magnitude is
--   nonnegative, and the phase in the range <tt>(-<a>pi</a>,
--   <a>pi</a>]</tt>; if the magnitude is zero, then so is the phase.
polar :: RealFloat a => Complex a -> (a, a)

-- | The nonnegative magnitude of a complex number.
magnitude :: RealFloat a => Complex a -> a

-- | The phase of a complex number, in the range <tt>(-<a>pi</a>,
--   <a>pi</a>]</tt>. If the magnitude is zero, then so is the phase.
phase :: RealFloat a => Complex a -> a

-- | The conjugate of a complex number.
conjugate :: RealFloat a => Complex a -> Complex a
instance Typeable1 Complex
instance Eq a => Eq (Complex a)
instance Show a => Show (Complex a)
instance Read a => Read (Complex a)
instance Data a => Data (Complex a)
instance RealFloat a => Floating (Complex a)
instance RealFloat a => Fractional (Complex a)
instance RealFloat a => Num (Complex a)


-- | This module defines a "Fixed" type for fixed-precision arithmetic. The
--   parameter to Fixed is any type that's an instance of HasResolution.
--   HasResolution has a single method that gives the resolution of the
--   Fixed type.
--   
--   This module also contains generalisations of div, mod, and divmod to
--   work with any Real instance.
module Data.Fixed

-- | generalisation of <a>div</a> to any instance of Real
div' :: (Real a, Integral b) => a -> a -> b

-- | generalisation of <a>mod</a> to any instance of Real
mod' :: Real a => a -> a -> a

-- | generalisation of <a>divMod</a> to any instance of Real
divMod' :: (Real a, Integral b) => a -> a -> (b, a)

-- | The type parameter should be an instance of <a>HasResolution</a>.
data Fixed a
class HasResolution a
resolution :: HasResolution a => p a -> Integer

-- | First arg is whether to chop off trailing zeros
showFixed :: HasResolution a => Bool -> Fixed a -> String
data E0

-- | resolution of 1, this works the same as Integer
type Uni = Fixed E0
data E1

-- | resolution of 10^-1 = .1
type Deci = Fixed E1
data E2

-- | resolution of 10^-2 = .01, useful for many monetary currencies
type Centi = Fixed E2
data E3

-- | resolution of 10^-3 = .001
type Milli = Fixed E3
data E6

-- | resolution of 10^-6 = .000001
type Micro = Fixed E6
data E9

-- | resolution of 10^-9 = .000000001
type Nano = Fixed E9
data E12

-- | resolution of 10^-12 = .000000000001
type Pico = Fixed E12
instance Typeable1 Fixed
instance Typeable E0
instance Typeable E1
instance Typeable E2
instance Typeable E3
instance Typeable E6
instance Typeable E9
instance Typeable E12
instance Eq (Fixed a)
instance Ord (Fixed a)
instance HasResolution E12
instance HasResolution E9
instance HasResolution E6
instance HasResolution E3
instance HasResolution E2
instance HasResolution E1
instance HasResolution E0
instance HasResolution a => Read (Fixed a)
instance HasResolution a => Show (Fixed a)
instance HasResolution a => RealFrac (Fixed a)
instance HasResolution a => Fractional (Fixed a)
instance HasResolution a => Real (Fixed a)
instance HasResolution a => Num (Fixed a)
instance Enum (Fixed a)
instance Typeable a => Data (Fixed a)


-- | The <a>Ix</a> class is used to map a contiguous subrange of values in
--   type onto integers. It is used primarily for array indexing (see the
--   array package).
module Data.Ix

-- | The <a>Ix</a> class is used to map a contiguous subrange of values in
--   a type onto integers. It is used primarily for array indexing (see the
--   array package).
--   
--   The first argument <tt>(l,u)</tt> of each of these operations is a
--   pair specifying the lower and upper bounds of a contiguous subrange of
--   values.
--   
--   An implementation is entitled to assume the following laws about these
--   operations:
--   
--   <ul>
--   <li><tt><a>inRange</a> (l,u) i == <a>elem</a> i (<a>range</a>
--   (l,u))</tt> <tt> </tt></li>
--   <li><tt><a>range</a> (l,u) <a>!!</a> <a>index</a> (l,u) i == i</tt>,
--   when <tt><a>inRange</a> (l,u) i</tt></li>
--   <li><tt><a>map</a> (<a>index</a> (l,u)) (<a>range</a> (l,u))) ==
--   [0..<a>rangeSize</a> (l,u)-1]</tt> <tt> </tt></li>
--   <li><tt><a>rangeSize</a> (l,u) == <a>length</a> (<a>range</a>
--   (l,u))</tt> <tt> </tt></li>
--   </ul>
--   
--   Minimal complete instance: <a>range</a>, <a>index</a> and
--   <a>inRange</a>.
class Ord a => Ix a where index b i | inRange b i = unsafeIndex b i | otherwise = hopelessIndexError unsafeIndex b i = index b i rangeSize b@(_l, h) | inRange b h = unsafeIndex b h + 1 | otherwise = 0 unsafeRangeSize b@(_l, h) = unsafeIndex b h + 1
range :: Ix a => (a, a) -> [a]
index :: Ix a => (a, a) -> a -> Int
inRange :: Ix a => (a, a) -> a -> Bool
rangeSize :: Ix a => (a, a) -> Int


-- | Standard functions on rational numbers
module Data.Ratio

-- | Rational numbers, with numerator and denominator of some
--   <a>Integral</a> type.
data Ratio a

-- | Arbitrary-precision rational numbers, represented as a ratio of two
--   <a>Integer</a> values. A rational number may be constructed using the
--   <a>%</a> operator.
type Rational = Ratio Integer

-- | Forms the ratio of two integral numbers.
(%) :: Integral a => a -> a -> Ratio a

-- | Extract the numerator of the ratio in reduced form: the numerator and
--   denominator have no common factor and the denominator is positive.
numerator :: Integral a => Ratio a -> a

-- | Extract the denominator of the ratio in reduced form: the numerator
--   and denominator have no common factor and the denominator is positive.
denominator :: Integral a => Ratio a -> a

-- | <a>approxRational</a>, applied to two real fractional numbers
--   <tt>x</tt> and <tt>epsilon</tt>, returns the simplest rational number
--   within <tt>epsilon</tt> of <tt>x</tt>. A rational number <tt>y</tt> is
--   said to be <i>simpler</i> than another <tt>y'</tt> if
--   
--   <ul>
--   <li><tt><a>abs</a> (<a>numerator</a> y) &lt;= <a>abs</a>
--   (<a>numerator</a> y')</tt>, and</li>
--   <li><tt><a>denominator</a> y &lt;= <a>denominator</a> y'</tt>.</li>
--   </ul>
--   
--   Any real interval contains a unique simplest rational; in particular,
--   note that <tt>0/1</tt> is the simplest rational of all.
approxRational :: RealFrac a => a -> a -> Rational


-- | Mutable references in the (strict) ST monad.
module Data.STRef

-- | a value of type <tt>STRef s a</tt> is a mutable variable in state
--   thread <tt>s</tt>, containing a value of type <tt>a</tt>
data STRef s a

-- | Build a new <a>STRef</a> in the current state thread
newSTRef :: a -> ST s (STRef s a)

-- | Read the value of an <a>STRef</a>
readSTRef :: STRef s a -> ST s a

-- | Write a new value into an <a>STRef</a>
writeSTRef :: STRef s a -> a -> ST s ()

-- | Mutate the contents of an <a>STRef</a>.
--   
--   Be warned that <a>modifySTRef</a> does not apply the function
--   strictly. This means if the program calls <a>modifySTRef</a> many
--   times, but seldomly uses the value, thunks will pile up in memory
--   resulting in a space leak. This is a common mistake made when using an
--   STRef as a counter. For example, the following will leak memory and
--   likely produce a stack overflow:
--   
--   <pre>
--   print $ runST $ do
--       ref &lt;- newSTRef 0
--       replicateM_ 1000000 $ modifySTRef ref (+1)
--       readSTRef ref
--   </pre>
--   
--   To avoid this problem, use <a>modifySTRef'</a> instead.
modifySTRef :: STRef s a -> (a -> a) -> ST s ()

-- | Strict version of <a>modifySTRef</a>
modifySTRef' :: STRef s a -> (a -> a) -> ST s ()


-- | Mutable references in the lazy ST monad.
module Data.STRef.Lazy

-- | a value of type <tt>STRef s a</tt> is a mutable variable in state
--   thread <tt>s</tt>, containing a value of type <tt>a</tt>
data STRef s a
newSTRef :: a -> ST s (STRef s a)
readSTRef :: STRef s a -> ST s a
writeSTRef :: STRef s a -> a -> ST s ()
modifySTRef :: STRef s a -> (a -> a) -> ST s ()


-- | Mutable references in the (strict) ST monad (re-export of
--   <a>Data.STRef</a>)
module Data.STRef.Strict


-- | A general library for representation and manipulation of versions.
--   
--   Versioning schemes are many and varied, so the version representation
--   provided by this library is intended to be a compromise between
--   complete generality, where almost no common functionality could
--   reasonably be provided, and fixing a particular versioning scheme,
--   which would probably be too restrictive.
--   
--   So the approach taken here is to provide a representation which
--   subsumes many of the versioning schemes commonly in use, and we
--   provide implementations of <a>Eq</a>, <a>Ord</a> and conversion
--   to/from <a>String</a> which will be appropriate for some applications,
--   but not all.
module Data.Version

-- | A <a>Version</a> represents the version of a software entity.
--   
--   An instance of <a>Eq</a> is provided, which implements exact equality
--   modulo reordering of the tags in the <a>versionTags</a> field.
--   
--   An instance of <a>Ord</a> is also provided, which gives lexicographic
--   ordering on the <a>versionBranch</a> fields (i.e. 2.1 &gt; 2.0, 1.2.3
--   &gt; 1.2.2, etc.). This is expected to be sufficient for many uses,
--   but note that you may need to use a more specific ordering for your
--   versioning scheme. For example, some versioning schemes may include
--   pre-releases which have tags <tt>"pre1"</tt>, <tt>"pre2"</tt>, and so
--   on, and these would need to be taken into account when determining
--   ordering. In some cases, date ordering may be more appropriate, so the
--   application would have to look for <tt>date</tt> tags in the
--   <a>versionTags</a> field and compare those. The bottom line is, don't
--   always assume that <a>compare</a> and other <a>Ord</a> operations are
--   the right thing for every <a>Version</a>.
--   
--   Similarly, concrete representations of versions may differ. One
--   possible concrete representation is provided (see <a>showVersion</a>
--   and <a>parseVersion</a>), but depending on the application a different
--   concrete representation may be more appropriate.
data Version
Version :: [Int] -> [String] -> Version

-- | The numeric branch for this version. This reflects the fact that most
--   software versions are tree-structured; there is a main trunk which is
--   tagged with versions at various points (1,2,3...), and the first
--   branch off the trunk after version 3 is 3.1, the second branch off the
--   trunk after version 3 is 3.2, and so on. The tree can be branched
--   arbitrarily, just by adding more digits.
--   
--   We represent the branch as a list of <a>Int</a>, so version 3.2.1
--   becomes [3,2,1]. Lexicographic ordering (i.e. the default instance of
--   <a>Ord</a> for <tt>[Int]</tt>) gives the natural ordering of branches.
versionBranch :: Version -> [Int]

-- | A version can be tagged with an arbitrary list of strings. The
--   interpretation of the list of tags is entirely dependent on the entity
--   that this version applies to.
versionTags :: Version -> [String]

-- | Provides one possible concrete representation for <a>Version</a>. For
--   a version with <a>versionBranch</a> <tt>= [1,2,3]</tt> and
--   <a>versionTags</a> <tt>= ["tag1","tag2"]</tt>, the output will be
--   <tt>1.2.3-tag1-tag2</tt>.
showVersion :: Version -> String

-- | A parser for versions in the format produced by <a>showVersion</a>.
parseVersion :: ReadP Version
instance Typeable Version
instance Read Version
instance Show Version
instance Ord Version
instance Eq Version


-- | This library provides facilities for parsing the command-line options
--   in a standalone program. It is essentially a Haskell port of the GNU
--   <tt>getopt</tt> library.
module System.Console.GetOpt

-- | Process the command-line, and return the list of values that matched
--   (and those that didn't). The arguments are:
--   
--   <ul>
--   <li>The order requirements (see <a>ArgOrder</a>)</li>
--   <li>The option descriptions (see <a>OptDescr</a>)</li>
--   <li>The actual command line arguments (presumably got from
--   <a>getArgs</a>).</li>
--   </ul>
--   
--   <a>getOpt</a> returns a triple consisting of the option arguments, a
--   list of non-options, and a list of error messages.
getOpt :: ArgOrder a -> [OptDescr a] -> [String] -> ([a], [String], [String])

-- | This is almost the same as <a>getOpt</a>, but returns a quadruple
--   consisting of the option arguments, a list of non-options, a list of
--   unrecognized options, and a list of error messages.
getOpt' :: ArgOrder a -> [OptDescr a] -> [String] -> ([a], [String], [String], [String])

-- | Return a string describing the usage of a command, derived from the
--   header (first argument) and the options described by the second
--   argument.
usageInfo :: String -> [OptDescr a] -> String

-- | What to do with options following non-options
data ArgOrder a

-- | no option processing after first non-option
RequireOrder :: ArgOrder a

-- | freely intersperse options and non-options
Permute :: ArgOrder a

-- | wrap non-options into options
ReturnInOrder :: (String -> a) -> ArgOrder a

-- | Each <a>OptDescr</a> describes a single option.
--   
--   The arguments to <a>Option</a> are:
--   
--   <ul>
--   <li>list of short option characters</li>
--   <li>list of long option strings (without "--")</li>
--   <li>argument descriptor</li>
--   <li>explanation of option for user</li>
--   </ul>
data OptDescr a
Option :: [Char] -> [String] -> (ArgDescr a) -> String -> OptDescr a

-- | Describes whether an option takes an argument or not, and if so how
--   the argument is injected into a value of type <tt>a</tt>.
data ArgDescr a

-- | no argument expected
NoArg :: a -> ArgDescr a

-- | option requires argument
ReqArg :: (String -> a) -> String -> ArgDescr a

-- | optional argument
OptArg :: (Maybe String -> a) -> String -> ArgDescr a


-- | The standard CPUTime library.
module System.CPUTime

-- | Computation <a>getCPUTime</a> returns the number of picoseconds CPU
--   time used by the current program. The precision of this result is
--   implementation-dependent.
getCPUTime :: IO Integer

-- | The <a>cpuTimePrecision</a> constant is the smallest measurable
--   difference in CPU time that the implementation can record, and is
--   given as an integral number of picoseconds.
cpuTimePrecision :: Integer


-- | Miscellaneous information about the system environment.
module System.Environment

-- | Computation <a>getArgs</a> returns a list of the program's command
--   line arguments (not including the program name).
getArgs :: IO [String]

-- | Computation <a>getProgName</a> returns the name of the program as it
--   was invoked.
--   
--   However, this is hard-to-impossible to implement on some non-Unix
--   OSes, so instead, for maximum portability, we just return the leafname
--   of the program as invoked. Even then there are some differences
--   between platforms: on Windows, for example, a program invoked as foo
--   is probably really <tt>FOO.EXE</tt>, and that is what
--   <a>getProgName</a> will return.
getProgName :: IO String

-- | Returns the absolute pathname of the current executable.
--   
--   Note that for scripts and interactive sessions, this is the path to
--   the interpreter (e.g. ghci.)
getExecutablePath :: IO FilePath

-- | Computation <a>getEnv</a> <tt>var</tt> returns the value of the
--   environment variable <tt>var</tt>. For the inverse, POSIX users can
--   use <a>putEnv</a>.
--   
--   This computation may fail with:
--   
--   <ul>
--   <li><a>isDoesNotExistError</a> if the environment variable does not
--   exist.</li>
--   </ul>
getEnv :: String -> IO String

-- | Return the value of the environment variable <tt>var</tt>, or
--   <tt>Nothing</tt> if there is no such value.
--   
--   For POSIX users, this is equivalent to <a>getEnv</a>.
lookupEnv :: String -> IO (Maybe String)

-- | <a>withArgs</a> <tt>args act</tt> - while executing action
--   <tt>act</tt>, have <a>getArgs</a> return <tt>args</tt>.
withArgs :: [String] -> IO a -> IO a

-- | <a>withProgName</a> <tt>name act</tt> - while executing action
--   <tt>act</tt>, have <a>getProgName</a> return <tt>name</tt>.
withProgName :: String -> IO a -> IO a

-- | <a>getEnvironment</a> retrieves the entire environment as a list of
--   <tt>(key,value)</tt> pairs.
--   
--   If an environment entry does not contain an <tt>'='</tt> character,
--   the <tt>key</tt> is the whole entry and the <tt>value</tt> is the
--   empty string.
getEnvironment :: IO [(String, String)]


-- | Exiting the program.
module System.Exit

-- | Defines the exit codes that a program can return.
data ExitCode

-- | indicates successful termination;
ExitSuccess :: ExitCode

-- | indicates program failure with an exit code. The exact interpretation
--   of the code is operating-system dependent. In particular, some values
--   may be prohibited (e.g. 0 on a POSIX-compliant system).
ExitFailure :: Int -> ExitCode

-- | Computation <a>exitWith</a> <tt>code</tt> throws <a>ExitCode</a>
--   <tt>code</tt>. Normally this terminates the program, returning
--   <tt>code</tt> to the program's caller.
--   
--   On program termination, the standard <tt>Handle</tt>s <tt>stdout</tt>
--   and <tt>stderr</tt> are flushed automatically; any other buffered
--   <tt>Handle</tt>s need to be flushed manually, otherwise the buffered
--   data will be discarded.
--   
--   A program that fails in any other way is treated as if it had called
--   <a>exitFailure</a>. A program that terminates successfully without
--   calling <a>exitWith</a> explicitly is treated as it it had called
--   <a>exitWith</a> <a>ExitSuccess</a>.
--   
--   As an <a>ExitCode</a> is not an <a>IOError</a>, <a>exitWith</a>
--   bypasses the error handling in the <a>IO</a> monad and cannot be
--   intercepted by <tt>catch</tt> from the <a>Prelude</a>. However it is a
--   <tt>SomeException</tt>, and can be caught using the functions of
--   <a>Control.Exception</a>. This means that cleanup computations added
--   with <a>bracket</a> (from <a>Control.Exception</a>) are also executed
--   properly on <a>exitWith</a>.
--   
--   Note: in GHC, <a>exitWith</a> should be called from the main program
--   thread in order to exit the process. When called from another thread,
--   <a>exitWith</a> will throw an <tt>ExitException</tt> as normal, but
--   the exception will not cause the process itself to exit.
exitWith :: ExitCode -> IO a

-- | The computation <a>exitFailure</a> is equivalent to <a>exitWith</a>
--   <tt>(</tt><a>ExitFailure</a> <i>exitfail</i><tt>)</tt>, where
--   <i>exitfail</i> is implementation-dependent.
exitFailure :: IO a

-- | The computation <a>exitSuccess</a> is equivalent to <a>exitWith</a>
--   <a>ExitSuccess</a>, It terminates the program successfully.
exitSuccess :: IO a


-- | Information about the characteristics of the host system lucky enough
--   to run your program.
module System.Info

-- | The operating system on which the program is running.
os :: String

-- | The machine architecture on which the program is running.
arch :: String

-- | The Haskell implementation with which the program was compiled or is
--   being interpreted.
compilerName :: String

-- | The version of <a>compilerName</a> with which the program was compiled
--   or is being interpreted.
compilerVersion :: Version


-- | Memory-related system things.
module System.Mem

-- | Triggers an immediate garbage collection
performGC :: IO ()


-- | Stable names are a way of performing fast (O(1)), not-quite-exact
--   comparison between objects.
--   
--   Stable names solve the following problem: suppose you want to build a
--   hash table with Haskell objects as keys, but you want to use pointer
--   equality for comparison; maybe because the keys are large and hashing
--   would be slow, or perhaps because the keys are infinite in size. We
--   can't build a hash table using the address of the object as the key,
--   because objects get moved around by the garbage collector, meaning a
--   re-hash would be necessary after every garbage collection.
module System.Mem.StableName

-- | An abstract name for an object, that supports equality and hashing.
--   
--   Stable names have the following property:
--   
--   <ul>
--   <li>If <tt>sn1 :: StableName</tt> and <tt>sn2 :: StableName</tt> and
--   <tt>sn1 == sn2</tt> then <tt>sn1</tt> and <tt>sn2</tt> were created by
--   calls to <tt>makeStableName</tt> on the same object.</li>
--   </ul>
--   
--   The reverse is not necessarily true: if two stable names are not
--   equal, then the objects they name may still be equal. Note in
--   particular that <tt>mkStableName</tt> may return a different
--   <a>StableName</a> after an object is evaluated.
--   
--   Stable Names are similar to Stable Pointers
--   (<a>Foreign.StablePtr</a>), but differ in the following ways:
--   
--   <ul>
--   <li>There is no <tt>freeStableName</tt> operation, unlike
--   <a>Foreign.StablePtr</a>s. Stable names are reclaimed by the runtime
--   system when they are no longer needed.</li>
--   <li>There is no <tt>deRefStableName</tt> operation. You can't get back
--   from a stable name to the original Haskell object. The reason for this
--   is that the existence of a stable name for an object does not
--   guarantee the existence of the object itself; it can still be garbage
--   collected.</li>
--   </ul>
data StableName a

-- | Makes a <a>StableName</a> for an arbitrary object. The object passed
--   as the first argument is not evaluated by <a>makeStableName</a>.
makeStableName :: a -> IO (StableName a)

-- | Convert a <a>StableName</a> to an <a>Int</a>. The <a>Int</a> returned
--   is not necessarily unique; several <a>StableName</a>s may map to the
--   same <a>Int</a> (in practice however, the chances of this are small,
--   so the result of <a>hashStableName</a> makes a good hash key).
hashStableName :: StableName a -> Int
instance Typeable1 StableName
instance Eq (StableName a)


-- | In general terms, a weak pointer is a reference to an object that is
--   not followed by the garbage collector - that is, the existence of a
--   weak pointer to an object has no effect on the lifetime of that
--   object. A weak pointer can be de-referenced to find out whether the
--   object it refers to is still alive or not, and if so to return the
--   object itself.
--   
--   Weak pointers are particularly useful for caches and memo tables. To
--   build a memo table, you build a data structure mapping from the
--   function argument (the key) to its result (the value). When you apply
--   the function to a new argument you first check whether the key/value
--   pair is already in the memo table. The key point is that the memo
--   table itself should not keep the key and value alive. So the table
--   should contain a weak pointer to the key, not an ordinary pointer. The
--   pointer to the value must not be weak, because the only reference to
--   the value might indeed be from the memo table.
--   
--   So it looks as if the memo table will keep all its values alive for
--   ever. One way to solve this is to purge the table occasionally, by
--   deleting entries whose keys have died.
--   
--   The weak pointers in this library support another approach, called
--   <i>finalization</i>. When the key referred to by a weak pointer dies,
--   the storage manager arranges to run a programmer-specified finalizer.
--   In the case of memo tables, for example, the finalizer could remove
--   the key/value pair from the memo table.
--   
--   Another difficulty with the memo table is that the value of a
--   key/value pair might itself contain a pointer to the key. So the memo
--   table keeps the value alive, which keeps the key alive, even though
--   there may be no other references to the key so both should die. The
--   weak pointers in this library provide a slight generalisation of the
--   basic weak-pointer idea, in which each weak pointer actually contains
--   both a key and a value.
module System.Mem.Weak

-- | A weak pointer object with a key and a value. The value has type
--   <tt>v</tt>.
--   
--   A weak pointer expresses a relationship between two objects, the
--   <i>key</i> and the <i>value</i>: if the key is considered to be alive
--   by the garbage collector, then the value is also alive. A reference
--   from the value to the key does <i>not</i> keep the key alive.
--   
--   A weak pointer may also have a finalizer of type <tt>IO ()</tt>; if it
--   does, then the finalizer will be run at most once, at a time after the
--   key has become unreachable by the program ("dead"). The storage
--   manager attempts to run the finalizer(s) for an object soon after the
--   object dies, but promptness is not guaranteed.
--   
--   It is not guaranteed that a finalizer will eventually run, and no
--   attempt is made to run outstanding finalizers when the program exits.
--   Therefore finalizers should not be relied on to clean up resources -
--   other methods (eg. exception handlers) should be employed, possibly in
--   addition to finalizers.
--   
--   References from the finalizer to the key are treated in the same way
--   as references from the value to the key: they do not keep the key
--   alive. A finalizer may therefore ressurrect the key, perhaps by
--   storing it in the same data structure.
--   
--   The finalizer, and the relationship between the key and the value,
--   exist regardless of whether the program keeps a reference to the
--   <a>Weak</a> object or not.
--   
--   There may be multiple weak pointers with the same key. In this case,
--   the finalizers for each of these weak pointers will all be run in some
--   arbitrary order, or perhaps concurrently, when the key dies. If the
--   programmer specifies a finalizer that assumes it has the only
--   reference to an object (for example, a file that it wishes to close),
--   then the programmer must ensure that there is only one such finalizer.
--   
--   If there are no other threads to run, the runtime system will check
--   for runnable finalizers before declaring the system to be deadlocked.
--   
--   WARNING: weak pointers to ordinary non-primitive Haskell types are
--   particularly fragile, because the compiler is free to optimise away or
--   duplicate the underlying data structure. Therefore attempting to place
--   a finalizer on an ordinary Haskell type may well result in the
--   finalizer running earlier than you expected. This is not a problem for
--   caches and memo tables where early finalization is benign.
--   
--   Finalizers <i>can</i> be used reliably for types that are created
--   explicitly and have identity, such as <tt>IORef</tt> and
--   <tt>MVar</tt>. However, to place a finalizer on one of these types,
--   you should use the specific operation provided for that type, e.g.
--   <tt>mkWeakIORef</tt> and <tt>addMVarFinalizer</tt> respectively (the
--   non-uniformity is accidental). These operations attach the finalizer
--   to the primitive object inside the box (e.g. <tt>MutVar#</tt> in the
--   case of <tt>IORef</tt>), because attaching the finalizer to the box
--   itself fails when the outer box is optimised away by the compiler.
data Weak v

-- | Establishes a weak pointer to <tt>k</tt>, with value <tt>v</tt> and a
--   finalizer.
--   
--   This is the most general interface for building a weak pointer.
mkWeak :: k -> v -> Maybe (IO ()) -> IO (Weak v)

-- | Dereferences a weak pointer. If the key is still alive, then
--   <tt><a>Just</a> v</tt> is returned (where <tt>v</tt> is the
--   <i>value</i> in the weak pointer), otherwise <a>Nothing</a> is
--   returned.
--   
--   The return value of <a>deRefWeak</a> depends on when the garbage
--   collector runs, hence it is in the <a>IO</a> monad.
deRefWeak :: Weak v -> IO (Maybe v)

-- | Causes a the finalizer associated with a weak pointer to be run
--   immediately.
finalize :: Weak v -> IO ()

-- | A specialised version of <a>mkWeak</a>, where the key and the value
--   are the same object:
--   
--   <pre>
--   mkWeakPtr key finalizer = mkWeak key key finalizer
--   </pre>
mkWeakPtr :: k -> Maybe (IO ()) -> IO (Weak k)

-- | A specialised version of <a>mkWeakPtr</a>, where the <a>Weak</a>
--   object returned is simply thrown away (however the finalizer will be
--   remembered by the garbage collector, and will still be run when the
--   key becomes unreachable).
--   
--   Note: adding a finalizer to a <a>ForeignPtr</a> using
--   <a>addFinalizer</a> won't work; use the specialised version
--   <a>addForeignPtrFinalizer</a> instead. For discussion see the
--   <a>Weak</a> type. .
addFinalizer :: key -> IO () -> IO ()

-- | A specialised version of <a>mkWeak</a> where the value is actually a
--   pair of the key and value passed to <a>mkWeakPair</a>:
--   
--   <pre>
--   mkWeakPair key val finalizer = mkWeak key (key,val) finalizer
--   </pre>
--   
--   The advantage of this is that the key can be retrieved by
--   <a>deRefWeak</a> in addition to the value.
mkWeakPair :: k -> v -> Maybe (IO ()) -> IO (Weak (k, v))


-- | A C printf like formatter.
module Text.Printf

-- | Format a variable number of arguments with the C-style formatting
--   string. The return value is either <a>String</a> or <tt>(<a>IO</a>
--   a)</tt>.
--   
--   The format string consists of ordinary characters and /conversion
--   specifications/, which specify how to format one of the arguments to
--   printf in the output string. A conversion specification begins with
--   the character <tt>%</tt>, followed by one or more of the following
--   flags:
--   
--   <pre>
--   -      left adjust (default is right adjust)
--   +      always use a sign (+ or -) for signed conversions
--   0      pad with zeroes rather than spaces
--   </pre>
--   
--   followed optionally by a field width:
--   
--   <pre>
--   num    field width
--   *      as num, but taken from argument list
--   </pre>
--   
--   followed optionally by a precision:
--   
--   <pre>
--   .num   precision (number of decimal places)
--   </pre>
--   
--   and finally, a format character:
--   
--   <pre>
--   c      character               Char, Int, Integer, ...
--   d      decimal                 Char, Int, Integer, ...
--   o      octal                   Char, Int, Integer, ...
--   x      hexadecimal             Char, Int, Integer, ...
--   X      hexadecimal             Char, Int, Integer, ...
--   u      unsigned decimal        Char, Int, Integer, ...
--   f      floating point          Float, Double
--   g      general format float    Float, Double
--   G      general format float    Float, Double
--   e      exponent format float   Float, Double
--   E      exponent format float   Float, Double
--   s      string                  String
--   </pre>
--   
--   Mismatch between the argument types and the format string will cause
--   an exception to be thrown at runtime.
--   
--   Examples:
--   
--   <pre>
--   &gt; printf "%d\n" (23::Int)
--   23
--   &gt; printf "%s %s\n" "Hello" "World"
--   Hello World
--   &gt; printf "%.2f\n" pi
--   3.14
--   </pre>
printf :: PrintfType r => String -> r

-- | Similar to <a>printf</a>, except that output is via the specified
--   <a>Handle</a>. The return type is restricted to <tt>(<a>IO</a>
--   a)</tt>.
hPrintf :: HPrintfType r => Handle -> String -> r

-- | The <a>PrintfType</a> class provides the variable argument magic for
--   <a>printf</a>. Its implementation is intentionally not visible from
--   this module. If you attempt to pass an argument of a type which is not
--   an instance of this class to <a>printf</a> or <a>hPrintf</a>, then the
--   compiler will report it as a missing instance of <a>PrintfArg</a>.
class PrintfType t

-- | The <a>HPrintfType</a> class provides the variable argument magic for
--   <a>hPrintf</a>. Its implementation is intentionally not visible from
--   this module.
class HPrintfType t
class PrintfArg a
class IsChar c
instance [safe] IsChar Char
instance [safe] PrintfArg Double
instance [safe] PrintfArg Float
instance [safe] PrintfArg Integer
instance [safe] PrintfArg Word64
instance [safe] PrintfArg Word32
instance [safe] PrintfArg Word16
instance [safe] PrintfArg Word8
instance [safe] PrintfArg Word
instance [safe] PrintfArg Int64
instance [safe] PrintfArg Int32
instance [safe] PrintfArg Int16
instance [safe] PrintfArg Int8
instance [safe] PrintfArg Int
instance [safe] IsChar c => PrintfArg [c]
instance [safe] PrintfArg Char
instance [safe] (PrintfArg a, HPrintfType r) => HPrintfType (a -> r)
instance [safe] (PrintfArg a, PrintfType r) => PrintfType (a -> r)
instance [safe] HPrintfType (IO a)
instance [safe] PrintfType (IO a)
instance [safe] IsChar c => PrintfType [c]


-- | Optional instance of <a>Show</a> for functions:
--   
--   <pre>
--   instance Show (a -&gt; b) where
--   	showsPrec _ _ = showString \"\&lt;function\&gt;\"
--   </pre>
module Text.Show.Functions
instance [safe] Show (a -> b)
