-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | A compatibility layer for base -- -- Provides functions available in later versions of base to a -- wider range of compilers, without requiring you to use CPP pragmas in -- your code. See the README for what is covered. Also see the -- changelog for recent changes. -- -- Note that base-compat does not add any orphan instances. -- There is a separate package, base-orphans, for that. -- -- In addition, base-compat does not backport any data types or -- type classes. See this section of the README for more -- info. -- -- base-compat is designed to have zero dependencies. For a -- version of base-compat that depends on compatibility -- libraries for a wider support window, see the -- base-compat-batteries package. Most of the modules in -- this library have the same names as in base-compat-batteries -- to make it easier to switch between the two. There also exist versions -- of each module with the suffix .Repl, which are distinct from -- anything in base-compat-batteries, to allow for easier use in -- GHCi. @package base-compat @version 0.10.5 module Control.Concurrent.Compat -- | Fork a thread and call the supplied function when the thread is about -- to terminate, with an exception or a returned value. The function is -- called with asynchronous exceptions masked. -- --
-- forkFinally action and_then = -- mask $ \restore -> -- forkIO $ try (restore action) >>= and_then ---- -- This function is useful for informing the parent when a child -- terminates, for example. forkFinally :: () => IO a -> Either SomeException a -> IO () -> IO ThreadId -- | Like forkIOWithUnmask, but the child thread is a bound thread, -- as with forkOS. forkOSWithUnmask :: forall a. () => IO a -> IO a -> IO () -> IO ThreadId -- | Reexports Control.Concurrent.Compat from a globally unique -- namespace. module Control.Concurrent.Compat.Repl module Control.Concurrent.MVar.Compat -- | Like withMVar, but the IO action in the second -- argument is executed with asynchronous exceptions masked. withMVarMasked :: () => MVar a -> a -> IO b -> IO b -- | Reexports Control.Concurrent.MVar.Compat from a globally unique -- namespace. module Control.Concurrent.MVar.Compat.Repl module Control.Exception.Compat -- | If the first argument evaluates to True, then the result is the -- second argument. Otherwise an AssertionFailed exception is -- raised, containing a String with the source file and line -- number of the call to assert. -- -- Assertions can normally be turned on or off with a compiler flag (for -- GHC, assertions are normally on unless optimisation is turned on with -- -O or the -fignore-asserts option is given). When -- assertions are turned off, the first argument to assert is -- ignored, and the second argument is returned as the result. assert :: () => Bool -> a -> a -- | When invoked inside mask, this function allows a masked -- asynchronous exception to be raised, if one exists. It is equivalent -- to performing an interruptible operation (see #interruptible), but -- does not involve any actual blocking. -- -- When called outside mask, or inside uninterruptibleMask, -- this function has no effect. allowInterrupt :: IO () -- | Sometimes you want to catch two different sorts of exception. You -- could do something like -- --
-- f = expr `catch` \ (ex :: ArithException) -> handleArith ex -- `catch` \ (ex :: IOException) -> handleIO ex ---- -- 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 -- handleArith throws an IOException then the second -- exception handler will catch it. -- -- Instead, we provide a function catches, which would be used -- thus: -- --
-- f = expr `catches` [Handler (\ (ex :: ArithException) -> handleArith ex), -- Handler (\ (ex :: IOException) -> handleIO ex)] --catches :: () => IO a -> [Handler a] -> IO a -- | You need this when using catches. data Handler a [Handler] :: Handler a -- | Like bracket, 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 variant of bracket where the return value from the first -- computation is not required. bracket_ :: () => IO a -> IO b -> IO c -> IO c -- | A specialised variant of bracket with just a computation to run -- afterward. finally :: () => IO a -> IO b -> IO 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 bracket, because -- bracket will install the necessary exception handler to release -- the resource in the event that an exception is raised during the -- computation. If an exception is raised, then bracket will -- re-raise the exception (after performing the release). -- -- A common example is opening a file: -- --
-- bracket
-- (openFile "filename" ReadMode)
-- (hClose)
-- (\fileHandle -> do { ... })
--
--
-- The arguments to bracket are in this order so that we can
-- partially apply it, e.g.:
--
-- -- withFile name mode = bracket (openFile name mode) hClose --bracket :: () => IO a -> a -> IO b -> a -> IO c -> IO c -- | Like finally, but only performs the final action if there was -- an exception raised by the computation. onException :: () => IO a -> IO b -> IO a -- | A variant of try that takes an exception predicate to select -- which exceptions are caught (c.f. catchJust). If the exception -- does not match the predicate, it is re-thrown. tryJust :: Exception e => e -> Maybe b -> IO a -> IO Either b a -- | Similar to catch, but returns an Either result which is -- (Right a) if no exception of type e was -- raised, or (Left ex) if an exception of type -- e was raised and its value is ex. If any other type -- of exception is raised than it will be propogated up to the next -- enclosing exception handler. -- --
-- try a = catch (Right `liftM` a) (return . Left) --try :: Exception e => IO a -> IO Either e 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 -- | A version of catchJust with the arguments swapped around (see -- handle). handleJust :: Exception e => e -> Maybe b -> b -> IO a -> IO a -> IO a -- | A version of catch with the arguments swapped around; useful in -- situations where the code for the handler is shorter. For example: -- --
-- do handle (\NonTermination -> exitWith (ExitFailure 1)) $ -- ... --handle :: Exception e => e -> IO a -> IO a -> IO a -- | The function catchJust is like catch, but it takes an -- extra argument which is an exception predicate, a function -- which selects which type of exceptions we're interested in. -- --
-- catchJust (\e -> if isDoesNotExistErrorType (ioeGetErrorType e) then Just () else Nothing)
-- (readFile f)
-- (\_ -> do hPutStrLn stderr ("No such file: " ++ show f)
-- return "")
--
--
-- Any other exceptions which are not matched by the predicate are
-- re-raised, and may be caught by an enclosing catch,
-- catchJust, etc.
catchJust :: Exception e => e -> Maybe b -> IO a -> b -> IO a -> IO a
-- | A pattern match failed. The String gives information about
-- the source location of the pattern.
newtype PatternMatchFail
PatternMatchFail :: String -> PatternMatchFail
-- | 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 String gives information about the source
-- location of the record selector.
newtype RecSelError
RecSelError :: String -> RecSelError
-- | An uninitialised record field was used. The String gives
-- information about the source location where the record was
-- constructed.
newtype RecConError
RecConError :: String -> RecConError
-- | 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 String gives information about the source
-- location of the record update.
newtype RecUpdError
RecUpdError :: String -> RecUpdError
-- | A class method without a definition (neither a default definition, nor
-- a definition in the appropriate instance) was called. The
-- String gives information about which method it was.
newtype NoMethodError
NoMethodError :: String -> NoMethodError
-- | An expression that didn't typecheck during compile time was called.
-- This is only possible with -fdefer-type-errors. The String
-- gives details about the failed type check.
newtype TypeError
TypeError :: String -> TypeError
-- | 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 atomically, from the
-- stm package, inside another call to atomically.
data NestedAtomically
NestedAtomically :: NestedAtomically
-- | throwTo raises an arbitrary exception in the target thread (GHC
-- only).
--
-- Exception delivery synchronizes between the source and target thread:
-- throwTo 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. Exception delivery is also
-- atomic with respect to other exceptions. Atomicity is a useful
-- property to have when dealing with race conditions: e.g. 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 throwTo will not
-- return) until the call has completed. This is the case regardless of
-- whether the call is inside a mask or not. However, in GHC a
-- foreign call can be annotated as interruptible, in which case
-- a throwTo will cause the RTS to attempt to cause the call to
-- return; see the GHC documentation for more details.
--
-- Important note: the behaviour of throwTo differs from that
-- described in the paper "Asynchronous exceptions in Haskell"
-- (http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm).
-- In the paper, throwTo is non-blocking; but the library
-- implementation adopts a more synchronous design in which
-- throwTo 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, throwTo is therefore interruptible
-- (see Section 5.3 of the paper). Unlike other interruptible operations,
-- however, throwTo is always 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 safe point, 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
-- throwTo.
--
-- If the target of throwTo is the calling thread, then the
-- behaviour is the same as throwIO, 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 unsafePerformIO or
-- unsafeInterleaveIO, that computation is not permanently
-- replaced by the exception, but is suspended as if it had received an
-- asynchronous exception.
--
-- Note that if throwTo is called with the current thread as the
-- target, the exception will be thrown even if the thread is currently
-- inside mask or uninterruptibleMask.
throwTo :: Exception e => ThreadId -> e -> IO ()
-- | Raise an IOError in the IO monad.
ioError :: () => IOError -> IO a
asyncExceptionFromException :: Exception e => SomeException -> Maybe e
asyncExceptionToException :: Exception e => e -> SomeException
-- | The thread is blocked on an MVar, but there are no other
-- references to the MVar 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 TVars involved, so it can't ever
-- continue.
data BlockedIndefinitelyOnSTM
BlockedIndefinitelyOnSTM :: BlockedIndefinitelyOnSTM
-- | There are no runnable threads, so the program is deadlocked. The
-- Deadlock exception is raised in the main thread only.
data Deadlock
Deadlock :: Deadlock
-- | This thread has exceeded its allocation limit. See
-- setAllocationCounter and enableAllocationLimit.
data AllocationLimitExceeded
AllocationLimitExceeded :: AllocationLimitExceeded
-- | Compaction found an object that cannot be compacted. Functions cannot
-- be compacted, nor can mutable objects or pinned objects. See
-- compact.
newtype CompactionFailed
CompactionFailed :: String -> CompactionFailed
-- | assert was applied to False.
newtype AssertionFailed
AssertionFailed :: String -> AssertionFailed
-- | Superclass for asynchronous exceptions.
data SomeAsyncException
[SomeAsyncException] :: SomeAsyncException
-- | 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:
--
-- -- evaluate $ force x ---- -- There is a subtle difference between evaluate x and -- return $! x, analogous to the difference -- between throwIO and throw. If the lazy value x -- throws an exception, return $! x will fail to -- return an IO action and will throw an exception instead. -- evaluate x, on the other hand, always produces an -- IO action; that action will throw an exception upon -- execution iff x throws an exception upon -- evaluation. -- -- The practical implication of this difference is that due to the -- imprecise exceptions semantics, -- --
-- (return $! error "foo") >> error "bar" ---- -- may throw either "foo" or "bar", depending on the -- optimizations performed by the compiler. On the other hand, -- --
-- evaluate (error "foo") >> error "bar" ---- -- is guaranteed to throw "foo". -- -- The rule of thumb is to use evaluate to force or handle -- exceptions in lazy values. If, on the other hand, you are forcing a -- lazy value for efficiency reasons only and do not care about -- exceptions, you may use return $! x. evaluate :: () => a -> IO a -- | Like mask, but the masked computation is not interruptible (see -- Control.Exception#interruptible). THIS SHOULD BE USED WITH -- GREAT CARE, because if a thread executing in -- uninterruptibleMask 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 uninterruptibleMask, but does not pass a restore -- action to the argument. uninterruptibleMask_ :: () => IO a -> IO a -- | Executes an IO computation with asynchronous exceptions masked. -- That is, any thread which attempts to raise an exception in the -- current thread with throwTo will be blocked until asynchronous -- exceptions are unmasked again. -- -- The argument passed to mask is a function that takes as its -- argument another function, which can be used to restore the prevailing -- masking state within the context of the masked computation. For -- example, a common way to use mask is to protect the acquisition -- of a resource: -- --
-- mask $ \restore -> do -- x <- acquire -- restore (do_something_with x) `onException` release -- release ---- -- This code guarantees that acquire is paired with -- release, by masking asynchronous exceptions for the critical -- parts. (Rather than write this code yourself, it would be better to -- use bracket which abstracts the general pattern). -- -- Note that the restore action passed to the argument to -- mask does not necessarily unmask asynchronous exceptions, it -- just restores the masking state to that of the enclosing context. Thus -- if asynchronous exceptions are already masked, mask cannot be -- used to unmask exceptions again. This is so that if you call a library -- function with exceptions masked, you can be sure that the library call -- will not be able to unmask exceptions again. If you are writing -- library code and need to use asynchronous exceptions, the only way is -- to create a new thread; see forkIOWithUnmask. -- -- Asynchronous exceptions may still be received while in the masked -- state if the masked thread blocks in certain ways; see -- Control.Exception#interruptible. -- -- Threads created by forkIO inherit the MaskingState from -- the parent; that is, to start a thread in the -- MaskedInterruptible state, use mask_ $ forkIO .... -- This is particularly useful if you need to establish an exception -- handler in the forked thread before any asynchronous exceptions are -- received. To create a a new thread in an unmasked state use -- forkIOWithUnmask. mask :: () => forall a. () => IO a -> IO a -> IO b -> IO b -- | Like mask, but does not pass a restore action to the -- argument. mask_ :: () => IO a -> IO a -- | Returns the MaskingState for the current thread. getMaskingState :: IO MaskingState -- | Allow asynchronous exceptions to be raised even inside mask, -- making the operation interruptible (see the discussion of -- "Interruptible operations" in Exception). -- -- When called outside mask, or inside uninterruptibleMask, -- this function has no effect. interruptible :: () => IO a -> IO a -- | A variant of throw that can only be used within the IO -- monad. -- -- Although throwIO has a type that is an instance of the type of -- throw, the two functions are subtly different: -- --
-- throw e `seq` x ===> throw e -- throwIO e `seq` x ===> x ---- -- The first example will cause the exception e to be raised, -- whereas the second one won't. In fact, throwIO will only cause -- an exception to be raised when it is used within the IO monad. -- The throwIO variant should be used in preference to -- throw to raise an exception within the IO monad because -- it guarantees ordering with respect to other IO operations, -- whereas throw does not. throwIO :: Exception e => e -> IO a -- | This is the simplest of the exception-catching functions. It takes a -- single argument, runs it, and if an exception is raised the "handler" -- is executed, with the value of the exception passed as an argument. -- Otherwise, the result is returned as normal. For example: -- --
-- catch (readFile f)
-- (\e -> do let err = show (e :: IOException)
-- hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err)
-- return "")
--
--
-- Note that we have to give a type signature to e, or the
-- program will not typecheck as the type is ambiguous. While it is
-- possible to catch exceptions of any type, see the section "Catching
-- all exceptions" (in Control.Exception) for an explanation of
-- the problems with doing so.
--
-- For catching exceptions in pure (non-IO) expressions, see the
-- function evaluate.
--
-- Note that due to Haskell's unspecified evaluation order, an expression
-- may throw one of several possible exceptions: consider the expression
-- (error "urk") + (1 `div` 0). Does the expression throw
-- ErrorCall "urk", or DivideByZero?
--
-- The answer is "it might throw either"; the choice is
-- non-deterministic. If you are catching any type of exception then you
-- might catch either. If you are calling catch with type IO
-- Int -> (ArithException -> IO Int) -> IO Int then the
-- handler may get run with DivideByZero as an argument, or an
-- ErrorCall "urk" exception may be propogated further up. If
-- you call it again, you might get a the opposite behaviour. This is ok,
-- because catch is an IO computation.
catch :: Exception e => IO a -> e -> 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 mask: asynchronous exceptions are masked, but
-- blocking operations may still be interrupted
MaskedInterruptible :: MaskingState
-- | the state during uninterruptibleMask: asynchronous exceptions
-- are masked, and blocking operations may not be interrupted
MaskedUninterruptible :: MaskingState
-- | Exceptions that occur in the IO monad. An
-- IOException records a more specific error type, a descriptive
-- string and maybe the handle that was used when the error was flagged.
data IOException
-- | Any type that you wish to throw or catch as an exception must be an
-- instance of the Exception class. The simplest case is a new
-- exception type directly below the root:
--
-- -- data MyException = ThisException | ThatException -- deriving Show -- -- instance Exception MyException ---- -- The default method definitions in the Exception class do what -- we need in this case. You can now throw and catch -- ThisException and ThatException as exceptions: -- --
-- *Main> throw ThisException `catch` \e -> putStrLn ("Caught " ++ show (e :: MyException))
-- Caught ThisException
--
--
-- In more complicated examples, you may wish to define a whole hierarchy
-- of exceptions:
--
-- -- --------------------------------------------------------------------- -- -- Make the root exception type for all the exceptions in a compiler -- -- data SomeCompilerException = forall e . Exception e => SomeCompilerException e -- -- instance Show SomeCompilerException where -- show (SomeCompilerException e) = show e -- -- instance Exception SomeCompilerException -- -- compilerExceptionToException :: Exception e => e -> SomeException -- compilerExceptionToException = toException . SomeCompilerException -- -- compilerExceptionFromException :: Exception e => SomeException -> Maybe e -- compilerExceptionFromException x = do -- SomeCompilerException a <- fromException x -- cast a -- -- --------------------------------------------------------------------- -- -- Make a subhierarchy for exceptions in the frontend of the compiler -- -- data SomeFrontendException = forall e . Exception e => SomeFrontendException e -- -- instance Show SomeFrontendException where -- show (SomeFrontendException e) = show e -- -- instance Exception SomeFrontendException where -- toException = compilerExceptionToException -- fromException = compilerExceptionFromException -- -- frontendExceptionToException :: Exception e => e -> SomeException -- frontendExceptionToException = toException . SomeFrontendException -- -- frontendExceptionFromException :: Exception e => SomeException -> Maybe e -- frontendExceptionFromException x = do -- SomeFrontendException a <- fromException x -- cast a -- -- --------------------------------------------------------------------- -- -- Make an exception type for a particular frontend compiler exception -- -- data MismatchedParentheses = MismatchedParentheses -- deriving Show -- -- instance Exception MismatchedParentheses where -- toException = frontendExceptionToException -- fromException = frontendExceptionFromException ---- -- We can now catch a MismatchedParentheses exception as -- MismatchedParentheses, SomeFrontendException or -- SomeCompilerException, but not other types, e.g. -- IOException: -- --
-- *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: MismatchedParentheses))
-- Caught MismatchedParentheses
-- *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeFrontendException))
-- Caught MismatchedParentheses
-- *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeCompilerException))
-- Caught MismatchedParentheses
-- *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: IOException))
-- *** Exception: MismatchedParentheses
--
class (Typeable e, Show e) => Exception e
toException :: Exception e => e -> SomeException
fromException :: Exception e => SomeException -> Maybe e
-- | Render this exception value in a human-friendly manner.
--
-- Default implementation: show.
displayException :: Exception e => e -> String
-- | This is thrown when the user calls error. The first
-- String is the argument given to error, second
-- String is the location.
data ErrorCall
ErrorCallWithLocation :: String -> String -> ErrorCall
-- | Arithmetic exceptions.
data ArithException
Overflow :: ArithException
Underflow :: ArithException
LossOfPrecision :: ArithException
DivideByZero :: ArithException
Denormal :: ArithException
RatioZeroDenominator :: ArithException
-- | The SomeException type is the root of the exception type
-- hierarchy. When an exception of type e is thrown, behind the
-- scenes it is encapsulated in a SomeException.
data SomeException
[SomeException] :: SomeException
-- | Throw an exception. Exceptions may be thrown from purely functional
-- code, but may only be caught within the IO monad.
throw :: forall (r :: RuntimeRep). forall (a :: TYPE r). forall e. Exception e => e -> a
-- | Reexports Control.Exception.Compat from a globally unique
-- namespace.
module Control.Exception.Compat.Repl
module Control.Monad.Compat
-- | The Monad class defines the basic operations over a
-- monad, a concept from a branch of mathematics known as
-- category theory. From the perspective of a Haskell programmer,
-- however, it is best to think of a monad as an abstract datatype
-- of actions. Haskell's do expressions provide a convenient
-- syntax for writing monadic expressions.
--
-- Instances of Monad should satisfy the following laws:
--
--
--
-- Furthermore, the Monad and Applicative operations should
-- relate as follows:
--
--
--
-- The above laws imply:
--
--
--
-- and that pure and (<*>) satisfy the applicative
-- functor laws.
--
-- The instances of Monad for lists, Maybe and IO
-- defined in the Prelude satisfy these laws.
class Applicative m => Monad (m :: * -> *)
-- | Sequentially compose two actions, passing any value produced by the
-- first as an argument to the second.
(>>=) :: Monad m => m a -> a -> m b -> m b
-- | Sequentially compose two actions, discarding any value produced by the
-- first, like sequencing operators (such as the semicolon) in imperative
-- languages.
(>>) :: Monad m => m a -> m b -> m b
-- | Inject a value into the monadic type.
return :: Monad m => a -> m a
-- | Fail with a message. This operation is not part of the mathematical
-- definition of a monad, but is invoked on pattern-match failure in a
-- do expression.
--
-- As part of the MonadFail proposal (MFP), this function is moved to its
-- own class MonadFail (see Control.Monad.Fail for more
-- details). The definition here will be removed in a future release.
fail :: Monad m => String -> m a
-- | Monads that also support choice and failure.
class (Alternative m, Monad m) => MonadPlus (m :: * -> *)
-- | The identity of mplus. It should also satisfy the equations
--
-- -- mzero >>= f = mzero -- v >> mzero = mzero ---- -- The default definition is -- --
-- mzero = empty --mzero :: MonadPlus m => m a -- | An associative operation. The default definition is -- --
-- mplus = (<|>) --mplus :: MonadPlus m => m a -> m a -> m a -- | Reexports Control.Monad.Compat from a globally unique -- namespace. module Control.Monad.Compat.Repl module Control.Monad.Fail.Compat -- | Reexports Control.Monad.Fail.Compat from a globally unique -- namespace. module Control.Monad.Fail.Compat.Repl module Control.Monad.IO.Class.Compat -- | Reexports Control.Monad.IO.Class.Compat from a globally unique -- namespace. module Control.Monad.IO.Class.Compat.Repl module Control.Monad.ST.Lazy.Unsafe.Compat unsafeInterleaveST :: () => ST s a -> ST s a unsafeIOToST :: () => IO a -> ST s a -- | Reexports Control.Monad.ST.Lazy.Unsafe.Compat from a globally -- unique namespace. module Control.Monad.ST.Lazy.Unsafe.Compat.Repl module Control.Monad.ST.Unsafe.Compat -- | unsafeInterleaveST allows an ST computation to be -- deferred lazily. When passed a value of type ST a, the -- ST computation will only be performed when the value of the -- a is demanded. unsafeInterleaveST :: () => ST s a -> ST s a -- | Convert an IO action to an ST action. This relies on -- IO and ST having the same representation modulo the -- constraint on the type of the state. unsafeIOToST :: () => IO a -> ST s a -- | Convert an ST action to an IO action. This relies on -- IO and ST having the same representation modulo the -- constraint on the type of the state. -- -- For an example demonstrating why this is unsafe, see -- https://mail.haskell.org/pipermail/haskell-cafe/2009-April/060719.html unsafeSTToIO :: () => ST s a -> IO a -- | Reexports Control.Monad.ST.Unsafe.Compat from a globally unique -- namespace. module Control.Monad.ST.Unsafe.Compat.Repl module Data.Bifoldable.Compat -- | Reexports Data.Bifoldable.Compat from a globally unique -- namespace. module Data.Bifoldable.Compat.Repl module Data.Bifunctor.Compat -- | Reexports Data.Bifunctor.Compat from a globally unique -- namespace. module Data.Bifunctor.Compat.Repl module Data.Bitraversable.Compat -- | Reexports Data.Bitraversable.Compat from a globally unique -- namespace. module Data.Bitraversable.Compat.Repl module Data.Bits.Compat -- | Default implementation for bit. -- -- Note that: bitDefault i = 1 shiftL i bitDefault :: (Bits a, Num a) => Int -> a -- | Default implementation for testBit. -- -- Note that: testBitDefault x i = (x .&. bit i) /= 0 testBitDefault :: (Bits a, Num a) => a -> Int -> Bool -- | Default implementation for popCount. -- -- This implementation is intentionally naive. Instances are expected to -- provide an optimized implementation for their size. popCountDefault :: (Bits a, Num a) => a -> Int -- | Attempt to convert an Integral type a to an -- Integral type b using the size of the types as -- measured by Bits methods. -- -- A simpler version of this function is: -- --
-- toIntegral :: (Integral a, Integral b) => a -> Maybe b -- toIntegral x -- | toInteger x == y = Just (fromInteger y) -- | otherwise = Nothing -- where -- y = toInteger x ---- -- This version requires going through Integer, which can be -- inefficient. However, toIntegralSized is optimized to allow -- GHC to statically determine the relative type sizes (as measured by -- bitSizeMaybe and isSigned) and avoid going through -- Integer for many types. (The implementation uses -- fromIntegral, which is itself optimized with rules for -- base types but may go through Integer for some type -- pairs.) toIntegralSized :: (Integral a, Integral b, Bits a, Bits b) => a -> Maybe b -- | Reexports Data.Bits.Compat from a globally unique namespace. module Data.Bits.Compat.Repl module Data.Bool.Compat -- | Case analysis for the Bool type. bool x y p -- evaluates to x when p is False, and evaluates -- to y when p is True. -- -- This is equivalent to if p then y else x; that is, one can -- think of it as an if-then-else construct with its arguments reordered. -- --
-- >>> bool "foo" "bar" True -- "bar" -- -- >>> bool "foo" "bar" False -- "foo" ---- -- Confirm that bool x y p and if p then y else -- x are equivalent: -- --
-- >>> let p = True; x = "bar"; y = "foo" -- -- >>> bool x y p == if p then y else x -- True -- -- >>> let p = False -- -- >>> bool x y p == if p then y else x -- True --bool :: () => a -> a -> Bool -> a -- | Reexports Data.Bool.Compat from a globally unique namespace. module Data.Bool.Compat.Repl module Data.Complex.Compat -- | Reexports Data.Complex.Compat from a globally unique namespace. module Data.Complex.Compat.Repl module Data.Either.Compat -- | Return True if the given value is a Left-value, -- False otherwise. -- --
-- >>> isLeft (Left "foo") -- True -- -- >>> isLeft (Right 3) -- False ---- -- Assuming a Left value signifies some sort of error, we can use -- isLeft to write a very simple error-reporting function that -- does absolutely nothing in the case of success, and outputs "ERROR" if -- any error occurred. -- -- This example shows how isLeft might be used to avoid pattern -- matching when one does not care about the value contained in the -- constructor: -- --
-- >>> import Control.Monad ( when ) -- -- >>> let report e = when (isLeft e) $ putStrLn "ERROR" -- -- >>> report (Right 1) -- -- >>> report (Left "parse error") -- ERROR --isLeft :: () => Either a b -> Bool -- | Return True if the given value is a Right-value, -- False otherwise. -- --
-- >>> isRight (Left "foo") -- False -- -- >>> isRight (Right 3) -- True ---- -- Assuming a Left value signifies some sort of error, we can use -- isRight to write a very simple reporting function that only -- outputs "SUCCESS" when a computation has succeeded. -- -- This example shows how isRight might be used to avoid pattern -- matching when one does not care about the value contained in the -- constructor: -- --
-- >>> import Control.Monad ( when ) -- -- >>> let report e = when (isRight e) $ putStrLn "SUCCESS" -- -- >>> report (Left "parse error") -- -- >>> report (Right 1) -- SUCCESS --isRight :: () => Either a b -> Bool -- | Return the contents of a Left-value or a default value -- otherwise. -- --
-- >>> fromLeft 1 (Left 3) -- 3 -- -- >>> fromLeft 1 (Right "foo") -- 1 --fromLeft :: () => a -> Either a b -> a -- | Return the contents of a Right-value or a default value -- otherwise. -- --
-- >>> fromRight 1 (Right 3) -- 3 -- -- >>> fromRight 1 (Left "foo") -- 1 --fromRight :: () => b -> Either a b -> b -- | Reexports Data.Either.Compat from a globally unique namespace. module Data.Either.Compat.Repl module Data.Foldable.Compat -- | Reexports Data.Foldable.Compat from a globally unique -- namespace. module Data.Foldable.Compat.Repl module Data.Function.Compat -- | & is a reverse application operator. This provides -- notational convenience. Its precedence is one higher than that of the -- forward application operator $, which allows & to be -- nested in $. -- --
-- >>> 5 & (+1) & show -- "6" --(&) :: () => a -> a -> b -> b infixl 1 & -- | Reexports Data.Function.Compat from a globally unique -- namespace. module Data.Function.Compat.Repl module Data.Functor.Compat -- | The Functor class is used for types that can be mapped over. -- Instances of Functor should satisfy the following laws: -- --
-- fmap id == id -- fmap (f . g) == fmap f . fmap g ---- -- The instances of Functor for lists, Maybe and IO -- satisfy these laws. class Functor (f :: * -> *) fmap :: Functor f => a -> b -> f a -> f b -- | Replace all locations in the input with the same value. The default -- definition is fmap . const, but this may be -- overridden with a more efficient version. (<$) :: Functor f => a -> f b -> f a -- | Flipped version of <$. -- --
-- >>> Nothing $> "foo" -- Nothing -- -- >>> Just 90210 $> "foo" -- Just "foo" ---- -- Replace the contents of an Either Int -- Int with a constant String, resulting in an -- Either Int String: -- --
-- >>> Left 8675309 $> "foo" -- Left 8675309 -- -- >>> Right 8675309 $> "foo" -- Right "foo" ---- -- Replace each element of a list with a constant String: -- --
-- >>> [1,2,3] $> "foo" -- ["foo","foo","foo"] ---- -- Replace the second element of a pair with a constant String: -- --
-- >>> (1,2) $> "foo" -- (1,"foo") --($>) :: Functor f => f a -> b -> f b infixl 4 $> -- | void value discards or ignores the result of -- evaluation, such as the return value of an IO action. -- --
-- >>> void Nothing -- Nothing -- -- >>> void (Just 3) -- Just () ---- -- Replace the contents of an Either Int -- Int with unit, resulting in an Either -- Int '()': -- --
-- >>> void (Left 8675309) -- Left 8675309 -- -- >>> void (Right 8675309) -- Right () ---- -- Replace every element of a list with unit: -- --
-- >>> void [1,2,3] -- [(),(),()] ---- -- Replace the second element of a pair with unit: -- --
-- >>> void (1,2) -- (1,()) ---- -- Discard the result of an IO action: -- --
-- >>> mapM print [1,2] -- 1 -- 2 -- [(),()] -- -- >>> void $ mapM print [1,2] -- 1 -- 2 --void :: Functor f => f a -> f () -- | Flipped version of <$>. -- --
-- (<&>) = flip fmap ---- --
-- >>> Just 2 <&> (+1) -- Just 3 ---- --
-- >>> [1,2,3] <&> (+1) -- [2,3,4] ---- --
-- >>> Right 3 <&> (+1) -- Right 4 --(<&>) :: Functor f => f a -> a -> b -> f b infixl 1 <&> -- | Reexports Data.Functor.Compat from a globally unique namespace. module Data.Functor.Compat.Repl module Data.Functor.Compose.Compat -- | Reexports Data.Functor.Compose.Compat from a globally unique -- namespace. module Data.Functor.Compose.Compat.Repl module Data.Functor.Const.Compat -- | The Const functor. newtype Const a (b :: k) :: forall k. () => * -> k -> * Const :: a -> Const a [getConst] :: Const a -> a -- | Reexports Data.Functor.Const.Compat from a globally unique -- namespace. module Data.Functor.Const.Compat.Repl module Data.Functor.Contravariant.Compat -- | Reexports Data.Functor.Contravariant.Compat from a globally -- unique namespace. module Data.Functor.Contravariant.Compat.Repl module Data.Functor.Identity.Compat -- | Reexports Data.Functor.Identity.Compat from a globally unique -- namespace. module Data.Functor.Identity.Compat.Repl module Data.Functor.Product.Compat -- | Reexports Data.Functor.Product.Compat from a globally unique -- namespace. module Data.Functor.Product.Compat.Repl module Data.Functor.Sum.Compat -- | Reexports Data.Functor.Sum.Compat from a globally unique -- namespace. module Data.Functor.Sum.Compat.Repl module Data.IORef.Compat -- | Strict version of modifyIORef modifyIORef' :: () => IORef a -> a -> a -> IO () -- | Strict version of atomicModifyIORef. This forces both the value -- stored in the IORef as well as the value returned. atomicModifyIORef' :: () => IORef a -> a -> (a, b) -> IO b -- | Variant of writeIORef with the "barrier to reordering" property -- that atomicModifyIORef has. atomicWriteIORef :: () => IORef a -> a -> IO () -- | Reexports Data.IORef.Compat from a globally unique namespace. module Data.IORef.Compat.Repl module Data.List.Compat -- | Reexports Data.List.Compat from a globally unique namespace. module Data.List.Compat.Repl -- | This backports the modern Data.Semigroup interface back to -- base-4.9/GHC 8.0. module Data.List.NonEmpty.Compat -- | Non-empty (and non-strict) list type. data NonEmpty a (:|) :: a -> [a] -> NonEmpty a -- | Map a function over a NonEmpty stream. map :: () => a -> b -> NonEmpty a -> NonEmpty b -- | 'intersperse x xs' alternates elements of the list with copies of -- x. -- --
-- intersperse 0 (1 :| [2,3]) == 1 :| [0,2,0,3] --intersperse :: () => a -> NonEmpty a -> NonEmpty a -- | scanl is similar to foldl, but returns a stream of -- successive reduced values from the left: -- --
-- scanl f z [x1, x2, ...] == z :| [z `f` x1, (z `f` x1) `f` x2, ...] ---- -- Note that -- --
-- last (scanl f z xs) == foldl f z xs. --scanl :: Foldable f => b -> a -> b -> b -> f a -> NonEmpty b -- | scanr is the right-to-left dual of scanl. Note that -- --
-- head (scanr f z xs) == foldr f z xs. --scanr :: Foldable f => a -> b -> b -> b -> f a -> NonEmpty b -- | scanl1 is a variant of scanl that has no starting value -- argument: -- --
-- scanl1 f [x1, x2, ...] == x1 :| [x1 `f` x2, x1 `f` (x2 `f` x3), ...] --scanl1 :: () => a -> a -> a -> NonEmpty a -> NonEmpty a -- | scanr1 is a variant of scanr that has no starting value -- argument. scanr1 :: () => a -> a -> a -> NonEmpty a -> NonEmpty a -- | transpose for NonEmpty, behaves the same as -- transpose The rows/columns need not be the same length, in -- which case > transpose . transpose /= id transpose :: () => NonEmpty NonEmpty a -> NonEmpty NonEmpty a -- | sortBy for NonEmpty, behaves the same as sortBy sortBy :: () => a -> a -> Ordering -> NonEmpty a -> NonEmpty a -- | sortWith for NonEmpty, behaves the same as: -- --
-- sortBy . comparing --sortWith :: Ord o => a -> o -> NonEmpty a -> NonEmpty a -- | Number of elements in NonEmpty list. length :: () => NonEmpty a -> Int -- | Extract the first element of the stream. head :: () => NonEmpty a -> a -- | Extract the possibly-empty tail of the stream. tail :: () => NonEmpty a -> [a] -- | Extract the last element of the stream. last :: () => NonEmpty a -> a -- | Extract everything except the last element of the stream. init :: () => NonEmpty a -> [a] -- | Prepend an element to the stream. (<|) :: () => a -> NonEmpty a -> NonEmpty a infixr 5 <| -- | Synonym for <|. cons :: () => a -> NonEmpty a -> NonEmpty a -- | uncons produces the first element of the stream, and a stream -- of the remaining elements, if any. uncons :: () => NonEmpty a -> (a, Maybe NonEmpty a) -- | The unfoldr function is analogous to Data.List's -- unfoldr operation. unfoldr :: () => a -> (b, Maybe a) -> a -> NonEmpty b -- | Sort a stream. sort :: Ord a => NonEmpty a -> NonEmpty a -- | reverse a finite NonEmpty stream. reverse :: () => NonEmpty a -> NonEmpty a -- | The inits function takes a stream xs and returns all -- the finite prefixes of xs. inits :: Foldable f => f a -> NonEmpty [a] -- | The tails function takes a stream xs and returns all -- the suffixes of xs. tails :: Foldable f => f a -> NonEmpty [a] -- | iterate f x produces the infinite sequence of repeated -- applications of f to x. -- --
-- iterate f x = x :| [f x, f (f x), ..] --iterate :: () => a -> a -> a -> NonEmpty a -- | repeat x returns a constant stream, where all elements -- are equal to x. repeat :: () => a -> NonEmpty a -- | cycle xs returns the infinite repetition of -- xs: -- --
-- cycle (1 :| [2,3]) = 1 :| [2,3,1,2,3,...] --cycle :: () => NonEmpty a -> NonEmpty a -- | unfold produces a new stream by repeatedly applying the -- unfolding function to the seed value to produce an element of type -- b and a new seed value. When the unfolding function returns -- Nothing instead of a new seed value, the stream ends. unfold :: () => a -> (b, Maybe a) -> a -> NonEmpty b -- | insert x xs inserts x into the last position -- in xs where it is still less than or equal to the next -- element. In particular, if the list is sorted beforehand, the result -- will also be sorted. insert :: (Foldable f, Ord a) => a -> f a -> NonEmpty a -- | some1 x sequences x one or more times. some1 :: Alternative f => f a -> f NonEmpty a -- | take n xs returns the first n elements of -- xs. take :: () => Int -> NonEmpty a -> [a] -- | drop n xs drops the first n elements off the -- front of the sequence xs. drop :: () => Int -> NonEmpty a -> [a] -- | splitAt n xs returns a pair consisting of the prefix -- of xs of length n and the remaining stream -- immediately following this prefix. -- --
-- 'splitAt' n xs == ('take' n xs, 'drop' n xs)
-- xs == ys ++ zs where (ys, zs) = 'splitAt' n xs
--
splitAt :: () => Int -> NonEmpty a -> ([a], [a])
-- | takeWhile p xs returns the longest prefix of the
-- stream xs for which the predicate p holds.
takeWhile :: () => a -> Bool -> NonEmpty a -> [a]
-- | dropWhile p xs returns the suffix remaining after
-- takeWhile p xs.
dropWhile :: () => a -> Bool -> NonEmpty a -> [a]
-- | span p xs returns the longest prefix of xs
-- that satisfies p, together with the remainder of the stream.
--
--
-- 'span' p xs == ('takeWhile' p xs, 'dropWhile' p xs)
-- xs == ys ++ zs where (ys, zs) = 'span' p xs
--
span :: () => a -> Bool -> NonEmpty a -> ([a], [a])
-- | The break p function is equivalent to span
-- (not . p).
break :: () => a -> Bool -> NonEmpty a -> ([a], [a])
-- | filter p xs removes any elements from xs that
-- do not satisfy p.
filter :: () => a -> Bool -> NonEmpty a -> [a]
-- | The partition function takes a predicate p and a
-- stream xs, and returns a pair of lists. The first list
-- corresponds to the elements of xs for which p holds;
-- the second corresponds to the elements of xs for which
-- p does not hold.
--
--
-- 'partition' p xs = ('filter' p xs, 'filter' (not . p) xs)
--
partition :: () => a -> Bool -> NonEmpty a -> ([a], [a])
-- | The group function takes a stream and returns a list of streams
-- such that flattening the resulting list is equal to the argument.
-- Moreover, each stream in the resulting list contains only equal
-- elements. For example, in list notation:
--
-- -- 'group' $ 'cycle' "Mississippi" -- = "M" : "i" : "ss" : "i" : "ss" : "i" : "pp" : "i" : "M" : "i" : ... --group :: (Foldable f, Eq a) => f a -> [NonEmpty a] -- | groupBy operates like group, but uses the provided -- equality predicate instead of ==. groupBy :: Foldable f => a -> a -> Bool -> f a -> [NonEmpty a] -- | groupWith operates like group, but uses the provided -- projection when comparing for equality groupWith :: (Foldable f, Eq b) => a -> b -> f a -> [NonEmpty a] -- | groupAllWith operates like groupWith, but sorts the list -- first so that each equivalence class has, at most, one list in the -- output groupAllWith :: Ord b => a -> b -> [a] -> [NonEmpty a] -- | group1 operates like group, but uses the knowledge that -- its input is non-empty to produce guaranteed non-empty output. group1 :: Eq a => NonEmpty a -> NonEmpty NonEmpty a -- | groupBy1 is to group1 as groupBy is to -- group. groupBy1 :: () => a -> a -> Bool -> NonEmpty a -> NonEmpty NonEmpty a -- | groupWith1 is to group1 as groupWith is to -- group groupWith1 :: Eq b => a -> b -> NonEmpty a -> NonEmpty NonEmpty a -- | groupAllWith1 is to groupWith1 as groupAllWith is -- to groupWith groupAllWith1 :: Ord b => a -> b -> NonEmpty a -> NonEmpty NonEmpty a -- | The isPrefix function returns True if the first -- argument is a prefix of the second. isPrefixOf :: Eq a => [a] -> NonEmpty a -> Bool -- | The nub function removes duplicate elements from a list. In -- particular, it keeps only the first occurrence of each element. (The -- name nub means 'essence'.) It is a special case of -- nubBy, which allows the programmer to supply their own -- inequality test. nub :: Eq a => NonEmpty a -> NonEmpty a -- | The nubBy function behaves just like nub, except it uses -- a user-supplied equality predicate instead of the overloaded == -- function. nubBy :: () => a -> a -> Bool -> NonEmpty a -> NonEmpty a -- | xs !! n returns the element of the stream xs at -- index n. Note that the head of the stream has index 0. -- -- Beware: a negative or out-of-bounds index will cause an error. (!!) :: () => NonEmpty a -> Int -> a infixl 9 !! -- | The zip function takes two streams and returns a stream of -- corresponding pairs. zip :: () => NonEmpty a -> NonEmpty b -> NonEmpty (a, b) -- | The zipWith function generalizes zip. Rather than -- tupling the elements, the elements are combined using the function -- passed as the first argument. zipWith :: () => a -> b -> c -> NonEmpty a -> NonEmpty b -> NonEmpty c -- | The unzip function is the inverse of the zip function. unzip :: Functor f => f (a, b) -> (f a, f b) -- | Converts a normal list to a NonEmpty stream. -- -- Raises an error if given an empty list. fromList :: () => [a] -> NonEmpty a -- | Convert a stream to a normal list efficiently. toList :: () => NonEmpty a -> [a] -- | nonEmpty efficiently turns a normal list into a NonEmpty -- stream, producing Nothing if the input is empty. nonEmpty :: () => [a] -> Maybe NonEmpty a -- | Compute n-ary logic exclusive OR operation on NonEmpty list. xor :: NonEmpty Bool -> Bool -- | Reexports Data.List.NonEmpty.Compat from a globally unique -- namespace. module Data.List.NonEmpty.Compat.Repl module Data.Monoid.Compat -- | The class of monoids (types with an associative binary operation that -- has an identity). Instances should satisfy the following laws: -- --
x <> mempty = x
mempty <> x = x
mconcat = foldr '(<>)' -- mempty
-- >>> getFirst (First (Just "hello") <> First Nothing <> First (Just "world")) -- Just "hello" --newtype First a First :: Maybe a -> First a [getFirst] :: First a -> Maybe a -- | Maybe monoid returning the rightmost non-Nothing value. -- -- Last a is isomorphic to Dual (First -- a), and thus to Dual (Alt Maybe a) -- --
-- >>> getLast (Last (Just "hello") <> Last Nothing <> Last (Just "world")) -- Just "world" --newtype Last a Last :: Maybe a -> Last a [getLast] :: Last a -> Maybe a -- | The dual of a Monoid, obtained by swapping the arguments of -- mappend. -- --
-- >>> getDual (mappend (Dual "Hello") (Dual "World")) -- "WorldHello" --newtype Dual a Dual :: a -> Dual a [getDual] :: Dual a -> a -- | The monoid of endomorphisms under composition. -- --
-- >>> let computation = Endo ("Hello, " ++) <> Endo (++ "!")
--
-- >>> appEndo computation "Haskell"
-- "Hello, Haskell!"
--
newtype Endo a
Endo :: a -> a -> Endo a
[appEndo] :: Endo a -> a -> a
-- | Boolean monoid under conjunction (&&).
--
-- -- >>> getAll (All True <> mempty <> All False) -- False ---- --
-- >>> getAll (mconcat (map (\x -> All (even x)) [2,4,6,7,8])) -- False --newtype All All :: Bool -> All [getAll] :: All -> Bool -- | Boolean monoid under disjunction (||). -- --
-- >>> getAny (Any True <> mempty <> Any False) -- True ---- --
-- >>> getAny (mconcat (map (\x -> Any (even x)) [2,4,6,7,8])) -- True --newtype Any Any :: Bool -> Any [getAny] :: Any -> Bool -- | Monoid under addition. -- --
-- >>> getSum (Sum 1 <> Sum 2 <> mempty) -- 3 --newtype Sum a Sum :: a -> Sum a [getSum] :: Sum a -> a -- | Monoid under multiplication. -- --
-- >>> getProduct (Product 3 <> Product 4 <> mempty) -- 12 --newtype Product a Product :: a -> Product a [getProduct] :: Product a -> a -- | Monoid under <|>. newtype Alt (f :: k -> *) (a :: k) :: forall k. () => k -> * -> k -> * Alt :: f a -> Alt [getAlt] :: Alt -> f a -- | An associative operation. (<>) :: Semigroup a => a -> a -> a infixr 6 <> -- | Reexports Data.Monoid.Compat from a globally unique namespace. module Data.Monoid.Compat.Repl module Data.Proxy.Compat -- | asProxyTypeOf is a type-restricted version of const. 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 -- tag of the second. -- --
-- >>> import Data.Word -- -- >>> :type asProxyTypeOf 123 (Proxy :: Proxy Word8) -- asProxyTypeOf 123 (Proxy :: Proxy Word8) :: Word8 ---- -- Note the lower-case proxy in the definition. This allows any -- type constructor with just one argument to be passed to the function, -- for example we could also write -- --
-- >>> import Data.Word -- -- >>> :type asProxyTypeOf 123 (Just (undefined :: Word8)) -- asProxyTypeOf 123 (Just (undefined :: Word8)) :: Word8 --asProxyTypeOf :: () => a -> proxy a -> a -- | Reexports Data.Proxy.Compat from a globally unique namespace. module Data.Proxy.Compat.Repl module Data.Ratio.Compat -- | Reexports Data.Ratio.Compat from a globally unique namespace. module Data.Ratio.Compat.Repl module Data.STRef.Compat -- | Strict version of modifySTRef modifySTRef' :: () => STRef s a -> a -> a -> ST s () -- | Reexports Data.STRef.Compat from a globally unique namespace. module Data.STRef.Compat.Repl -- | This backports the modern Data.Semigroup interface back to -- base-4.9/GHC 8.0. module Data.Semigroup.Compat -- | The class of semigroups (types with an associative binary operation). -- -- Instances should satisfy the associativity law: -- -- class Semigroup a -- | An associative operation. (<>) :: Semigroup a => a -> a -> a -- | Reduce a non-empty list with <> -- -- The default definition should be sufficient, but this can be -- overridden for efficiency. sconcat :: Semigroup a => NonEmpty a -> a -- | Repeat a value n times. -- -- Given that this works on a Semigroup it is allowed to fail if -- you request 0 or fewer repetitions, and the default definition will do -- so. -- -- By making this a member of the class, idempotent semigroups and -- monoids can upgrade this to execute in O(1) by picking -- stimes = stimesIdempotent or stimes = -- stimesIdempotentMonoid respectively. stimes :: (Semigroup a, Integral b) => b -> a -> a -- | This is a valid definition of stimes for a Monoid. -- -- Unlike the default definition of stimes, it is defined for 0 -- and so it should be preferred where possible. stimesMonoid :: (Integral b, Monoid a) => b -> a -> a -- | This is a valid definition of stimes for an idempotent -- Semigroup. -- -- When x <> x = x, this definition should be preferred, -- because it works in O(1) rather than O(log n). stimesIdempotent :: Integral b => b -> a -> a -- | This is a valid definition of stimes for an idempotent -- Monoid. -- -- When mappend x x = x, this definition should be preferred, -- because it works in O(1) rather than O(log n) stimesIdempotentMonoid :: (Integral b, Monoid a) => b -> a -> a -- | Repeat a value n times. -- --
-- mtimesDefault n a = a <> a <> ... <> a -- using <> (n-1) times ---- -- Implemented using stimes and mempty. -- -- This is a suitable definition for an mtimes member of -- Monoid. mtimesDefault :: (Integral b, Monoid a) => b -> a -> a newtype Min a Min :: a -> Min a [getMin] :: Min a -> a newtype Max a Max :: a -> Max a [getMax] :: Max a -> a -- | Use Option (First a) to get the behavior of -- First from Data.Monoid. newtype First a First :: a -> First a [getFirst] :: First a -> a -- | Use Option (Last a) to get the behavior of -- Last from Data.Monoid newtype Last a Last :: a -> Last a [getLast] :: Last a -> a -- | Provide a Semigroup for an arbitrary Monoid. -- -- NOTE: This is not needed anymore since Semigroup became -- a superclass of Monoid in base-4.11 and this newtype be -- deprecated at some point in the future. newtype WrappedMonoid m WrapMonoid :: m -> WrappedMonoid m [unwrapMonoid] :: WrappedMonoid m -> m -- | The dual of a Monoid, obtained by swapping the arguments of -- mappend. -- --
-- >>> getDual (mappend (Dual "Hello") (Dual "World")) -- "WorldHello" --newtype Dual a Dual :: a -> Dual a [getDual] :: Dual a -> a -- | The monoid of endomorphisms under composition. -- --
-- >>> let computation = Endo ("Hello, " ++) <> Endo (++ "!")
--
-- >>> appEndo computation "Haskell"
-- "Hello, Haskell!"
--
newtype Endo a
Endo :: a -> a -> Endo a
[appEndo] :: Endo a -> a -> a
-- | Boolean monoid under conjunction (&&).
--
-- -- >>> getAll (All True <> mempty <> All False) -- False ---- --
-- >>> getAll (mconcat (map (\x -> All (even x)) [2,4,6,7,8])) -- False --newtype All All :: Bool -> All [getAll] :: All -> Bool -- | Boolean monoid under disjunction (||). -- --
-- >>> getAny (Any True <> mempty <> Any False) -- True ---- --
-- >>> getAny (mconcat (map (\x -> Any (even x)) [2,4,6,7,8])) -- True --newtype Any Any :: Bool -> Any [getAny] :: Any -> Bool -- | Monoid under addition. -- --
-- >>> getSum (Sum 1 <> Sum 2 <> mempty) -- 3 --newtype Sum a Sum :: a -> Sum a [getSum] :: Sum a -> a -- | Monoid under multiplication. -- --
-- >>> getProduct (Product 3 <> Product 4 <> mempty) -- 12 --newtype Product a Product :: a -> Product a [getProduct] :: Product a -> a -- | Option is effectively Maybe with a better instance of -- Monoid, built off of an underlying Semigroup instead of -- an underlying Monoid. -- -- Ideally, this type would not exist at all and we would just fix the -- Monoid instance of Maybe newtype Option a Option :: Maybe a -> Option a [getOption] :: Option a -> Maybe a -- | Fold an Option case-wise, just like maybe. option :: () => b -> a -> b -> Option a -> b -- | This lets you use a difference list of a Semigroup as a -- Monoid. diff :: Semigroup m => m -> Endo m -- | A generalization of cycle to an arbitrary Semigroup. May -- fail to terminate for some values in some semigroups. cycle1 :: Semigroup m => m -> m -- | Arg isn't itself a Semigroup in its own right, but it -- can be placed inside Min and Max to compute an arg min -- or arg max. data Arg a b Arg :: a -> b -> Arg a b type ArgMin a b = Min Arg a b type ArgMax a b = Max Arg a b -- | Reexports Data.Semigroup.Compat from a globally unique -- namespace. module Data.Semigroup.Compat.Repl module Data.String.Compat -- | A String is a list of characters. String constants in Haskell -- are values of type String. type String = [Char] -- | lines breaks a string up into a list of strings at newline -- characters. The resulting strings do not contain newlines. -- -- Note that after splitting the string at newline characters, the last -- part of the string is considered a line even if it doesn't end with a -- newline. For example, -- --
-- >>> lines "" -- [] ---- --
-- >>> lines "\n" -- [""] ---- --
-- >>> lines "one" -- ["one"] ---- --
-- >>> lines "one\n" -- ["one"] ---- --
-- >>> lines "one\n\n" -- ["one",""] ---- --
-- >>> lines "one\ntwo" -- ["one","two"] ---- --
-- >>> lines "one\ntwo\n" -- ["one","two"] ---- -- Thus lines s contains at least as many elements as -- newlines in s. lines :: String -> [String] -- | words breaks a string up into a list of words, which were -- delimited by white space. -- --
-- >>> words "Lorem ipsum\ndolor" -- ["Lorem","ipsum","dolor"] --words :: String -> [String] -- | unlines is an inverse operation to lines. It joins -- lines, after appending a terminating newline to each. -- --
-- >>> unlines ["Hello", "World", "!"] -- "Hello\nWorld\n!\n" --unlines :: [String] -> String -- | unwords is an inverse operation to words. It joins words -- with separating spaces. -- --
-- >>> unwords ["Lorem", "ipsum", "dolor"] -- "Lorem ipsum dolor" --unwords :: [String] -> String -- | Reexports Data.String.Compat from a globally unique namespace. module Data.String.Compat.Repl module Data.Type.Coercion.Compat -- | Generalized form of type-safe cast using representational equality gcoerceWith :: () => Coercion a b -> Coercible a b -> r -> r -- | Reexports Data.Type.Coercion.Compat from a globally unique -- namespace. module Data.Type.Coercion.Compat.Repl module Data.Version.Compat -- | Construct tag-less Version makeVersion :: [Int] -> Version -- | Reexports Data.Version.Compat from a globally unique namespace. module Data.Version.Compat.Repl module Data.Void.Compat -- | Reexports Data.Void.Compat from a globally unique namespace. module Data.Void.Compat.Repl module Data.Word.Compat -- | Swap bytes in Word16. byteSwap16 :: Word16 -> Word16 -- | Reverse order of bytes in Word32. byteSwap32 :: Word32 -> Word32 -- | Reverse order of bytes in Word64. byteSwap64 :: Word64 -> Word64 -- | Reexports Data.Word.Compat from a globally unique namespace. module Data.Word.Compat.Repl module Debug.Trace.Compat -- | Like trace but returns the message instead of a third value. -- --
-- >>> traceId "hello" -- "hello -- hello" --traceId :: String -> String -- | Like traceShow but returns the shown value instead of a third -- value. -- --
-- >>> traceShowId (1+2+3, "hello" ++ "world") -- (6,"helloworld") -- (6,"helloworld") --traceShowId :: Show a => a -> a -- | Like trace but returning unit in an arbitrary -- Applicative context. Allows for convenient use in do-notation. -- -- Note that the application of traceM is not an action in the -- Applicative context, as traceIO is in the IO -- type. While the fresh bindings in the following example will force the -- traceM expressions to be reduced every time the -- do-block is executed, traceM "not crashed" would -- only be reduced once, and the message would only be printed once. If -- your monad is in MonadIO, liftIO . traceIO may be a -- better option. -- --
-- >>> :{
-- do
-- x <- Just 3
-- traceM ("x: " ++ show x)
-- y <- pure 12
-- traceM ("y: " ++ show y)
-- pure (x*2 + y)
-- :}
-- x: 3
-- y: 12
-- Just 18
--
traceM :: Applicative f => String -> f ()
-- | Like traceM, but uses show on the argument to convert it
-- to a String.
--
--
-- >>> :{
-- do
-- x <- Just 3
-- traceShowM x
-- y <- pure 12
-- traceShowM y
-- pure (x*2 + y)
-- :}
-- 3
-- 12
-- Just 18
--
traceShowM :: (Show a, Applicative f) => a -> f ()
-- | Reexports Debug.Trace.Compat from a globally unique namespace.
module Debug.Trace.Compat.Repl
module Foreign.ForeignPtr.Compat
-- | Advances the given address by the given offset in bytes.
--
-- The new ForeignPtr shares the finalizer of the original,
-- equivalent from a finalization standpoint to just creating another
-- reference to the original. That is, the finalizer will not be called
-- before the new ForeignPtr is unreachable, nor will it be called
-- an additional time due to this call, and the finalizer will be called
-- with the same address that it would have had this call not happened,
-- *not* the new address.
plusForeignPtr :: () => ForeignPtr a -> Int -> ForeignPtr b
-- | Reexports Foreign.ForeignPtr.Compat from a globally unique
-- namespace.
module Foreign.ForeignPtr.Compat.Repl
module Foreign.ForeignPtr.Safe.Compat
-- | The type ForeignPtr 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 ForeignPtrs and vanilla memory
-- references of type Ptr a is that the former may be associated
-- with finalizers. 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
-- ForeignPtr. Typically, the finalizer will, then, invoke
-- routines in the foreign language that free the resources bound by the
-- foreign object.
--
-- The ForeignPtr is parameterised in the same way as Ptr.
-- The type argument of ForeignPtr should normally be an instance
-- of class Storable.
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.
--
-- Note that the foreign function must use the ccall
-- calling convention.
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 addForeignPtrFinalizer.
newForeignPtr_ :: () => Ptr a -> IO ForeignPtr a
-- | This function adds a finalizer to the given foreign object. The
-- finalizer will run before all other finalizers for the same
-- object which have already been registered.
addForeignPtrFinalizer :: () => FinalizerPtr a -> ForeignPtr a -> IO ()
-- | This variant of newForeignPtr 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
-- newForeignPtrEnv.
newForeignPtrEnv :: () => FinalizerEnvPtr env a -> Ptr env -> Ptr a -> IO ForeignPtr a
-- | Like addForeignPtrFinalizerEnv 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 addForeignPtrFinalizerEnv
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 IO 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 withForeignPtr bracket. The reason
-- for this unsafeness is the same as for unsafeForeignPtrToPtr
-- below: the finalizer may run earlier than expected, because the
-- compiler can only track usage of the ForeignPtr object, not a
-- Ptr object made from it.
--
-- This function is normally used for marshalling data to or from the
-- object pointed to by the ForeignPtr, using the operations from
-- the Storable 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
-- withForeignPtr does a touchForeignPtr after it executes
-- the user action.
--
-- Note that this function should not be used to express dependencies
-- between finalizers on ForeignPtrs. For example, if the
-- finalizer for a ForeignPtr F1 calls
-- touchForeignPtr on a second ForeignPtr F2, then
-- the only guarantee is that the finalizer for F2 is never
-- started before the finalizer for F1. They might be started
-- together if for example both F1 and F2 are otherwise
-- unreachable, and in that case the scheduler might end up running the
-- finalizer for F2 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
-- MVars 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 ForeignPtr parameterised by one type into
-- another type.
castForeignPtr :: () => ForeignPtr a -> ForeignPtr b
-- | Allocate some memory and return a ForeignPtr to it. The memory
-- will be released automatically when the ForeignPtr is
-- discarded.
--
-- mallocForeignPtr is equivalent to
--
--
-- do { p <- malloc; newForeignPtr finalizerFree p }
--
--
-- although it may be implemented differently internally: you may not
-- assume that the memory returned by mallocForeignPtr has been
-- allocated with malloc.
--
-- GHC notes: mallocForeignPtr has a heavily optimised
-- implementation in GHC. It uses pinned memory in the garbage collected
-- heap, so the ForeignPtr does not require a finalizer to free
-- the memory. Use of mallocForeignPtr and associated functions is
-- strongly recommended in preference to newForeignPtr with a
-- finalizer.
mallocForeignPtr :: Storable a => IO ForeignPtr a
-- | This function is similar to mallocForeignPtr, 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 mallocArray, but yields a memory
-- area that has a finalizer attached that releases the memory area. As
-- with mallocForeignPtr, it is not guaranteed that the block of
-- memory was allocated by malloc.
mallocForeignPtrArray :: Storable a => Int -> IO ForeignPtr a
-- | This function is similar to mallocArray0, but yields a memory
-- area that has a finalizer attached that releases the memory area. As
-- with mallocForeignPtr, it is not guaranteed that the block of
-- memory was allocated by malloc.
mallocForeignPtrArray0 :: Storable a => Int -> IO ForeignPtr a
-- | Reexports Foreign.ForeignPtr.Safe.Compat from a globally unique
-- namespace.
module Foreign.ForeignPtr.Safe.Compat.Repl
module Foreign.ForeignPtr.Unsafe.Compat
-- | This function extracts the pointer component of a foreign pointer.
-- This is a potentially dangerous operations, as if the argument to
-- unsafeForeignPtrToPtr 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,
-- touchForeignPtr 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 withForeignPtr rather than combinations of
-- unsafeForeignPtrToPtr and touchForeignPtr. However, the
-- latter routines are occasionally preferred in tool generated
-- marshalling code.
unsafeForeignPtrToPtr :: () => ForeignPtr a -> Ptr a
-- | Reexports Foreign.ForeignPtr.Unsafe.Compat from a globally
-- unique namespace.
module Foreign.ForeignPtr.Unsafe.Compat.Repl
module Foreign.Marshal.Alloc.Compat
-- | Like malloc but memory is filled with bytes of value zero.
calloc :: Storable a => IO Ptr a
-- | Llike mallocBytes but memory is filled with bytes of value
-- zero.
callocBytes :: () => Int -> IO Ptr a
-- | Reexports Foreign.Marshal.Alloc.Compat from a globally unique
-- namespace.
module Foreign.Marshal.Alloc.Compat.Repl
module Foreign.Marshal.Array.Compat
-- | Like mallocArray, but allocated memory is filled with bytes of
-- value zero.
callocArray :: Storable a => Int -> IO Ptr a
-- | Like callocArray0, but allocated memory is filled with bytes of
-- value zero.
callocArray0 :: Storable a => Int -> IO Ptr a
-- | Reexports Foreign.Marshal.Array.Compat from a globally unique
-- namespace.
module Foreign.Marshal.Array.Compat.Repl
module Foreign.Marshal.Safe.Compat
-- | Reexports Foreign.Marshal.Safe.Compat from a globally unique
-- namespace.
module Foreign.Marshal.Safe.Compat.Repl
module Foreign.Marshal.Unsafe.Compat
-- | Sometimes an external entity is a pure function, except that it passes
-- arguments and/or results via pointers. The function
-- unsafeLocalState permits the packaging of such entities as
-- pure functions.
--
-- The only IO operations allowed in the IO action passed to
-- unsafeLocalState are (a) local allocation (alloca,
-- allocaBytes and derived operations such as withArray
-- and withCString), and (b) pointer operations
-- (Foreign.Storable and Foreign.Ptr) 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
-- | Reexports Foreign.Marshal.Unsafe.Compat from a globally unique
-- namespace.
module Foreign.Marshal.Unsafe.Compat.Repl
module Foreign.Marshal.Utils.Compat
-- | Fill a given number of bytes in memory area with a byte value.
fillBytes :: () => Ptr a -> Word8 -> Int -> IO ()
module Foreign.Marshal.Compat
-- | Reexports Foreign.Marshal.Compat from a globally unique
-- namespace.
module Foreign.Marshal.Compat.Repl
module Foreign.Compat
-- | Reexports Foreign.Compat from a globally unique namespace.
module Foreign.Compat.Repl
-- | Reexports Foreign.Marshal.Utils.Compat from a globally unique
-- namespace.
module Foreign.Marshal.Utils.Compat.Repl
module Numeric.Compat
-- | Show a signed RealFloat value using standard decimal notation
-- (e.g. 245000, 0.0015).
--
-- This behaves as showFFloat, except that a decimal point is
-- always guaranteed, even if not needed.
showFFloatAlt :: RealFloat a => Maybe Int -> a -> ShowS
-- | Show a signed RealFloat value using standard decimal notation
-- for arguments whose absolute value lies between 0.1 and
-- 9,999,999, and scientific notation otherwise.
--
-- This behaves as showFFloat, except that a decimal point is
-- always guaranteed, even if not needed.
showGFloatAlt :: RealFloat a => Maybe Int -> a -> ShowS
-- | Show a floating-point value in the hexadecimal format, similar to the
-- %a specifier in C's printf.
--
-- -- >>> showHFloat (212.21 :: Double) "" -- "0x1.a86b851eb851fp7" -- -- >>> showHFloat (-12.76 :: Float) "" -- "-0x1.9851ecp3" -- -- >>> showHFloat (-0 :: Double) "" -- "-0x0p+0" --showHFloat :: RealFloat a => a -> ShowS -- | Reexports Numeric.Compat from a globally unique namespace. module Numeric.Compat.Repl module Numeric.Natural.Compat -- | Reexports Numeric.Natural.Compat from a globally unique -- namespace. module Numeric.Natural.Compat.Repl module Prelude.Compat -- | Case analysis for the Either type. If the value is -- Left a, apply the first function to a; if it -- is Right b, apply the second function to b. -- --
-- >>> let s = Left "foo" :: Either String Int -- -- >>> let n = Right 3 :: Either String Int -- -- >>> either length (*2) s -- 3 -- -- >>> either length (*2) n -- 6 --either :: () => a -> c -> b -> c -> Either a b -> c -- | Determines whether all elements of the structure satisfy the -- predicate. all :: Foldable t => a -> Bool -> t a -> Bool -- | and returns the conjunction of a container of Bools. For the -- result to be True, the container must be finite; False, -- however, results from a False value finitely far from the left -- end. and :: Foldable t => t Bool -> Bool -- | Determines whether any element of the structure satisfies the -- predicate. any :: Foldable t => a -> Bool -> t a -> Bool -- | 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] -- | Map each element of a structure to a monadic action, evaluate these -- actions from left to right, and ignore the results. For a version that -- doesn't ignore the results see mapM. -- -- As of base 4.8.0.0, mapM_ is just traverse_, specialized -- to Monad. mapM_ :: (Foldable t, Monad m) => a -> m b -> t a -> m () -- | notElem is the negation of elem. notElem :: (Foldable t, Eq a) => a -> t a -> Bool infix 4 `notElem` -- | or returns the disjunction of a container of Bools. For the -- result to be False, the container must be finite; True, -- however, results from a True value finitely far from the left -- end. or :: Foldable t => t Bool -> Bool -- | Evaluate each monadic action in the structure from left to right, and -- ignore the results. For a version that doesn't ignore the results see -- sequence. -- -- As of base 4.8.0.0, sequence_ is just sequenceA_, -- specialized to Monad. sequence_ :: (Foldable t, Monad m) => t m a -> m () -- | An infix synonym for fmap. -- -- The name of this operator is an allusion to $. Note the -- similarities between their types: -- --
-- ($) :: (a -> b) -> a -> b -- (<$>) :: Functor f => (a -> b) -> f a -> f b ---- -- Whereas $ is function application, <$> is -- function application lifted over a Functor. -- --
-- >>> show <$> Nothing -- Nothing -- -- >>> show <$> Just 3 -- Just "3" ---- -- Convert from an Either Int Int to -- an Either Int String using -- show: -- --
-- >>> show <$> Left 17 -- Left 17 -- -- >>> show <$> Right 17 -- Right "17" ---- -- Double each element of a list: -- --
-- >>> (*2) <$> [1,2,3] -- [2,4,6] ---- -- Apply even to the second element of a pair: -- --
-- >>> even <$> (2,2) -- (2,True) --(<$>) :: Functor f => a -> b -> f a -> f b infixl 4 <$> -- | The maybe function takes a default value, a function, and a -- Maybe value. If the Maybe value is Nothing, the -- function returns the default value. Otherwise, it applies the function -- to the value inside the Just and returns the result. -- --
-- >>> maybe False odd (Just 3) -- True ---- --
-- >>> maybe False odd Nothing -- False ---- -- Read an integer from a string using readMaybe. If we succeed, -- return twice the integer; that is, apply (*2) to it. If -- instead we fail to parse an integer, return 0 by default: -- --
-- >>> import Text.Read ( readMaybe ) -- -- >>> maybe 0 (*2) (readMaybe "5") -- 10 -- -- >>> maybe 0 (*2) (readMaybe "") -- 0 ---- -- Apply show to a Maybe Int. If we have Just -- n, we want to show the underlying Int n. But if -- we have Nothing, we return the empty string instead of (for -- example) "Nothing": -- --
-- >>> maybe "" show (Just 5) -- "5" -- -- >>> maybe "" show Nothing -- "" --maybe :: () => b -> a -> b -> Maybe a -> b -- | lines breaks a string up into a list of strings at newline -- characters. The resulting strings do not contain newlines. -- -- Note that after splitting the string at newline characters, the last -- part of the string is considered a line even if it doesn't end with a -- newline. For example, -- --
-- >>> lines "" -- [] ---- --
-- >>> lines "\n" -- [""] ---- --
-- >>> lines "one" -- ["one"] ---- --
-- >>> lines "one\n" -- ["one"] ---- --
-- >>> lines "one\n\n" -- ["one",""] ---- --
-- >>> lines "one\ntwo" -- ["one","two"] ---- --
-- >>> lines "one\ntwo\n" -- ["one","two"] ---- -- Thus lines s contains at least as many elements as -- newlines in s. lines :: String -> [String] -- | unlines is an inverse operation to lines. It joins -- lines, after appending a terminating newline to each. -- --
-- >>> unlines ["Hello", "World", "!"] -- "Hello\nWorld\n!\n" --unlines :: [String] -> String -- | unwords is an inverse operation to words. It joins words -- with separating spaces. -- --
-- >>> unwords ["Lorem", "ipsum", "dolor"] -- "Lorem ipsum dolor" --unwords :: [String] -> String -- | words breaks a string up into a list of words, which were -- delimited by white space. -- --
-- >>> words "Lorem ipsum\ndolor" -- ["Lorem","ipsum","dolor"] --words :: String -> [String] -- | curry converts an uncurried function to a curried function. -- --
-- >>> curry fst 1 2 -- 1 --curry :: () => (a, b) -> c -> a -> b -> c -- | Extract the first component of a pair. fst :: () => (a, b) -> a -- | Extract the second component of a pair. snd :: () => (a, b) -> b -- | uncurry converts a curried function to a function on pairs. -- --
-- >>> uncurry (+) (1,2) -- 3 ---- --
-- >>> uncurry ($) (show, 1) -- "1" ---- --
-- >>> map (uncurry max) [(1,2), (3,4), (6,8)] -- [2,4,8] --uncurry :: () => a -> b -> c -> (a, b) -> c -- | Strict (call-by-value) application operator. It takes a function and -- an argument, evaluates the argument to weak head normal form (WHNF), -- then calls the function with that value. ($!) :: forall r a (b :: TYPE r). (a -> b) -> a -> b infixr 0 $! -- | Append two lists, i.e., -- --
-- [x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn] -- [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...] ---- -- If the first list is not finite, the result is the first list. (++) :: () => [a] -> [a] -> [a] infixr 5 ++ -- | Function composition. (.) :: () => b -> c -> a -> b -> a -> c infixr 9 . -- | Same as >>=, but with the arguments interchanged. (=<<) :: Monad m => a -> m b -> m a -> m b infixr 1 =<< -- | asTypeOf is a type-restricted version of const. 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 -- | const x is a unary function which evaluates to x for -- all inputs. -- --
-- >>> const 42 "hello" -- 42 ---- --
-- >>> map (const 42) [0..3] -- [42,42,42,42] --const :: () => a -> b -> a -- | flip f takes its (first) two arguments in the reverse -- order of f. -- --
-- >>> flip (++) "hello" "world" -- "worldhello" --flip :: () => a -> b -> c -> b -> a -> c -- | Identity function. -- --
-- id x = x --id :: () => a -> a -- | map f xs is the list obtained by applying f -- to each element of xs, i.e., -- --
-- map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn] -- map f [x1, x2, ...] == [f x1, f x2, ...] --map :: () => a -> b -> [a] -> [b] -- | otherwise is defined as the value True. It helps to make -- guards more readable. eg. -- --
-- f x | x < 0 = ... -- | otherwise = ... --otherwise :: Bool -- | until p f yields the result of applying f -- until p holds. until :: () => a -> Bool -> a -> a -> a -> a -- | Raise an IOError in the IO monad. ioError :: () => IOError -> IO a -- | Construct an IOError value with a string describing the error. -- The fail method of the IO instance of the Monad -- class raises a userError, thus: -- --
-- instance Monad IO where -- ... -- fail s = ioError (userError s) --userError :: String -> IOError -- | List index (subscript) operator, starting from 0. It is an instance of -- the more general genericIndex, which takes an index of any -- integral type. (!!) :: () => [a] -> Int -> a infixl 9 !! -- | break, applied to a predicate p and a list -- xs, returns a tuple where first element is longest prefix -- (possibly empty) of xs of elements that do not satisfy -- p and second element is the remainder of the list: -- --
-- break (> 3) [1,2,3,4,1,2,3,4] == ([1,2,3],[4,1,2,3,4]) -- break (< 9) [1,2,3] == ([],[1,2,3]) -- break (> 9) [1,2,3] == ([1,2,3],[]) ---- -- break p is equivalent to span (not . -- p). break :: () => a -> Bool -> [a] -> ([a], [a]) -- | cycle 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] -- | drop n xs returns the suffix of xs after the -- first n elements, or [] if n > length -- xs: -- --
-- 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] ---- -- It is an instance of the more general genericDrop, in which -- n may be of any integral type. drop :: () => Int -> [a] -> [a] -- | dropWhile p xs returns the suffix remaining after -- takeWhile p xs: -- --
-- dropWhile (< 3) [1,2,3,4,5,1,2,3] == [3,4,5,1,2,3] -- dropWhile (< 9) [1,2,3] == [] -- dropWhile (< 0) [1,2,3] == [1,2,3] --dropWhile :: () => a -> Bool -> [a] -> [a] -- | filter, applied to a predicate and a list, returns the list of -- those elements that satisfy the predicate; i.e., -- --
-- filter p xs = [ x | x <- xs, p x] --filter :: () => a -> Bool -> [a] -> [a] -- | Extract the first element of a list, which must be non-empty. head :: () => [a] -> a -- | Return all the elements of a list except the last one. The list must -- be non-empty. init :: () => [a] -> [a] -- | iterate f x returns an infinite list of repeated -- applications of f to x: -- --
-- iterate f x == [x, f x, f (f x), ...] ---- -- Note that iterate is lazy, potentially leading to thunk -- build-up if the consumer doesn't force each iterate. See 'iterate\'' -- for a strict variant of this function. iterate :: () => a -> a -> a -> [a] -- | Extract the last element of a list, which must be finite and -- non-empty. last :: () => [a] -> a -- | lookup key assocs looks up a key in an association -- list. lookup :: Eq a => a -> [(a, b)] -> Maybe b -- | repeat x is an infinite list, with x the -- value of every element. repeat :: () => a -> [a] -- | replicate n x is a list of length n with -- x the value of every element. It is an instance of the more -- general genericReplicate, in which n may be of any -- integral type. replicate :: () => Int -> a -> [a] -- | reverse xs returns the elements of xs in -- reverse order. xs must be finite. reverse :: () => [a] -> [a] -- | scanl is similar to foldl, but returns a list of -- successive reduced values from the left: -- --
-- scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...] ---- -- Note that -- --
-- last (scanl f z xs) == foldl f z xs. --scanl :: () => b -> a -> b -> b -> [a] -> [b] -- | scanl1 is a variant of scanl that has no starting value -- argument: -- --
-- scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...] --scanl1 :: () => a -> a -> a -> [a] -> [a] -- | scanr is the right-to-left dual of scanl. Note that -- --
-- head (scanr f z xs) == foldr f z xs. --scanr :: () => a -> b -> b -> b -> [a] -> [b] -- | scanr1 is a variant of scanr that has no starting value -- argument. scanr1 :: () => a -> a -> a -> [a] -> [a] -- | span, applied to a predicate p and a list xs, -- returns a tuple where first element is longest prefix (possibly empty) -- of xs of elements that satisfy p and second element -- is the remainder of the list: -- --
-- span (< 3) [1,2,3,4,1,2,3,4] == ([1,2],[3,4,1,2,3,4]) -- span (< 9) [1,2,3] == ([1,2,3],[]) -- span (< 0) [1,2,3] == ([],[1,2,3]) ---- -- span p xs is equivalent to (takeWhile p xs, -- dropWhile p xs) span :: () => a -> Bool -> [a] -> ([a], [a]) -- | splitAt n xs returns a tuple where first element is -- xs prefix of length n and second element is the -- remainder of the list: -- --
-- 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])
--
--
-- It is equivalent to (take n xs, drop n xs) when
-- n is not _|_ (splitAt _|_ xs = _|_).
-- splitAt is an instance of the more general
-- genericSplitAt, in which n may be of any integral
-- type.
splitAt :: () => Int -> [a] -> ([a], [a])
-- | Extract the elements after the head of a list, which must be
-- non-empty.
tail :: () => [a] -> [a]
-- | take n, applied to a list xs, returns the
-- prefix of xs of length n, or xs itself if
-- n > length xs:
--
-- -- 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] == [] ---- -- It is an instance of the more general genericTake, in which -- n may be of any integral type. take :: () => Int -> [a] -> [a] -- | takeWhile, applied to a predicate p and a list -- xs, returns the longest prefix (possibly empty) of -- xs of elements that satisfy p: -- --
-- takeWhile (< 3) [1,2,3,4,1,2,3,4] == [1,2] -- takeWhile (< 9) [1,2,3] == [1,2,3] -- takeWhile (< 0) [1,2,3] == [] --takeWhile :: () => a -> Bool -> [a] -> [a] -- | unzip transforms a list of pairs into a list of first -- components and a list of second components. unzip :: () => [(a, b)] -> ([a], [b]) -- | The unzip3 function takes a list of triples and returns three -- lists, analogous to unzip. unzip3 :: () => [(a, b, c)] -> ([a], [b], [c]) -- | zip 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 is right-lazy: -- --
-- zip [] _|_ = [] --zip :: () => [a] -> [b] -> [(a, b)] -- | zip3 takes three lists and returns a list of triples, analogous -- to zip. zip3 :: () => [a] -> [b] -> [c] -> [(a, b, c)] -- | zipWith generalises zip by zipping with the function -- given as the first argument, instead of a tupling function. For -- example, zipWith (+) is applied to two lists to -- produce the list of corresponding sums. -- -- zipWith is right-lazy: -- --
-- zipWith f [] _|_ = [] --zipWith :: () => a -> b -> c -> [a] -> [b] -> [c] -- | The zipWith3 function takes a function which combines three -- elements, as well as three lists and returns a list of their -- point-wise combination, analogous to zipWith. zipWith3 :: () => a -> b -> c -> d -> [a] -> [b] -> [c] -> [d] -- | the same as flip (-). -- -- Because - is treated specially in the Haskell grammar, -- (- e) is not a section, but an application of -- prefix negation. However, (subtract -- exp) is equivalent to the disallowed section. subtract :: Num a => a -> a -> a -- | The lex 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, -- lex returns a single successful `lexeme' consisting of the -- empty string. (Thus lex "" = [("","")].) If there is -- no legal lexeme at the beginning of the input string, lex fails -- (i.e. returns []). -- -- This lexer is not completely faithful to the Haskell lexical syntax in -- the following respects: -- --
-- main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]]) --appendFile :: FilePath -> String -> IO () -- | Read a character from the standard input device (same as -- hGetChar stdin). getChar :: IO Char -- | The getContents operation returns all user input as a single -- string, which is read lazily as it is needed (same as -- hGetContents stdin). getContents :: IO String -- | Read a line from the standard input device (same as hGetLine -- stdin). getLine :: IO String -- | The interact function takes a function of type -- String->String 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 () -- | The print function outputs a value of any printable type to the -- standard output device. Printable types are those that are instances -- of class Show; print converts values to strings for -- output using the show operation and adds a newline. -- -- For example, a program to print the first 20 integers and their powers -- of 2 could be written as: -- --
-- main = print ([(n, 2^n) | n <- [0..19]]) --print :: Show a => a -> IO () -- | Write a character to the standard output device (same as -- hPutChar stdout). putChar :: Char -> IO () -- | Write a string to the standard output device (same as hPutStr -- stdout). putStr :: String -> IO () -- | The same as putStr, but adds a newline character. putStrLn :: String -> IO () -- | The readFile function reads a file and returns the contents of -- the file as a string. The file is read lazily, on demand, as with -- getContents. readFile :: FilePath -> IO String -- | The readIO function is similar to read except that it -- signals parse failure to the IO monad instead of terminating -- the program. readIO :: Read a => String -> IO a -- | The readLn function combines getLine and readIO. readLn :: Read a => IO a -- | The computation writeFile file str function writes the -- string str, to the file file. writeFile :: FilePath -> String -> IO () -- | The read function reads input from a string, which must be -- completely consumed by the input process. read fails with an -- error if the parse is unsuccessful, and it is therefore -- discouraged from being used in real applications. Use readMaybe -- or readEither for safe alternatives. -- --
-- >>> read "123" :: Int -- 123 ---- --
-- >>> read "hello" :: Int -- *** Exception: Prelude.read: no parse --read :: Read a => String -> a -- | equivalent to readsPrec with a precedence of 0. reads :: Read a => ReadS a -- | Boolean "and" (&&) :: Bool -> Bool -> Bool infixr 3 && -- | Boolean "not" not :: Bool -> Bool -- | Boolean "or" (||) :: Bool -> Bool -> Bool infixr 2 || -- | Application operator. This operator is redundant, since ordinary -- application (f x) means the same as (f $ x). -- However, $ has low, right-associative binding precedence, so it -- sometimes allows parentheses to be omitted; for example: -- --
-- f $ g $ h x = f (g (h x)) ---- -- It is also useful in higher-order situations, such as map -- ($ 0) xs, or zipWith ($) fs xs. ($) :: () => a -> b -> a -> b infixr 0 $ -- | error stops execution and displays an error message. error :: HasCallStack => [Char] -> a -- | A variant of error that does not produce a stack trace. errorWithoutStackTrace :: () => [Char] -> a -- | A special case of error. It is expected that compilers will -- recognize this and insert error messages which are more appropriate to -- the context in which undefined appears. undefined :: HasCallStack => a -- | The value of seq a b is bottom if a is bottom, and -- otherwise equal to b. In other words, it evaluates the first -- argument a to weak head normal form (WHNF). seq is -- usually introduced to improve performance by avoiding unneeded -- laziness. -- -- A note on evaluation order: the expression seq a b does -- not guarantee that a will be evaluated before -- b. The only guarantee given by seq is that the both -- a and b will be evaluated before seq -- returns a value. In particular, this means that b may be -- evaluated before a. If you need to guarantee a specific order -- of evaluation, you must use the function pseq from the -- "parallel" package. seq :: () => a -> b -> b -- | Does the element occur in the structure? elem :: (Foldable t, Eq a) => a -> t a -> Bool infix 4 `elem` -- | Map each element of the structure to a monoid, and combine the -- results. foldMap :: (Foldable t, Monoid m) => a -> m -> t a -> m -- | Left-associative fold of a structure. -- -- In the case of lists, foldl, when 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: -- --
-- foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn ---- -- Note that to produce the outermost application of the operator the -- entire input list must be traversed. This means that foldl' -- will diverge if given an infinite list. -- -- Also note that if you want an efficient left-fold, you probably want -- to use foldl' instead of foldl. The reason for this is -- that latter does not force the "inner" results (e.g. z f -- x1 in the above example) before applying them to the operator -- (e.g. to (f x2)). This results in a thunk chain -- O(n) elements long, which then must be evaluated from the -- outside-in. -- -- For a general Foldable structure this should be semantically -- identical to, -- --
-- foldl f z = foldl f z . toList --foldl :: Foldable t => b -> a -> b -> b -> t a -> b -- | A variant of foldl that has no base case, and thus may only be -- applied to non-empty structures. -- --
-- foldl1 f = foldl1 f . toList --foldl1 :: Foldable t => a -> a -> a -> t a -> a -- | Right-associative fold of a structure. -- -- In the case of lists, foldr, when 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: -- --
-- foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...) ---- -- Note that, since the head of the resulting expression is produced by -- an application of the operator to the first element of the list, -- foldr can produce a terminating expression from an infinite -- list. -- -- For a general Foldable structure this should be semantically -- identical to, -- --
-- foldr f z = foldr f z . toList --foldr :: Foldable t => a -> b -> b -> b -> t a -> b -- | A variant of foldr that has no base case, and thus may only be -- applied to non-empty structures. -- --
-- foldr1 f = foldr1 f . toList --foldr1 :: Foldable t => a -> a -> a -> t a -> a -- | Returns the size/length of a finite structure as an Int. The -- default implementation is optimized for structures that are similar to -- cons-lists, because there is no general way to do better. length :: Foldable t => t a -> Int -- | The largest element of a non-empty structure. maximum :: (Foldable t, Ord a) => t a -> a -- | The least element of a non-empty structure. minimum :: (Foldable t, Ord a) => t a -> a -- | Test whether the structure is empty. The default implementation is -- optimized for structures that are similar to cons-lists, because there -- is no general way to do better. null :: Foldable t => t a -> Bool -- | The product function computes the product of the numbers of a -- structure. product :: (Foldable t, Num a) => t a -> a -- | The sum function computes the sum of the numbers of a -- structure. sum :: (Foldable t, Num a) => t a -> a -- | Map each element of a structure to a monadic action, evaluate these -- actions from left to right, and collect the results. For a version -- that ignores the results see mapM_. mapM :: (Traversable t, Monad m) => a -> m b -> t a -> m t b -- | Evaluate each monadic action in the structure from left to right, and -- collect the results. For a version that ignores the results see -- sequence_. sequence :: (Traversable t, Monad m) => t m a -> m t a -- | Evaluate each action in the structure from left to right, and and -- collect the results. For a version that ignores the results see -- sequenceA_. sequenceA :: (Traversable t, Applicative f) => t f a -> f t a -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and collect the results. For a version that -- ignores the results see traverse_. traverse :: (Traversable t, Applicative f) => a -> f b -> t a -> f t b -- | Sequence actions, discarding the value of the first argument. (*>) :: Applicative f => f a -> f b -> f b infixl 4 *> -- | Sequence actions, discarding the value of the second argument. (<*) :: Applicative f => f a -> f b -> f a infixl 4 <* -- | Sequential application. -- -- A few functors support an implementation of <*> that is -- more efficient than the default one. (<*>) :: Applicative f => f a -> b -> f a -> f b infixl 4 <*> -- | Lift a value. pure :: Applicative f => a -> f a -- | Replace all locations in the input with the same value. The default -- definition is fmap . const, but this may be -- overridden with a more efficient version. (<$) :: Functor f => a -> f b -> f a infixl 4 <$ fmap :: Functor f => a -> b -> f a -> f b -- | Sequentially compose two actions, discarding any value produced by the -- first, like sequencing operators (such as the semicolon) in imperative -- languages. (>>) :: Monad m => m a -> m b -> m b infixl 1 >> -- | Sequentially compose two actions, passing any value produced by the -- first as an argument to the second. (>>=) :: Monad m => m a -> a -> m b -> m b infixl 1 >>= -- | Fail with a message. This operation is not part of the mathematical -- definition of a monad, but is invoked on pattern-match failure in a -- do expression. -- -- As part of the MonadFail proposal (MFP), this function is moved to its -- own class MonadFail (see Control.Monad.Fail for more -- details). The definition here will be removed in a future release. fail :: Monad m => String -> m a -- | Inject a value into the monadic type. return :: Monad m => a -> m a -- | An associative operation -- -- NOTE: This method is redundant and has the default -- implementation mappend = '(<>)' since -- base-4.11.0.0. mappend :: Monoid a => a -> a -> a -- | Fold a list using the monoid. -- -- For most types, the default definition for mconcat will be -- used, but the function is included in the class definition so that an -- optimized version can be provided for specific types. mconcat :: Monoid a => [a] -> a -- | Identity of mappend mempty :: Monoid a => a -- | An associative operation. (<>) :: Semigroup a => a -> a -> a infixr 6 <> maxBound :: Bounded a => a minBound :: Bounded a => a -- | Used in Haskell's translation of [n..]. enumFrom :: Enum a => a -> [a] -- | Used in Haskell's translation of [n,n'..]. enumFromThen :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n,n'..m]. enumFromThenTo :: Enum a => a -> a -> a -> [a] -- | Used in Haskell's translation of [n..m]. enumFromTo :: Enum a => a -> a -> [a] -- | Convert to an Int. It is implementation-dependent what -- fromEnum returns when applied to a value that is too large to -- fit in an Int. fromEnum :: Enum a => a -> Int -- | the predecessor of a value. For numeric types, pred subtracts -- 1. pred :: Enum a => a -> a -- | the successor of a value. For numeric types, succ adds 1. succ :: Enum a => a -> a -- | Convert from an Int. toEnum :: Enum a => Int -> a (**) :: Floating a => a -> a -> a infixr 8 ** acos :: Floating a => a -> a acosh :: Floating a => a -> a asin :: Floating a => a -> a asinh :: Floating a => a -> a atan :: Floating a => a -> a atanh :: Floating a => a -> a cos :: Floating a => a -> a cosh :: Floating a => a -> a exp :: Floating a => a -> a log :: Floating a => a -> a logBase :: Floating a => a -> a -> a pi :: Floating a => a sin :: Floating a => a -> a sinh :: Floating a => a -> a sqrt :: Floating a => a -> a tan :: Floating a => a -> a tanh :: Floating a => a -> a -- | a version of arctangent taking two real floating-point arguments. For -- real floating x and y, atan2 y x -- computes the angle (from the positive x-axis) of the vector from the -- origin to the point (x,y). atan2 y x returns -- a value in the range [-pi, pi]. It follows the -- Common Lisp semantics for the origin when signed zeroes are supported. -- atan2 y 1, with y in a type that is -- RealFloat, should return the same value as atan -- y. A default definition of atan2 is provided, but -- implementors can provide a more accurate implementation. atan2 :: RealFloat a => a -> a -> a -- | The function decodeFloat applied to a real floating-point -- number returns the significand expressed as an Integer and an -- appropriately scaled exponent (an Int). If -- decodeFloat x yields (m,n), then x -- is equal in value to m*b^^n, where b is the -- floating-point radix, and furthermore, either m and -- n are both zero or else b^(d-1) <= abs m < -- b^d, where d is the value of floatDigits -- x. In particular, decodeFloat 0 = (0,0). If the -- type contains a negative zero, also decodeFloat (-0.0) = -- (0,0). The result of decodeFloat x is -- unspecified if either of isNaN x or -- isInfinite x is True. decodeFloat :: RealFloat a => a -> (Integer, Int) -- | encodeFloat performs the inverse of decodeFloat in the -- sense that for finite x with the exception of -0.0, -- uncurry encodeFloat (decodeFloat x) = -- x. encodeFloat m n is one of the two closest -- representable floating-point numbers to m*b^^n (or -- ±Infinity if overflow occurs); usually the closer, but if -- m contains too many bits, the result may be rounded in the -- wrong direction. encodeFloat :: RealFloat a => Integer -> Int -> a -- | exponent corresponds to the second component of -- decodeFloat. exponent 0 = 0 and for finite -- nonzero x, exponent x = snd (decodeFloat x) -- + floatDigits x. If x is a finite floating-point -- number, it is equal in value to significand x * b ^^ -- exponent x, where b is the floating-point radix. -- The behaviour is unspecified on infinite or NaN values. exponent :: RealFloat a => a -> Int -- | a constant function, returning the number of digits of -- floatRadix in the significand floatDigits :: RealFloat a => a -> Int -- | a constant function, returning the radix of the representation (often -- 2) floatRadix :: RealFloat a => a -> Integer -- | a constant function, returning the lowest and highest values the -- exponent may assume floatRange :: RealFloat a => a -> (Int, Int) -- | True if the argument is too small to be represented in -- normalized format isDenormalized :: RealFloat a => a -> Bool -- | True if the argument is an IEEE floating point number isIEEE :: RealFloat a => a -> Bool -- | True if the argument is an IEEE infinity or negative infinity isInfinite :: RealFloat a => a -> Bool -- | True if the argument is an IEEE "not-a-number" (NaN) value isNaN :: RealFloat a => a -> Bool -- | True if the argument is an IEEE negative zero isNegativeZero :: RealFloat a => a -> Bool -- | multiplies a floating-point number by an integer power of the radix scaleFloat :: RealFloat a => Int -> a -> a -- | The first component of decodeFloat, scaled to lie in the open -- interval (-1,1), either 0.0 or of absolute -- value >= 1/b, where b is the floating-point -- radix. The behaviour is unspecified on infinite or NaN -- values. significand :: RealFloat a => a -> a (*) :: Num a => a -> a -> a infixl 7 * (+) :: Num a => a -> a -> a infixl 6 + (-) :: Num a => a -> a -> a infixl 6 - -- | Absolute value. abs :: Num a => a -> a -- | Unary negation. negate :: Num a => a -> a -- | Sign of a number. The functions abs and signum should -- satisfy the law: -- --
-- abs x * signum x == x ---- -- For real numbers, the signum is either -1 (negative), -- 0 (zero) or 1 (positive). signum :: Num a => a -> a -- | The method readList is provided to allow the programmer to give -- a specialised way of parsing lists of values. For example, this is -- used by the predefined Read instance of the Char type, -- where values of type String should be are expected to use -- double quotes, rather than square brackets. readList :: Read a => ReadS [a] -- | attempts to parse a value from the front of the string, returning a -- list of (parsed value, remaining string) pairs. If there is no -- successful parse, the returned list is empty. -- -- Derived instances of Read and Show satisfy the -- following: -- -- -- -- That is, readsPrec parses the string produced by -- showsPrec, and delivers the value that showsPrec started -- with. readsPrec :: Read a => Int -> ReadS a -- | fractional division (/) :: Fractional a => a -> a -> a infixl 7 / -- | Conversion from a Rational (that is Ratio -- Integer). A floating literal stands for an application of -- fromRational to a value of type Rational, so such -- literals have type (Fractional a) => a. fromRational :: Fractional a => Rational -> a -- | reciprocal fraction recip :: Fractional a => a -> a -- | integer division truncated toward negative infinity div :: Integral a => a -> a -> a infixl 7 `div` -- | simultaneous div and mod divMod :: Integral a => a -> a -> (a, a) -- | integer modulus, satisfying -- --
-- (x `div` y)*y + (x `mod` y) == x --mod :: Integral a => a -> a -> a infixl 7 `mod` -- | integer division truncated toward zero quot :: Integral a => a -> a -> a infixl 7 `quot` -- | simultaneous quot and rem quotRem :: Integral a => a -> a -> (a, a) -- | integer remainder, satisfying -- --
-- (x `quot` y)*y + (x `rem` y) == x --rem :: Integral a => a -> a -> a infixl 7 `rem` -- | conversion to Integer toInteger :: Integral a => a -> Integer -- | the rational equivalent of its real argument with full precision toRational :: Real a => a -> Rational -- | ceiling x returns the least integer not less than -- x ceiling :: (RealFrac a, Integral b) => a -> b -- | floor x returns the greatest integer not greater than -- x floor :: (RealFrac a, Integral b) => a -> b -- | The function properFraction takes a real fractional number -- x and returns a pair (n,f) such that x = -- n+f, and: -- --
-- showsPrec d x r ++ s == showsPrec d x (r ++ s) ---- -- Derived instances of Read and Show satisfy the -- following: -- -- -- -- That is, readsPrec parses the string produced by -- showsPrec, and delivers the value that showsPrec started -- with. showsPrec :: Show a => Int -> a -> ShowS (/=) :: Eq a => a -> a -> Bool infix 4 /= (==) :: Eq a => a -> a -> Bool infix 4 == (<) :: Ord a => a -> a -> Bool infix 4 < (<=) :: Ord a => a -> a -> Bool infix 4 <= (>) :: Ord a => a -> a -> Bool infix 4 > (>=) :: Ord a => a -> a -> Bool infix 4 >= compare :: Ord a => a -> a -> Ordering max :: Ord a => a -> a -> a min :: Ord a => a -> a -> a -- | A functor with application, providing operations to -- --
-- (<*>) = liftA2 id ---- --
-- liftA2 f x y = f <$> x <*> y ---- -- Further, any definition must satisfy the following: -- --
pure id <*> -- v = v
pure (.) <*> u -- <*> v <*> w = u <*> (v -- <*> w)
pure f <*> -- pure x = pure (f x)
u <*> pure y = -- pure ($ y) <*> u
-- forall x y. p (q x y) = f x . g y ---- -- it follows from the above that -- --
-- liftA2 p (liftA2 q u v) = liftA2 f u . liftA2 g v ---- -- If f is also a Monad, it should satisfy -- -- -- -- (which implies that pure and <*> satisfy the -- applicative functor laws). class Functor f => Applicative (f :: * -> *) -- | The Bounded class is used to name the upper and lower limits of -- a type. Ord is not a superclass of Bounded since types -- that are not totally ordered may also have upper and lower bounds. -- -- The Bounded class may be derived for any enumeration type; -- minBound is the first constructor listed in the data -- declaration and maxBound is the last. Bounded may also -- be derived for single-constructor datatypes whose constituent types -- are in Bounded. class Bounded a -- | Class Enum defines operations on sequentially ordered types. -- -- The enumFrom... methods are used in Haskell's translation of -- arithmetic sequences. -- -- Instances of Enum 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 fromEnum from -- 0 through n-1. See Chapter 10 of the Haskell -- Report for more details. -- -- For any type that is an instance of class Bounded as well as -- Enum, the following should hold: -- --
-- enumFrom x = enumFromTo x maxBound -- enumFromThen x y = enumFromThenTo x y bound -- where -- bound | fromEnum y >= fromEnum x = maxBound -- | otherwise = minBound --class Enum a -- | The Eq class defines equality (==) and inequality -- (/=). All the basic datatypes exported by the Prelude -- are instances of Eq, and Eq may be derived for any -- datatype whose constituents are also instances of Eq. -- -- Minimal complete definition: either == or /=. class Eq a -- | Trigonometric and hyperbolic functions and related functions. class Fractional a => Floating a -- | Data structures that can be folded. -- -- For example, given a data type -- --
-- data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a) ---- -- a suitable instance would be -- --
-- 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 ---- -- This is suitable even for abstract types, as the monoid is assumed to -- satisfy the monoid laws. Alternatively, one could define -- foldr: -- --
-- 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 ---- -- Foldable instances are expected to satisfy the following -- laws: -- --
-- foldr f z t = appEndo (foldMap (Endo . f) t ) z ---- --
-- foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z ---- --
-- fold = foldMap id ---- --
-- length = getSum . foldMap (Sum . const 1) ---- -- sum, product, maximum, and minimum -- should all be essentially equivalent to foldMap forms, such -- as -- --
-- sum = getSum . foldMap Sum ---- -- but may be less defined. -- -- If the type is also a Functor instance, it should satisfy -- --
-- foldMap f = fold . fmap f ---- -- which implies that -- --
-- foldMap f . fmap g = foldMap (f . g) --class Foldable (t :: * -> *) -- | Fractional numbers, supporting real division. class Num a => Fractional a -- | The Functor class is used for types that can be mapped over. -- Instances of Functor should satisfy the following laws: -- --
-- fmap id == id -- fmap (f . g) == fmap f . fmap g ---- -- The instances of Functor for lists, Maybe and IO -- satisfy these laws. class Functor (f :: * -> *) -- | Integral numbers, supporting integer division. class (Real a, Enum a) => Integral a -- | The Monad class defines the basic operations over a -- monad, a concept from a branch of mathematics known as -- category theory. From the perspective of a Haskell programmer, -- however, it is best to think of a monad as an abstract datatype -- of actions. Haskell's do expressions provide a convenient -- syntax for writing monadic expressions. -- -- Instances of Monad should satisfy the following laws: -- -- -- -- Furthermore, the Monad and Applicative operations should -- relate as follows: -- -- -- -- The above laws imply: -- -- -- -- and that pure and (<*>) satisfy the applicative -- functor laws. -- -- The instances of Monad for lists, Maybe and IO -- defined in the Prelude satisfy these laws. class Applicative m => Monad (m :: * -> *) -- | The class of monoids (types with an associative binary operation that -- has an identity). Instances should satisfy the following laws: -- --
x <> mempty = x
mempty <> x = x
mconcat = foldr '(<>)' -- mempty
-- infixr 5 :^: -- data Tree a = Leaf a | Tree a :^: Tree a ---- -- the derived instance of Read in Haskell 2010 is equivalent to -- --
-- instance (Read a) => Read (Tree a) where
--
-- readsPrec d r = readParen (d > app_prec)
-- (\r -> [(Leaf m,t) |
-- ("Leaf",s) <- lex r,
-- (m,t) <- readsPrec (app_prec+1) s]) r
--
-- ++ readParen (d > up_prec)
-- (\r -> [(u:^:v,w) |
-- (u,s) <- readsPrec (up_prec+1) r,
-- (":^:",t) <- lex s,
-- (v,w) <- readsPrec (up_prec+1) t]) r
--
-- where app_prec = 10
-- up_prec = 5
--
--
-- Note that right-associativity of :^: is unused.
--
-- The derived instance in GHC is equivalent to
--
-- -- instance (Read a) => Read (Tree a) where -- -- readPrec = parens $ (prec app_prec $ do -- Ident "Leaf" <- lexP -- m <- step readPrec -- return (Leaf m)) -- -- +++ (prec up_prec $ do -- u <- step readPrec -- Symbol ":^:" <- lexP -- v <- step readPrec -- return (u :^: v)) -- -- where app_prec = 10 -- up_prec = 5 -- -- readListPrec = readListPrecDefault ---- -- Why do both readsPrec and readPrec exist, and why does -- GHC opt to implement readPrec in derived Read instances -- instead of readsPrec? The reason is that readsPrec is -- based on the ReadS type, and although ReadS is mentioned -- in the Haskell 2010 Report, it is not a very efficient parser data -- structure. -- -- readPrec, on the other hand, is based on a much more efficient -- ReadPrec datatype (a.k.a "new-style parsers"), but its -- definition relies on the use of the RankNTypes language -- extension. Therefore, readPrec (and its cousin, -- readListPrec) are marked as GHC-only. Nevertheless, it is -- recommended to use readPrec instead of readsPrec -- whenever possible for the efficiency improvements it brings. -- -- As mentioned above, derived Read instances in GHC will -- implement readPrec instead of readsPrec. The default -- implementations of readsPrec (and its cousin, readList) -- will simply use readPrec under the hood. If you are writing a -- Read instance by hand, it is recommended to write it like so: -- --
-- instance Read T where -- readPrec = ... -- readListPrec = readListPrecDefault --class Read a class (Num a, Ord a) => Real a -- | Efficient, machine-independent access to the components of a -- floating-point number. class (RealFrac a, Floating a) => RealFloat a -- | Extracting components of fractions. class (Real a, Fractional a) => RealFrac a -- | The class of semigroups (types with an associative binary operation). -- -- Instances should satisfy the associativity law: -- -- class Semigroup a -- | Conversion of values to readable Strings. -- -- Derived instances of Show have the following properties, which -- are compatible with derived instances of Read: -- --
-- infixr 5 :^: -- data Tree a = Leaf a | Tree a :^: Tree a ---- -- the derived instance of Show is equivalent to -- --
-- instance (Show a) => Show (Tree a) where -- -- showsPrec d (Leaf m) = showParen (d > app_prec) $ -- showString "Leaf " . showsPrec (app_prec+1) m -- where app_prec = 10 -- -- showsPrec d (u :^: v) = showParen (d > up_prec) $ -- showsPrec (up_prec+1) u . -- showString " :^: " . -- showsPrec (up_prec+1) v -- where up_prec = 5 ---- -- Note that right-associativity of :^: is ignored. For example, -- --
-- t :: (Applicative f, Applicative g) => f a -> g a ---- -- preserving the Applicative operations, i.e. -- -- -- -- and the identity functor Identity and composition of functors -- Compose are defined as -- --
-- newtype Identity a = Identity a -- -- instance Functor Identity where -- fmap f (Identity x) = Identity (f x) -- -- instance Applicative Identity where -- pure x = Identity x -- Identity f <*> Identity x = Identity (f x) -- -- newtype Compose f g a = Compose (f (g a)) -- -- instance (Functor f, Functor g) => Functor (Compose f g) where -- fmap f (Compose x) = Compose (fmap (fmap f) x) -- -- instance (Applicative f, Applicative g) => Applicative (Compose f g) where -- pure x = Compose (pure (pure x)) -- Compose f <*> Compose x = Compose ((<*>) <$> f <*> x) ---- -- (The naturality law is implied by parametricity.) -- -- Instances are similar to Functor, e.g. given a data type -- --
-- data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a) ---- -- a suitable instance would be -- --
-- instance Traversable Tree where -- traverse f Empty = pure Empty -- traverse f (Leaf x) = Leaf <$> f x -- traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r ---- -- This is suitable even for abstract types, as the laws for -- <*> imply a form of associativity. -- -- The superclass instances should satisfy the following: -- --
-- >>> let s = Left "foo" :: Either String Int -- -- >>> s -- Left "foo" -- -- >>> let n = Right 3 :: Either String Int -- -- >>> n -- Right 3 -- -- >>> :type s -- s :: Either String Int -- -- >>> :type n -- n :: Either String Int ---- -- The fmap from our Functor instance will ignore -- Left values, but will apply the supplied function to values -- contained in a Right: -- --
-- >>> let s = Left "foo" :: Either String Int -- -- >>> let n = Right 3 :: Either String Int -- -- >>> fmap (*2) s -- Left "foo" -- -- >>> fmap (*2) n -- Right 6 ---- -- The Monad instance for Either allows us to chain -- together multiple actions which may fail, and fail overall if any of -- the individual steps failed. First we'll write a function that can -- either parse an Int from a Char, or fail. -- --
-- >>> import Data.Char ( digitToInt, isDigit )
--
-- >>> :{
-- let parseEither :: Char -> Either String Int
-- parseEither c
-- | isDigit c = Right (digitToInt c)
-- | otherwise = Left "parse error"
--
-- >>> :}
--
--
-- The following should work, since both '1' and '2'
-- can be parsed as Ints.
--
--
-- >>> :{
-- let parseMultiple :: Either String Int
-- parseMultiple = do
-- x <- parseEither '1'
-- y <- parseEither '2'
-- return (x + y)
--
-- >>> :}
--
--
-- -- >>> parseMultiple -- Right 3 ---- -- But the following should fail overall, since the first operation where -- we attempt to parse 'm' as an Int will fail: -- --
-- >>> :{
-- let parseMultiple :: Either String Int
-- parseMultiple = do
-- x <- parseEither 'm'
-- y <- parseEither '2'
-- return (x + y)
--
-- >>> :}
--
--
-- -- >>> parseMultiple -- Left "parse error" --data Either a b Left :: a -> Either a b Right :: b -> Either a b -- | The Maybe type encapsulates an optional value. A value of type -- Maybe a either contains a value of type a -- (represented as Just a), or it is empty (represented -- as Nothing). Using Maybe is a good way to deal with -- errors or exceptional cases without resorting to drastic measures such -- as error. -- -- The Maybe type is also a monad. It is a simple kind of error -- monad, where all errors are represented by Nothing. A richer -- error monad can be built using the Either type. data Maybe a Nothing :: Maybe a Just :: a -> Maybe a data Ordering LT :: Ordering EQ :: Ordering GT :: Ordering -- | File and directory names are values of type String, whose -- precise meaning is operating system dependent. Files can be opened, -- yielding a handle which can then be used to operate on the contents of -- that file. type FilePath = String -- | The Haskell 2010 type for exceptions in the IO monad. Any I/O -- operation may raise an IOError instead of returning a result. -- For a more general type of exception, including also those that arise -- in pure code, see Exception. -- -- In Haskell 2010, this is an opaque type. type IOError = IOException -- | Arbitrary-precision rational numbers, represented as a ratio of two -- Integer values. A rational number may be constructed using the -- % operator. type Rational = Ratio Integer -- | A parser for a type a, represented as a function that takes a -- String and returns a list of possible parses as -- (a,String) pairs. -- -- Note that this kind of backtracking parser is very inefficient; -- reading a large structure may be quite slow (cf ReadP). type ReadS a = String -> [(a, String)] -- | The shows functions return a function that prepends the -- output String to an existing String. This allows -- constant-time concatenation of results using function composition. type ShowS = String -> String -- | A String is a list of characters. String constants in Haskell -- are values of type String. type String = [Char] -- | Reexports Prelude.Compat from a globally unique namespace. module Prelude.Compat.Repl -- | Miscellaneous information about the system environment. module System.Environment.Compat -- | Computation getArgs returns a list of the program's command -- line arguments (not including the program name). getArgs :: IO [String] -- | Computation getProgName 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 FOO.EXE, and that is what -- getProgName will return. getProgName :: IO String -- | Computation getEnv var returns the value of the -- environment variable var. For the inverse, the setEnv -- function can be used. -- -- This computation may fail with: -- --
-- setEnv name "" ---- -- has the same effect as -- --
-- unsetEnv name ---- -- If you'd like to be able to set environment variables to blank -- strings, use setEnv. -- -- Throws IOException if name is the empty string or -- contains an equals sign. setEnv :: String -> String -> IO () -- | unsetEnv name removes the specified environment variable from -- the environment of the current process. -- -- Throws IOException if name is the empty string or -- contains an equals sign. unsetEnv :: String -> IO () -- | withArgs args act - while executing action -- act, have getArgs return args. withArgs :: () => [String] -> IO a -> IO a -- | withProgName name act - while executing action -- act, have getProgName return name. withProgName :: () => String -> IO a -> IO a -- | getEnvironment retrieves the entire environment as a list of -- (key,value) pairs. -- -- If an environment entry does not contain an '=' character, -- the key is the whole entry and the value is the -- empty string. getEnvironment :: IO [(String, String)] -- | Reexports System.Environment.Compat from a globally unique -- namespace. module System.Environment.Compat.Repl module System.Exit.Compat -- | Write given error message to stderr and terminate with -- exitFailure. die :: () => String -> IO a -- | Reexports System.Exit.Compat from a globally unique namespace. module System.Exit.Compat.Repl module System.IO.Unsafe.Compat -- | A slightly faster version of fixIO that may not be safe to use -- with multiple threads. The unsafety arises when used like this: -- --
-- unsafeFixIO $ \r -> do -- forkIO (print r) -- return (...) ---- -- In this case, the child thread will receive a NonTermination -- exception instead of waiting for the value of r to be -- computed. unsafeFixIO :: () => a -> IO a -> IO a -- | This version of unsafePerformIO is more efficient because it -- omits the check that the IO is only being performed by a single -- thread. Hence, when you use unsafeDupablePerformIO, 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. It may even happen that one of the duplicated -- IO actions is only run partially, and then interrupted in the middle -- without an exception being raised. Therefore, functions like -- bracket cannot be used safely within -- unsafeDupablePerformIO. unsafeDupablePerformIO :: () => IO a -> a -- | Reexports System.IO.Unsafe.Compat from a globally unique -- namespace. module System.IO.Unsafe.Compat.Repl module Text.Read.Compat -- | Parsing of Strings, producing values. -- -- Derived instances of Read make the following assumptions, which -- derived instances of Show obey: -- --
-- infixr 5 :^: -- data Tree a = Leaf a | Tree a :^: Tree a ---- -- the derived instance of Read in Haskell 2010 is equivalent to -- --
-- instance (Read a) => Read (Tree a) where
--
-- readsPrec d r = readParen (d > app_prec)
-- (\r -> [(Leaf m,t) |
-- ("Leaf",s) <- lex r,
-- (m,t) <- readsPrec (app_prec+1) s]) r
--
-- ++ readParen (d > up_prec)
-- (\r -> [(u:^:v,w) |
-- (u,s) <- readsPrec (up_prec+1) r,
-- (":^:",t) <- lex s,
-- (v,w) <- readsPrec (up_prec+1) t]) r
--
-- where app_prec = 10
-- up_prec = 5
--
--
-- Note that right-associativity of :^: is unused.
--
-- The derived instance in GHC is equivalent to
--
-- -- instance (Read a) => Read (Tree a) where -- -- readPrec = parens $ (prec app_prec $ do -- Ident "Leaf" <- lexP -- m <- step readPrec -- return (Leaf m)) -- -- +++ (prec up_prec $ do -- u <- step readPrec -- Symbol ":^:" <- lexP -- v <- step readPrec -- return (u :^: v)) -- -- where app_prec = 10 -- up_prec = 5 -- -- readListPrec = readListPrecDefault ---- -- Why do both readsPrec and readPrec exist, and why does -- GHC opt to implement readPrec in derived Read instances -- instead of readsPrec? The reason is that readsPrec is -- based on the ReadS type, and although ReadS is mentioned -- in the Haskell 2010 Report, it is not a very efficient parser data -- structure. -- -- readPrec, on the other hand, is based on a much more efficient -- ReadPrec datatype (a.k.a "new-style parsers"), but its -- definition relies on the use of the RankNTypes language -- extension. Therefore, readPrec (and its cousin, -- readListPrec) are marked as GHC-only. Nevertheless, it is -- recommended to use readPrec instead of readsPrec -- whenever possible for the efficiency improvements it brings. -- -- As mentioned above, derived Read instances in GHC will -- implement readPrec instead of readsPrec. The default -- implementations of readsPrec (and its cousin, readList) -- will simply use readPrec under the hood. If you are writing a -- Read instance by hand, it is recommended to write it like so: -- --
-- instance Read T where -- readPrec = ... -- readListPrec = readListPrecDefault --class Read a -- | attempts to parse a value from the front of the string, returning a -- list of (parsed value, remaining string) pairs. If there is no -- successful parse, the returned list is empty. -- -- Derived instances of Read and Show satisfy the -- following: -- -- -- -- That is, readsPrec parses the string produced by -- showsPrec, and delivers the value that showsPrec started -- with. readsPrec :: Read a => Int -> ReadS a -- | The method readList is provided to allow the programmer to give -- a specialised way of parsing lists of values. For example, this is -- used by the predefined Read instance of the Char type, -- where values of type String should be are expected to use -- double quotes, rather than square brackets. readList :: Read a => ReadS [a] -- | Proposed replacement for readsPrec using new-style parsers (GHC -- only). readPrec :: Read a => ReadPrec a -- | Proposed replacement for readList using new-style parsers (GHC -- only). The default definition uses readList. Instances that -- define readPrec should also define readListPrec as -- readListPrecDefault. readListPrec :: Read a => ReadPrec [a] -- | A parser for a type a, represented as a function that takes a -- String and returns a list of possible parses as -- (a,String) pairs. -- -- Note that this kind of backtracking parser is very inefficient; -- reading a large structure may be quite slow (cf ReadP). type ReadS a = String -> [(a, String)] -- | equivalent to readsPrec with a precedence of 0. reads :: Read a => ReadS a -- | The read function reads input from a string, which must be -- completely consumed by the input process. read fails with an -- error if the parse is unsuccessful, and it is therefore -- discouraged from being used in real applications. Use readMaybe -- or readEither for safe alternatives. -- --
-- >>> read "123" :: Int -- 123 ---- --
-- >>> read "hello" :: Int -- *** Exception: Prelude.read: no parse --read :: Read a => String -> a -- | readParen True p parses what p parses, -- but surrounded with parentheses. -- -- readParen False p parses what p -- parses, but optionally surrounded with parentheses. readParen :: () => Bool -> ReadS a -> ReadS a -- | The lex 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, -- lex returns a single successful `lexeme' consisting of the -- empty string. (Thus lex "" = [("","")].) If there is -- no legal lexeme at the beginning of the input string, lex fails -- (i.e. returns []). -- -- This lexer is not completely faithful to the Haskell lexical syntax in -- the following respects: -- --
-- >>> readEither "123" :: Either String Int -- Right 123 ---- --
-- >>> readEither "hello" :: Either String Int -- Left "Prelude.read: no parse" --readEither :: Read a => String -> Either String a -- | Parse a string using the Read instance. Succeeds if there is -- exactly one valid result. -- --
-- >>> readMaybe "123" :: Maybe Int -- Just 123 ---- --
-- >>> readMaybe "hello" :: Maybe Int -- Nothing --readMaybe :: Read a => String -> Maybe a -- | Reexports Text.Read.Compat from a globally unique namespace. module Text.Read.Compat.Repl module Type.Reflection.Compat -- | Use a TypeRep as Typeable evidence. withTypeable :: () => TypeRep a -> Typeable a -> r -> r -- | Reexports Type.Reflection.Compat from a globally unique -- namespace. module Type.Reflection.Compat.Repl