-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | A more progressive alternative to the "base" package -- -- This package is intended for those who are tired of keeping long lists -- of dependencies to the same essential libraries in each package as -- well as the endless imports of the same APIs all over again. It also -- supports the modern tendencies in the language. -- -- To solve those problems this package does the following: -- -- -- -- The policy behind the package is only to reexport the non-ambiguous -- and non-controversial APIs, which the community has obviously settled -- on. The package is intended to rapidly evolve with the contribution -- from the community, with the missing features being added with -- pull-requests. -- -- If you don't need the "Rebase" namespace and want to import modules -- from the reexported packages as they are check out the -- "rerebase" package which simply reexports the original symbols -- in the original namespace. Thus it simply lets you depend on all the -- de-facto default packages, by yourself having to maintain only the -- dependency on "rerebase". Also it comes packed with a prelude as rich -- as here. @package rebase @version 1.17 module Rebase.Control.Applicative module Rebase.Control.Applicative.Backwards module Rebase.Control.Applicative.Lift module Rebase.Control.Arrow module Rebase.Control.Category module Rebase.Control.Comonad module Rebase.Control.Concurrent module Rebase.Control.Concurrent.Chan module Rebase.Control.Concurrent.MVar module Rebase.Control.Concurrent.QSem module Rebase.Control.Concurrent.QSemN module Rebase.Control.Concurrent.STM module Rebase.Control.Concurrent.STM.TArray module Rebase.Control.Concurrent.STM.TBQueue module Rebase.Control.Concurrent.STM.TChan module Rebase.Control.Concurrent.STM.TMVar module Rebase.Control.Concurrent.STM.TQueue module Rebase.Control.Concurrent.STM.TSem module Rebase.Control.Concurrent.STM.TVar module Rebase.Control.DeepSeq module Rebase.Control.Exception module Rebase.Control.Exception.Base module Rebase.Control.Monad module Rebase.Control.Monad.Cont module Rebase.Control.Monad.Cont.Class module Rebase.Control.Monad.Error.Class module Rebase.Control.Monad.Fail module Rebase.Control.Monad.Fix module Rebase.Control.Monad.IO.Class module Rebase.Control.Monad.Identity module Rebase.Control.Monad.RWS module Rebase.Control.Monad.RWS.Class module Rebase.Control.Monad.RWS.Lazy module Rebase.Control.Monad.RWS.Strict module Rebase.Control.Monad.Reader module Rebase.Control.Monad.Reader.Class module Rebase.Control.Monad.ST module Rebase.Control.Monad.ST.Lazy module Rebase.Control.Monad.ST.Lazy.Safe module Rebase.Control.Monad.ST.Lazy.Unsafe module Rebase.Control.Monad.ST.Safe module Rebase.Control.Monad.ST.Strict module Rebase.Control.Monad.ST.Unsafe module Rebase.Control.Monad.STM module Rebase.Control.Monad.Signatures module Rebase.Control.Monad.State module Rebase.Control.Monad.State.Class module Rebase.Control.Monad.State.Lazy module Rebase.Control.Monad.State.Strict module Rebase.Control.Monad.Trans module Rebase.Control.Monad.Trans.Class module Rebase.Control.Monad.Trans.Cont module Rebase.Control.Monad.Trans.Except module Rebase.Control.Monad.Trans.Identity module Rebase.Control.Monad.Trans.List module Rebase.Control.Monad.Trans.Maybe module Rebase.Control.Monad.Trans.RWS module Rebase.Control.Monad.Trans.RWS.Lazy module Rebase.Control.Monad.Trans.RWS.Strict module Rebase.Control.Monad.Trans.Reader module Rebase.Control.Monad.Trans.State module Rebase.Control.Monad.Trans.State.Lazy module Rebase.Control.Monad.Trans.State.Strict module Rebase.Control.Monad.Trans.Writer module Rebase.Control.Monad.Trans.Writer.Lazy module Rebase.Control.Monad.Trans.Writer.Strict module Rebase.Control.Monad.Writer module Rebase.Control.Monad.Writer.Class module Rebase.Control.Monad.Writer.Lazy module Rebase.Control.Monad.Writer.Strict module Rebase.Control.Monad.Zip module Rebase.Control.Selective module Rebase.Control.Selective.Free module Rebase.Control.Selective.Multi module Rebase.Control.Selective.Rigid.Free module Rebase.Control.Selective.Rigid.Freer module Rebase.Control.Selective.Trans.Except module Rebase.Data.Biapplicative module Rebase.Data.Bifoldable module Rebase.Data.Bifunctor -- | A more meaningful and conflict-free alias for first. mapLeft :: Bifunctor p => (a -> b) -> p a c -> p b c -- | A more meaningful and conflict-free alias for second. mapRight :: Bifunctor p => (b -> c) -> p a b -> p a c module Rebase.Data.Bifunctor.Apply module Rebase.Data.Bifunctor.Biff module Rebase.Data.Bifunctor.Clown module Rebase.Data.Bifunctor.Flip module Rebase.Data.Bifunctor.Join module Rebase.Data.Bifunctor.Joker module Rebase.Data.Bifunctor.Product module Rebase.Data.Bifunctor.Tannen module Rebase.Data.Bifunctor.Wrapped module Rebase.Data.Bitraversable module Rebase.Data.Bits module Rebase.Data.Bool module Rebase.Data.ByteString module Rebase.Data.ByteString.Builder module Rebase.Data.ByteString.Builder.Extra module Rebase.Data.ByteString.Builder.Internal module Rebase.Data.ByteString.Builder.Prim module Rebase.Data.ByteString.Builder.Prim.Internal module Rebase.Data.ByteString.Builder.Scientific module Rebase.Data.ByteString.Char8 module Rebase.Data.ByteString.Internal module Rebase.Data.ByteString.Lazy module Rebase.Data.ByteString.Lazy.Char8 module Rebase.Data.ByteString.Lazy.Internal module Rebase.Data.ByteString.Short module Rebase.Data.ByteString.Short.Internal module Rebase.Data.ByteString.Unsafe module Rebase.Data.Char module Rebase.Data.Coerce module Rebase.Data.Complex module Rebase.Data.DList module Rebase.Data.Data module Rebase.Data.Dynamic module Rebase.Data.Either module Rebase.Data.Either.Combinators module Rebase.Data.Either.Validation module Rebase.Data.Eq module Rebase.Data.Fixed module Rebase.Data.Foldable module Rebase.Data.Function module Rebase.Data.Functor module Rebase.Data.Functor.Alt module Rebase.Data.Functor.Apply module Rebase.Data.Functor.Bind module Rebase.Data.Functor.Bind.Class module Rebase.Data.Functor.Bind.Trans module Rebase.Data.Functor.Classes module Rebase.Data.Functor.Compose module Rebase.Data.Functor.Constant module Rebase.Data.Functor.Contravariant module Rebase.Data.Functor.Contravariant.Compose module Rebase.Data.Functor.Contravariant.Divisible module Rebase.Data.Functor.Extend module Rebase.Data.Functor.Identity module Rebase.Data.Functor.Invariant module Rebase.Data.Functor.Invariant.TH module Rebase.Data.Functor.Plus module Rebase.Data.Functor.Product module Rebase.Data.Functor.Reverse module Rebase.Data.Functor.Sum module Rebase.Data.Graph module Rebase.Data.Group module Rebase.Data.Groupoid module Rebase.Data.HashMap.Lazy module Rebase.Data.HashMap.Strict module Rebase.Data.HashSet module Rebase.Data.Hashable module Rebase.Data.IORef module Rebase.Data.Int module Rebase.Data.IntMap module Rebase.Data.IntMap.Lazy module Rebase.Data.IntMap.Strict module Rebase.Data.IntSet module Rebase.Data.Isomorphism module Rebase.Data.Ix module Rebase.Data.Kind module Rebase.Data.List -- | If you're not a fan of magical or special cases, you probably have -- already been looking for this alias. type List = [] module Rebase.Data.List.NonEmpty -- | This module simply provides a more meaningful name to -- Data.List.NonEmpty. module Rebase.Data.List1 -- | A more meaningful name for the non-empty list. Follows the convention -- behind such names as foldr1. type List1 = NonEmpty module Rebase.Data.Map module Rebase.Data.Map.Lazy module Rebase.Data.Map.Strict module Rebase.Data.Maybe module Rebase.Data.Monoid module Rebase.Data.Ord module Rebase.Data.Profunctor module Rebase.Data.Profunctor.Adjunction module Rebase.Data.Profunctor.Cayley module Rebase.Data.Profunctor.Choice module Rebase.Data.Profunctor.Closed module Rebase.Data.Profunctor.Composition module Rebase.Data.Profunctor.Mapping module Rebase.Data.Profunctor.Monad module Rebase.Data.Profunctor.Ran module Rebase.Data.Profunctor.Rep module Rebase.Data.Profunctor.Sieve module Rebase.Data.Profunctor.Strong module Rebase.Data.Profunctor.Traversing module Rebase.Data.Profunctor.Types module Rebase.Data.Profunctor.Unsafe module Rebase.Data.Profunctor.Yoneda module Rebase.Data.Proxy module Rebase.Data.Ratio module Rebase.Data.STRef module Rebase.Data.STRef.Lazy module Rebase.Data.STRef.Strict module Rebase.Data.Scientific module Rebase.Data.Semigroup sappend :: Semigroup a => a -> a -> a module Rebase.Data.Semigroup.Bifoldable module Rebase.Data.Semigroup.Bitraversable module Rebase.Data.Semigroup.Foldable module Rebase.Data.Semigroup.Foldable.Class module Rebase.Data.Semigroup.Traversable module Rebase.Data.Semigroup.Traversable.Class module Rebase.Data.Semigroupoid module Rebase.Data.Semigroupoid.Dual module Rebase.Data.Semigroupoid.Ob module Rebase.Data.Semigroupoid.Static module Rebase.Data.Sequence module Rebase.Data.Set module Rebase.Data.String -- | Unifies some modules, which are separated in the original API for -- unknown reasons. module Rebase.Data.Text module Rebase.Data.Text.Array module Rebase.Data.Text.Encoding module Rebase.Data.Text.Encoding.Error module Rebase.Data.Text.Foreign module Rebase.Data.Text.IO module Rebase.Data.Text.Internal -- | Unifies some modules, which are separated in the original API for -- unknown reasons. module Rebase.Data.Text.Lazy module Rebase.Data.Text.Lazy.Builder module Rebase.Data.Text.Lazy.Builder.Int module Rebase.Data.Text.Lazy.Builder.RealFloat module Rebase.Data.Text.Lazy.Builder.Scientific module Rebase.Data.Text.Lazy.Encoding module Rebase.Data.Text.Lazy.IO module Rebase.Data.Text.Lazy.Read module Rebase.Data.Text.Read module Rebase.Data.Text.Unsafe module Rebase.Data.Time module Rebase.Data.Time.Calendar module Rebase.Data.Time.Calendar.Easter module Rebase.Data.Time.Calendar.Julian module Rebase.Data.Time.Calendar.MonthDay module Rebase.Data.Time.Calendar.OrdinalDate module Rebase.Data.Time.Calendar.WeekDate module Rebase.Data.Time.Clock module Rebase.Data.Time.Clock.POSIX module Rebase.Data.Time.Clock.System module Rebase.Data.Time.Clock.TAI module Rebase.Data.Time.Compat module Rebase.Data.Time.Format module Rebase.Data.Time.Format.ISO8601 module Rebase.Data.Time.LocalTime module Rebase.Data.Traversable module Rebase.Data.Traversable.Instances module Rebase.Data.Tree module Rebase.Data.Tuple module Rebase.Data.Type.Bool module Rebase.Data.Type.Coercion module Rebase.Data.Type.Equality module Rebase.Data.Typeable module Rebase.Data.UUID module Rebase.Data.Unique module Rebase.Data.Vector module Rebase.Data.Vector.Fusion.Stream.Monadic module Rebase.Data.Vector.Fusion.Util module Rebase.Data.Vector.Generic module Rebase.Data.Vector.Generic.Base module Rebase.Data.Vector.Generic.Mutable module Rebase.Data.Vector.Generic.New module Rebase.Data.Vector.Instances module Rebase.Data.Vector.Internal.Check module Rebase.Data.Vector.Mutable module Rebase.Data.Vector.Primitive module Rebase.Data.Vector.Primitive.Mutable module Rebase.Data.Vector.Storable module Rebase.Data.Vector.Storable.Internal module Rebase.Data.Vector.Storable.Mutable module Rebase.Data.Vector.Unboxed module Rebase.Data.Vector.Unboxed.Base module Rebase.Data.Vector.Unboxed.Mutable module Rebase.Data.Version module Rebase.Data.Void module Rebase.Data.Void.Unsafe module Rebase.Data.Word module Rebase.Debug.Trace module Rebase.Foreign module Rebase.Foreign.C module Rebase.Foreign.C.Error module Rebase.Foreign.C.String module Rebase.Foreign.C.Types module Rebase.Foreign.Concurrent module Rebase.Foreign.ForeignPtr module Rebase.Foreign.ForeignPtr.Safe module Rebase.Foreign.ForeignPtr.Unsafe module Rebase.Foreign.Marshal module Rebase.Foreign.Marshal.Alloc module Rebase.Foreign.Marshal.Array module Rebase.Foreign.Marshal.Error module Rebase.Foreign.Marshal.Pool module Rebase.Foreign.Marshal.Safe module Rebase.Foreign.Marshal.Unsafe module Rebase.Foreign.Marshal.Utils module Rebase.Foreign.Ptr module Rebase.Foreign.Safe module Rebase.Foreign.StablePtr module Rebase.Foreign.Storable module Rebase.GHC.Arr module Rebase.GHC.Base module Rebase.GHC.Char module Rebase.GHC.Conc module Rebase.GHC.Conc.IO module Rebase.GHC.Conc.Signal module Rebase.GHC.Conc.Sync module Rebase.GHC.ConsoleHandler module Rebase.GHC.Constants module Rebase.GHC.Desugar module Rebase.GHC.Enum module Rebase.GHC.Environment module Rebase.GHC.Err module Rebase.GHC.Exception module Rebase.GHC.Exts module Rebase.GHC.Fingerprint module Rebase.GHC.Fingerprint.Type module Rebase.GHC.Float module Rebase.GHC.Float.ConversionUtils module Rebase.GHC.Float.RealFracMethods module Rebase.GHC.Foreign module Rebase.GHC.ForeignPtr module Rebase.GHC.GHCi module Rebase.GHC.Generics module Rebase.GHC.IO module Rebase.GHC.IO.Buffer module Rebase.GHC.IO.BufferedIO module Rebase.GHC.IO.Device module Rebase.GHC.IO.Encoding module Rebase.GHC.IO.Encoding.CodePage module Rebase.GHC.IO.Encoding.Failure module Rebase.GHC.IO.Encoding.Iconv module Rebase.GHC.IO.Encoding.Latin1 module Rebase.GHC.IO.Encoding.Types module Rebase.GHC.IO.Encoding.UTF16 module Rebase.GHC.IO.Encoding.UTF32 module Rebase.GHC.IO.Encoding.UTF8 module Rebase.GHC.IO.Exception module Rebase.GHC.IO.FD module Rebase.GHC.IO.Handle module Rebase.GHC.IO.Handle.FD module Rebase.GHC.IO.Handle.Internals module Rebase.GHC.IO.Handle.Text module Rebase.GHC.IO.Handle.Types module Rebase.GHC.IO.IOMode module Rebase.GHC.IOArray module Rebase.GHC.IORef module Rebase.GHC.Int module Rebase.GHC.List module Rebase.GHC.MVar module Rebase.GHC.Num module Rebase.GHC.OverloadedLabels module Rebase.GHC.Pack module Rebase.GHC.Profiling module Rebase.GHC.Ptr module Rebase.GHC.Read module Rebase.GHC.Real module Rebase.GHC.Records module Rebase.GHC.ST module Rebase.GHC.STRef module Rebase.GHC.Show module Rebase.GHC.Stable module Rebase.GHC.Stack module Rebase.GHC.Stats module Rebase.GHC.Storable module Rebase.GHC.TopHandler module Rebase.GHC.TypeLits module Rebase.GHC.TypeNats module Rebase.GHC.Unicode module Rebase.GHC.Weak module Rebase.GHC.Word module Rebase.Numeric module Rebase.Numeric.Natural module Rebase.System.CPUTime module Rebase.System.Console.GetOpt module Rebase.System.Environment module Rebase.System.Exit module Rebase.System.IO module Rebase.System.IO.Error module Rebase.System.IO.Unsafe module Rebase.System.Info module Rebase.System.Mem module Rebase.System.Mem.StableName module Rebase.System.Mem.Weak module Rebase.System.Posix.Internals module Rebase.System.Posix.Types module Rebase.System.Timeout module Rebase.Text.ParserCombinators.ReadP module Rebase.Text.ParserCombinators.ReadPrec module Rebase.Text.Printf module Rebase.Text.Read module Rebase.Text.Read.Lex module Rebase.Text.Show module Rebase.Text.Show.Functions module Rebase.Unsafe.Coerce -- | This module reexports the non-conflicting definitions from the modules -- exported by this package, providing a much more featureful alternative -- to the standard Prelude. -- -- For details check out the source. module Rebase.Prelude -- | 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 ++ -- | 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 :: forall {r :: RuntimeRep} a (b :: TYPE r). a -> b -> b infixr 0 `seq` -- | <math>. 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 odd [1, 2, 3]
--   [1,3]
--   
filter :: (a -> Bool) -> [a] -> [a] -- | <math>. zip takes two lists and returns a list of -- corresponding pairs. -- --
--   >>> zip [1, 2] ['a', 'b']
--   [(1,'a'),(2,'b')]
--   
-- -- If one input list is shorter than the other, excess elements of the -- longer list are discarded, even if one of the lists is infinite: -- --
--   >>> zip [1] ['a', 'b']
--   [(1,'a')]
--   
--   >>> zip [1, 2] ['a']
--   [(1,'a')]
--   
--   >>> zip [] [1..]
--   []
--   
--   >>> zip [1..] []
--   []
--   
-- -- zip is right-lazy: -- --
--   >>> zip [] undefined
--   []
--   
--   >>> zip undefined []
--   *** Exception: Prelude.undefined
--   ...
--   
-- -- zip is capable of list fusion, but it is restricted to its -- first list argument and its resulting list. zip :: [a] -> [b] -> [(a, b)] -- | Create a stable pointer referring to the given Haskell value. newStablePtr :: a -> IO (StablePtr a) -- | 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 () -- | Extract the first component of a pair. fst :: (a, b) -> a -- | Extract the second component of a pair. snd :: (a, b) -> b -- | otherwise is defined as the value True. It helps to make -- guards more readable. eg. -- --
--   f x | x < 0     = ...
--       | otherwise = ...
--   
otherwise :: Bool -- | 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 -- | The lazy function restrains strictness analysis a little. The -- call lazy e means the same as e, but lazy has -- a magical property so far as strictness analysis is concerned: it is -- lazy in its first argument, even though its semantics is strict. After -- strictness analysis has run, calls to lazy are inlined to be -- the identity function. -- -- This behaviour is occasionally useful when controlling evaluation -- order. Notably, lazy is used in the library definition of -- par: -- --
--   par :: a -> b -> b
--   par x y = case (par# x) of _ -> lazy y
--   
-- -- If lazy were not lazy, par would look strict in -- y which would defeat the whole purpose of par. lazy :: a -> a assertError :: (?callStack :: CallStack) => Bool -> a -> a -- | The trace function outputs the trace message given as its first -- argument, before returning the second argument as its result. -- -- For example, this returns the value of f x and outputs the -- message to stderr. Depending on your terminal (settings), they may or -- may not be mixed. -- --
--   >>> let x = 123; f = show
--   
--   >>> trace ("calling f with x = " ++ show x) (f x)
--   calling f with x = 123
--   "123"
--   
-- -- The trace function should only be used for debugging, or -- for monitoring execution. The function is not referentially -- transparent: its type indicates that it is a pure function but it has -- the side effect of outputting the trace message. trace :: String -> a -> a -- | The call inline f arranges that f is inlined, -- regardless of its size. More precisely, the call inline f -- rewrites to the right-hand side of f's definition. This -- allows the programmer to control inlining from a particular call site -- rather than the definition site of the function (c.f. INLINE -- pragmas). -- -- This inlining occurs regardless of the argument to the call or the -- size of f's definition; it is unconditional. The main caveat -- is that f's definition must be visible to the compiler; it is -- therefore recommended to mark the function with an INLINABLE -- pragma at its definition so that GHC guarantees to record its -- unfolding regardless of size. -- -- If no inlining takes place, the inline function expands to the -- identity function in Phase zero, so its use imposes no overhead. inline :: a -> a -- | <math>. 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 (+1) [1, 2, 3]
--   [2,3,4]
--   
map :: (a -> b) -> [a] -> [b] -- | The groupWith function uses the user supplied function which -- projects an element out of every list element in order to first sort -- the input list and then to form groups by equality on these projected -- elements groupWith :: Ord b => (a -> b) -> [a] -> [[a]] -- | 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. -- -- Note that ($) is levity-polymorphic in its result -- type, so that foo $ True where foo :: Bool -> -- Int# is well-typed. ($) :: forall (r :: RuntimeRep) a (b :: TYPE r). (a -> b) -> a -> b infixr 0 $ -- | The function coerce allows you to safely convert between -- values of types that have the same representation with no run-time -- overhead. In the simplest case you can use it instead of a newtype -- constructor, to go from the newtype's concrete type to the abstract -- type. But it also works in more complicated settings, e.g. converting -- a list of newtypes to a list of concrete types. -- -- This function is runtime-representation polymorphic, but the -- RuntimeRep type argument is marked as Inferred, -- meaning that it is not available for visible type application. This -- means the typechecker will accept coerce @Int @Age 42. coerce :: forall {k :: RuntimeRep} (a :: TYPE k) (b :: TYPE k). Coercible a b => a -> b -- | general coercion from integral types fromIntegral :: (Integral a, Num b) => a -> b -- | general coercion to fractional types realToFrac :: (Real a, Fractional b) => a -> b -- | Conditional failure of Alternative computations. Defined by -- --
--   guard True  = pure ()
--   guard False = empty
--   
-- --

Examples

-- -- Common uses of guard include conditionally signaling an error -- in an error monad and conditionally rejecting the current choice in an -- Alternative-based parser. -- -- As an example of signaling an error in the error monad Maybe, -- consider a safe division function safeDiv x y that returns -- Nothing when the denominator y is zero and -- Just (x `div` y) otherwise. For example: -- --
--   >>> safeDiv 4 0
--   Nothing
--   
-- --
--   >>> safeDiv 4 2
--   Just 2
--   
-- -- A definition of safeDiv using guards, but not guard: -- --
--   safeDiv :: Int -> Int -> Maybe Int
--   safeDiv x y | y /= 0    = Just (x `div` y)
--               | otherwise = Nothing
--   
-- -- A definition of safeDiv using guard and Monad -- do-notation: -- --
--   safeDiv :: Int -> Int -> Maybe Int
--   safeDiv x y = do
--     guard (y /= 0)
--     return (x `div` y)
--   
guard :: Alternative f => Bool -> f () -- | The IsList class and its methods are intended to be used in -- conjunction with the OverloadedLists extension. class IsList l where { -- | The Item type function returns the type of items of the -- structure l. type family Item l; } -- | The fromList function constructs the structure l from -- the given list of Item l fromList :: IsList l => [Item l] -> l -- | The fromListN function takes the input list's length and -- potentially uses it to construct the structure l more -- efficiently compared to fromList. If the given number does not -- equal to the input list's length the behaviour of fromListN is -- not specified. -- --
--   fromListN (length xs) xs == fromList xs
--   
fromListN :: IsList l => Int -> [Item l] -> l -- | The toList function extracts a list of Item l from the -- structure l. It should satisfy fromList . toList = id. toList :: IsList l => l -> [Item l] -- | Converts an arbitrary value into an object of type Dynamic. -- -- The type of the object must be an instance of Typeable, which -- ensures that only monomorphically-typed objects may be converted to -- Dynamic. To convert a polymorphic object into Dynamic, -- give it a monomorphic type signature. For example: -- --
--   toDyn (id :: Int -> Int)
--   
toDyn :: Typeable a => a -> Dynamic unsafeEqualityProof :: forall {k} (a :: k) (b :: k). UnsafeEquality a b -- | Highly, terribly dangerous coercion from one representation type to -- another. Misuse of this function can invite the garbage collector to -- trounce upon your data and then laugh in your face. You don't want -- this function. Really. unsafeCoerce# :: forall (q :: RuntimeRep) (r :: RuntimeRep) (a :: TYPE q) (b :: TYPE r). a -> b -- | The join function is the conventional monad join operator. It -- is used to remove one level of monadic structure, projecting its bound -- argument into the outer level. -- -- 'join bss' can be understood as the do -- expression -- --
--   do bs <- bss
--      bs
--   
-- --

Examples

-- -- A common use of join is to run an IO computation -- returned from an STM transaction, since STM transactions -- can't perform IO directly. Recall that -- --
--   atomically :: STM a -> IO a
--   
-- -- is used to run STM transactions atomically. So, by specializing -- the types of atomically and join to -- --
--   atomically :: STM (IO b) -> IO (IO b)
--   join       :: IO (IO b)  -> IO b
--   
-- -- we can compose them as -- --
--   join . atomically :: STM (IO b) -> IO b
--   
-- -- to run an STM transaction and the IO action it returns. join :: Monad m => m (m a) -> m a -- | 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 minBound :: Bounded a => a maxBound :: Bounded a => 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 successor of a value. For numeric types, succ adds 1. succ :: Enum a => a -> a -- | the predecessor of a value. For numeric types, pred subtracts -- 1. pred :: Enum a => a -> a -- | Convert from an Int. toEnum :: Enum a => Int -> 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 -- | Used in Haskell's translation of [n..] with [n..] = -- enumFrom n, a possible implementation being enumFrom n = n : -- enumFrom (succ n). For example: -- -- enumFrom :: Enum a => a -> [a] -- | Used in Haskell's translation of [n,n'..] with [n,n'..] = -- enumFromThen n n', a possible implementation being -- enumFromThen n n' = n : n' : worker (f x) (f x n'), -- worker s v = v : worker s (s v), x = fromEnum n' - -- fromEnum n and f n y | n > 0 = f (n - 1) (succ y) | n < -- 0 = f (n + 1) (pred y) | otherwise = y For example: -- -- enumFromThen :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n..m] with [n..m] = -- enumFromTo n m, a possible implementation being enumFromTo n -- m | n <= m = n : enumFromTo (succ n) m | otherwise = []. For -- example: -- -- enumFromTo :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n,n'..m] with [n,n'..m] -- = enumFromThenTo n n' m, a possible implementation being -- enumFromThenTo n n' m = worker (f x) (c x) n m, x = -- fromEnum n' - fromEnum n, c x = bool (>=) ((x -- 0) f n y | n > 0 = f (n - 1) (succ y) | n < 0 = f (n + -- 1) (pred y) | otherwise = y and worker s c v m | c v m = v : -- worker s c (s v) m | otherwise = [] For example: -- -- enumFromThenTo :: Enum a => a -> a -> a -> [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. -- -- The Haskell Report defines no laws for Eq. However, instances -- are encouraged to follow these properties: -- -- -- -- Minimal complete definition: either == or /=. class Eq a (==) :: Eq a => a -> a -> Bool (/=) :: Eq a => a -> a -> Bool infix 4 == infix 4 /= -- | Trigonometric and hyperbolic functions and related functions. -- -- The Haskell Report defines no laws for Floating. However, -- (+), (*) and exp are -- customarily expected to define an exponential field and have the -- following properties: -- -- class Fractional a => Floating a pi :: Floating a => a exp :: Floating a => a -> a log :: Floating a => a -> a sqrt :: Floating a => a -> a (**) :: Floating a => a -> a -> a logBase :: Floating a => a -> a -> a sin :: Floating a => a -> a cos :: Floating a => a -> a tan :: Floating a => a -> a asin :: Floating a => a -> a acos :: Floating a => a -> a atan :: Floating a => a -> a sinh :: Floating a => a -> a cosh :: Floating a => a -> a tanh :: Floating a => a -> a asinh :: Floating a => a -> a acosh :: Floating a => a -> a atanh :: Floating a => a -> a -- | log1p x computes log (1 + x), but -- provides more precise results for small (absolute) values of -- x if possible. log1p :: Floating a => a -> a -- | expm1 x computes exp x - 1, but -- provides more precise results for small (absolute) values of -- x if possible. expm1 :: Floating a => a -> a -- | log1pexp x computes log (1 + exp -- x), but provides more precise results if possible. -- -- Examples: -- -- log1pexp :: Floating a => a -> a -- | log1mexp x computes log (1 - exp -- x), but provides more precise results if possible. -- -- Examples: -- -- log1mexp :: Floating a => a -> a infixr 8 ** -- | Fractional numbers, supporting real division. -- -- The Haskell Report defines no laws for Fractional. However, -- (+) and (*) are customarily expected -- to define a division ring and have the following properties: -- -- -- -- Note that it isn't customarily expected that a type instance of -- Fractional implement a field. However, all instances in -- base do. class Num a => Fractional a -- | Fractional division. (/) :: Fractional a => a -> a -> a -- | Reciprocal fraction. recip :: Fractional a => a -> a -- | 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 infixl 7 / -- | Integral numbers, supporting integer division. -- -- The Haskell Report defines no laws for Integral. However, -- Integral instances are customarily expected to define a -- Euclidean domain and have the following properties for the -- div/mod and quot/rem pairs, given suitable -- Euclidean functions f and g: -- -- -- -- An example of a suitable Euclidean function, for Integer's -- instance, is abs. class (Real a, Enum a) => Integral a -- | integer division truncated toward zero quot :: Integral a => a -> a -> a -- | integer remainder, satisfying -- --
--   (x `quot` y)*y + (x `rem` y) == x
--   
rem :: Integral a => a -> a -> a -- | integer division truncated toward negative infinity div :: Integral a => a -> a -> a -- | integer modulus, satisfying -- --
--   (x `div` y)*y + (x `mod` y) == x
--   
mod :: Integral a => a -> a -> a -- | simultaneous quot and rem quotRem :: Integral a => a -> a -> (a, a) -- | simultaneous div and mod divMod :: Integral a => a -> a -> (a, a) -- | conversion to Integer toInteger :: Integral a => a -> Integer infixl 7 `rem` infixl 7 `quot` infixl 7 `mod` infixl 7 `div` -- | 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: -- -- -- -- 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 :: Type -> Type) -- | Sequentially compose two actions, passing any value produced by the -- first as an argument to the second. -- -- 'as >>= bs' can be understood as the do -- expression -- --
--   do a <- as
--      bs a
--   
(>>=) :: 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. -- -- 'as >> bs' can be understood as the do -- expression -- --
--   do as
--      bs
--   
(>>) :: Monad m => m a -> m b -> m b -- | Inject a value into the monadic type. return :: Monad m => a -> m a infixl 1 >>= infixl 1 >> -- | The Data class comprehends a fundamental primitive -- gfoldl for folding over constructor applications, say terms. -- This primitive can be instantiated in several ways to map over the -- immediate subterms of a term; see the gmap combinators later -- in this class. Indeed, a generic programmer does not necessarily need -- to use the ingenious gfoldl primitive but rather the intuitive -- gmap combinators. The gfoldl primitive is completed by -- means to query top-level constructors, to turn constructor -- representations into proper terms, and to list all possible datatype -- constructors. This completion allows us to serve generic programming -- scenarios like read, show, equality, term generation. -- -- The combinators gmapT, gmapQ, gmapM, etc are all -- provided with default definitions in terms of gfoldl, leaving -- open the opportunity to provide datatype-specific definitions. (The -- inclusion of the gmap combinators as members of class -- Data allows the programmer or the compiler to derive -- specialised, and maybe more efficient code per datatype. Note: -- gfoldl is more higher-order than the gmap combinators. -- This is subject to ongoing benchmarking experiments. It might turn out -- that the gmap combinators will be moved out of the class -- Data.) -- -- Conceptually, the definition of the gmap combinators in terms -- of the primitive gfoldl requires the identification of the -- gfoldl function arguments. Technically, we also need to -- identify the type constructor c for the construction of the -- result type from the folded term type. -- -- In the definition of gmapQx combinators, we use -- phantom type constructors for the c in the type of -- gfoldl because the result type of a query does not involve the -- (polymorphic) type of the term argument. In the definition of -- gmapQl we simply use the plain constant type constructor -- because gfoldl is left-associative anyway and so it is readily -- suited to fold a left-associative binary operation over the immediate -- subterms. In the definition of gmapQr, extra effort is needed. We use -- a higher-order accumulation trick to mediate between left-associative -- constructor application vs. right-associative binary operation (e.g., -- (:)). When the query is meant to compute a value of type -- r, then the result type within generic folding is r -> -- r. So the result of folding is a function to which we finally -- pass the right unit. -- -- With the -XDeriveDataTypeable option, GHC can generate -- instances of the Data class automatically. For example, given -- the declaration -- --
--   data T a b = C1 a b | C2 deriving (Typeable, Data)
--   
-- -- GHC will generate an instance that is equivalent to -- --
--   instance (Data a, Data b) => Data (T a b) where
--       gfoldl k z (C1 a b) = z C1 `k` a `k` b
--       gfoldl k z C2       = z C2
--   
--       gunfold k z c = case constrIndex c of
--                           1 -> k (k (z C1))
--                           2 -> z C2
--   
--       toConstr (C1 _ _) = con_C1
--       toConstr C2       = con_C2
--   
--       dataTypeOf _ = ty_T
--   
--   con_C1 = mkConstr ty_T "C1" [] Prefix
--   con_C2 = mkConstr ty_T "C2" [] Prefix
--   ty_T   = mkDataType "Module.T" [con_C1, con_C2]
--   
-- -- This is suitable for datatypes that are exported transparently. class Typeable a => Data a -- | Left-associative fold operation for constructor applications. -- -- The type of gfoldl is a headache, but operationally it is a -- simple generalisation of a list fold. -- -- The default definition for gfoldl is const -- id, which is suitable for abstract datatypes with no -- substructures. gfoldl :: Data a => (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. () => g -> c g) -> a -> c a -- | Unfolding constructor applications gunfold :: Data a => (forall b r. Data b => c (b -> r) -> c r) -> (forall r. () => r -> c r) -> Constr -> c a -- | Obtaining the constructor from a given datum. For proper terms, this -- is meant to be the top-level constructor. Primitive datatypes are here -- viewed as potentially infinite sets of values (i.e., constructors). toConstr :: Data a => a -> Constr -- | The outer type constructor of the type dataTypeOf :: Data a => a -> DataType -- | Mediate types and unary type constructors. -- -- In Data instances of the form -- --
--   instance (Data a, ...) => Data (T a)
--   
-- -- dataCast1 should be defined as gcast1. -- -- The default definition is const Nothing, which -- is appropriate for instances of other forms. dataCast1 :: (Data a, Typeable t) => (forall d. Data d => c (t d)) -> Maybe (c a) -- | Mediate types and binary type constructors. -- -- In Data instances of the form -- --
--   instance (Data a, Data b, ...) => Data (T a b)
--   
-- -- dataCast2 should be defined as gcast2. -- -- The default definition is const Nothing, which -- is appropriate for instances of other forms. dataCast2 :: (Data a, Typeable t) => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c a) -- | A generic transformation that maps over the immediate subterms -- -- The default definition instantiates the type constructor c in -- the type of gfoldl to an identity datatype constructor, using -- the isomorphism pair as injection and projection. gmapT :: Data a => (forall b. Data b => b -> b) -> a -> a -- | A generic query with a left-associative binary operator gmapQl :: Data a => (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> a -> r -- | A generic query with a right-associative binary operator gmapQr :: forall r r'. Data a => (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> a -> r -- | A generic query that processes the immediate subterms and returns a -- list of results. The list is given in the same order as originally -- specified in the declaration of the data constructors. gmapQ :: Data a => (forall d. Data d => d -> u) -> a -> [u] -- | A generic query that processes one child by index (zero-based) gmapQi :: Data a => Int -> (forall d. Data d => d -> u) -> a -> u -- | A generic monadic transformation that maps over the immediate subterms -- -- The default definition instantiates the type constructor c in -- the type of gfoldl to the monad datatype constructor, defining -- injection and projection using return and >>=. gmapM :: (Data a, Monad m) => (forall d. Data d => d -> m d) -> a -> m a -- | Transformation of at least one immediate subterm does not fail gmapMp :: (Data a, MonadPlus m) => (forall d. Data d => d -> m d) -> a -> m a -- | Transformation of one immediate subterm with success gmapMo :: (Data a, MonadPlus m) => (forall d. Data d => d -> m d) -> a -> m a -- | A type f is a Functor if it provides a function fmap -- which, given any types a and b lets you apply any -- function from (a -> b) to turn an f a into an -- f b, preserving the structure of f. Furthermore -- f needs to adhere to the following: -- -- -- -- Note, that the second law follows from the free theorem of the type -- fmap and the first law, so you need only check that the former -- condition holds. class Functor (f :: Type -> Type) -- | fmap is used to apply a function of type (a -> b) -- to a value of type f a, where f is a functor, to produce a -- value of type f b. Note that for any type constructor with -- more than one parameter (e.g., Either), only the last type -- parameter can be modified with fmap (e.g., b in -- `Either a b`). -- -- Some type constructors with two parameters or more have a -- Bifunctor instance that allows both the last and the -- penultimate parameters to be mapped over. -- --

Examples

-- -- Convert from a Maybe Int to a Maybe String -- using show: -- --
--   >>> fmap show Nothing
--   Nothing
--   
--   >>> fmap show (Just 3)
--   Just "3"
--   
-- -- Convert from an Either Int Int to an Either Int -- String using show: -- --
--   >>> fmap show (Left 17)
--   Left 17
--   
--   >>> fmap show (Right 17)
--   Right "17"
--   
-- -- Double each element of a list: -- --
--   >>> fmap (*2) [1,2,3]
--   [2,4,6]
--   
-- -- Apply even to the second element of a pair: -- --
--   >>> fmap even (2,2)
--   (2,True)
--   
-- -- It may seem surprising that the function is only applied to the last -- element of the tuple compared to the list example above which applies -- it to every element in the list. To understand, remember that tuples -- are type constructors with multiple type parameters: a tuple of 3 -- elements (a,b,c) can also be written (,,) a b c and -- its Functor instance is defined for Functor ((,,) a -- b) (i.e., only the third parameter is free to be mapped over with -- fmap). -- -- It explains why fmap can be used with tuples containing -- values of different types as in the following example: -- --
--   >>> fmap even ("hello", 1.0, 4)
--   ("hello",1.0,True)
--   
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 infixl 4 <$ -- | Basic numeric class. -- -- The Haskell Report defines no laws for Num. However, -- (+) and (*) are customarily expected -- to define a ring and have the following properties: -- -- -- -- Note that it isn't customarily expected that a type instance of -- both Num and Ord implement an ordered ring. Indeed, in -- base only Integer and Rational do. class Num a (+) :: Num a => a -> a -> a (-) :: Num a => a -> a -> a (*) :: Num a => a -> a -> a -- | Unary negation. negate :: Num a => a -> a -- | Absolute value. abs :: 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 -- | Conversion from an Integer. An integer literal represents the -- application of the function fromInteger to the appropriate -- value of type Integer, so such literals have type -- (Num a) => a. fromInteger :: Num a => Integer -> a infixl 7 * infixl 6 + infixl 6 - -- | The Ord class is used for totally ordered datatypes. -- -- Instances of Ord can be derived for any user-defined datatype -- whose constituent types are in Ord. The declared order of the -- constructors in the data declaration determines the ordering in -- derived Ord instances. The Ordering datatype allows a -- single comparison to determine the precise ordering of two objects. -- -- Ord, as defined by the Haskell report, implements a total order -- and has the following properties: -- -- -- -- The following operator interactions are expected to hold: -- --
    --
  1. x >= y = y <= x
  2. --
  3. x < y = x <= y && x /= y
  4. --
  5. x > y = y < x
  6. --
  7. x < y = compare x y == LT
  8. --
  9. x > y = compare x y == GT
  10. --
  11. x == y = compare x y == EQ
  12. --
  13. min x y == if x <= y then x else y = True
  14. --
  15. max x y == if x >= y then x else y = True
  16. --
-- -- Note that (7.) and (8.) do not require min and -- max to return either of their arguments. The result is merely -- required to equal one of the arguments in terms of (==). -- -- Minimal complete definition: either compare or <=. -- Using compare can be more efficient for complex types. class Eq a => Ord a compare :: Ord a => a -> a -> Ordering (<) :: Ord a => a -> a -> Bool (<=) :: Ord a => a -> a -> Bool (>) :: Ord a => a -> a -> Bool (>=) :: Ord a => a -> a -> Bool max :: Ord a => a -> a -> a min :: Ord a => a -> a -> a infix 4 < infix 4 <= infix 4 > infix 4 >= -- | Parsing of Strings, producing values. -- -- Derived instances of Read make the following assumptions, which -- derived instances of Show obey: -- -- -- -- For example, given the declarations -- --
--   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] class (Num a, Ord a) => Real a -- | the rational equivalent of its real argument with full precision toRational :: Real a => a -> Rational -- | Efficient, machine-independent access to the components of a -- floating-point number. class (RealFrac a, Floating a) => RealFloat a -- | a constant function, returning the radix of the representation (often -- 2) floatRadix :: RealFloat a => a -> Integer -- | a constant function, returning the number of digits of -- floatRadix in the significand floatDigits :: RealFloat a => a -> Int -- | a constant function, returning the lowest and highest values the -- exponent may assume floatRange :: RealFloat a => a -> (Int, Int) -- | 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 -- | 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 -- | multiplies a floating-point number by an integer power of the radix scaleFloat :: RealFloat a => Int -> a -> a -- | True if the argument is an IEEE "not-a-number" (NaN) value isNaN :: 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 too small to be represented in -- normalized format isDenormalized :: RealFloat a => a -> Bool -- | True if the argument is an IEEE negative zero isNegativeZero :: RealFloat a => a -> Bool -- | True if the argument is an IEEE floating point number isIEEE :: RealFloat a => a -> Bool -- | 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 -- | Extracting components of fractions. class (Real a, Fractional a) => RealFrac a -- | The function properFraction takes a real fractional number -- x and returns a pair (n,f) such that x = -- n+f, and: -- -- -- -- The default definitions of the ceiling, floor, -- truncate and round functions are in terms of -- properFraction. properFraction :: (RealFrac a, Integral b) => a -> (b, a) -- | truncate x returns the integer nearest x -- between zero and x truncate :: (RealFrac a, Integral b) => a -> b -- | round x returns the nearest integer to x; the -- even integer if x is equidistant between two integers round :: (RealFrac a, Integral b) => a -> b -- | 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 -- | Conversion of values to readable Strings. -- -- Derived instances of Show have the following properties, which -- are compatible with derived instances of Read: -- -- -- -- For example, given the declarations -- --
--   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, -- -- class Show a -- | Convert a value to a readable String. -- -- showsPrec should satisfy the law -- --
--   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 -- | A specialised variant of showsPrec, using precedence context -- zero, and returning an ordinary String. show :: Show a => a -> String -- | The method showList is provided to allow the programmer to give -- a specialised way of showing lists of values. For example, this is -- used by the predefined Show instance of the Char type, -- where values of type String should be shown in double quotes, -- rather than between square brackets. showList :: Show a => [a] -> ShowS -- | The Ix class is used to map a contiguous subrange of values in -- a type onto integers. It is used primarily for array indexing (see the -- array package). -- -- The first argument (l,u) of each of these operations is a -- pair specifying the lower and upper bounds of a contiguous subrange of -- values. -- -- An implementation is entitled to assume the following laws about these -- operations: -- -- class Ord a => Ix a -- | The list of values in the subrange defined by a bounding pair. range :: Ix a => (a, a) -> [a] -- | The position of a subscript in the subrange. index :: Ix a => (a, a) -> a -> Int -- | Returns True the given subscript lies in the range defined the -- bounding pair. inRange :: Ix a => (a, a) -> a -> Bool -- | The size of the subrange defined by a bounding pair. rangeSize :: Ix a => (a, a) -> Int -- | The class Typeable allows a concrete representation of a type -- to be calculated. class Typeable (a :: k) -- | Monads having fixed points with a 'knot-tying' semantics. Instances of -- MonadFix should satisfy the following laws: -- -- -- -- This class is used in the translation of the recursive do -- notation supported by GHC and Hugs. class Monad m => MonadFix (m :: Type -> Type) -- | The fixed point of a monadic computation. mfix f -- executes the action f only once, with the eventual output fed -- back as the input. Hence f should not be strict, for then -- mfix f would diverge. mfix :: MonadFix m => (a -> m a) -> m a -- | When a value is bound in do-notation, the pattern on the left -- hand side of <- might not match. In this case, this class -- provides a function to recover. -- -- A Monad without a MonadFail instance may only be used in -- conjunction with pattern that always match, such as newtypes, tuples, -- data types with only a single data constructor, and irrefutable -- patterns (~pat). -- -- Instances of MonadFail should satisfy the following law: -- fail s should be a left zero for >>=, -- --
--   fail s >>= f  =  fail s
--   
-- -- If your Monad is also MonadPlus, a popular definition is -- --
--   fail _ = mzero
--   
class Monad m => MonadFail (m :: Type -> Type) fail :: MonadFail m => String -> m a -- | Class for string-like datastructures; used by the overloaded string -- extension (-XOverloadedStrings in GHC). class IsString a fromString :: IsString a => String -> a -- | A functor with application, providing operations to -- -- -- -- A minimal complete definition must include implementations of -- pure and of either <*> or liftA2. If it -- defines both, then they must behave the same as their default -- definitions: -- --
--   (<*>) = liftA2 id
--   
-- --
--   liftA2 f x y = f <$> x <*> y
--   
-- -- Further, any definition must satisfy the following: -- -- -- -- The other methods have the following default definitions, which may be -- overridden with equivalent specialized implementations: -- -- -- -- As a consequence of these laws, the Functor instance for -- f will satisfy -- -- -- -- It may be useful to note that supposing -- --
--   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 :: Type -> Type) -- | Lift a value. pure :: Applicative f => a -> f a -- | Sequential application. -- -- A few functors support an implementation of <*> that is -- more efficient than the default one. -- --

Example

-- -- Used in combination with (<$>), -- (<*>) can be used to build a record. -- --
--   >>> data MyState = MyState {arg1 :: Foo, arg2 :: Bar, arg3 :: Baz}
--   
-- --
--   >>> produceFoo :: Applicative f => f Foo
--   
-- --
--   >>> produceBar :: Applicative f => f Bar
--   
--   >>> produceBaz :: Applicative f => f Baz
--   
-- --
--   >>> mkState :: Applicative f => f MyState
--   
--   >>> mkState = MyState <$> produceFoo <*> produceBar <*> produceBaz
--   
(<*>) :: Applicative f => f (a -> b) -> f a -> f b -- | Lift a binary function to actions. -- -- Some functors support an implementation of liftA2 that is more -- efficient than the default one. In particular, if fmap is an -- expensive operation, it is likely better to use liftA2 than to -- fmap over the structure and then use <*>. -- -- This became a typeclass method in 4.10.0.0. Prior to that, it was a -- function defined in terms of <*> and fmap. -- --

Example

-- --
--   >>> liftA2 (,) (Just 3) (Just 5)
--   Just (3,5)
--   
liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c -- | Sequence actions, discarding the value of the first argument. -- --

Examples

-- -- If used in conjunction with the Applicative instance for Maybe, -- you can chain Maybe computations, with a possible "early return" in -- case of Nothing. -- --
--   >>> Just 2 *> Just 3
--   Just 3
--   
-- --
--   >>> Nothing *> Just 3
--   Nothing
--   
-- -- Of course a more interesting use case would be to have effectful -- computations instead of just returning pure values. -- --
--   >>> import Data.Char
--   
--   >>> import Text.ParserCombinators.ReadP
--   
--   >>> let p = string "my name is " *> munch1 isAlpha <* eof
--   
--   >>> readP_to_S p "my name is Simon"
--   [("Simon","")]
--   
(*>) :: Applicative f => f a -> f b -> f b -- | Sequence actions, discarding the value of the second argument. (<*) :: Applicative f => f a -> f b -> f a infixl 4 <* infixl 4 *> infixl 4 <*> -- | The Foldable class represents data structures that can be reduced to a -- summary value one element at a time. Strict left-associative folds are -- a good fit for space-efficient reduction, while lazy right-associative -- folds are a good fit for corecursive iteration, or for folds that -- short-circuit after processing an initial subsequence of the -- structure's elements. -- -- Instances can be derived automatically by enabling the -- DeriveFoldable extension. For example, a derived instance for -- a binary tree might be: -- --
--   {-# LANGUAGE DeriveFoldable #-}
--   data Tree a = Empty
--               | Leaf a
--               | Node (Tree a) a (Tree a)
--       deriving Foldable
--   
-- -- A more detailed description can be found in the Overview -- section of Data.Foldable#overview. -- -- For the class laws see the Laws section of -- Data.Foldable#laws. class Foldable (t :: TYPE LiftedRep -> Type) -- | Given a structure with elements whose type is a Monoid, combine -- them via the monoid's (<>) operator. This fold -- is right-associative and lazy in the accumulator. When you need a -- strict left-associative fold, use foldMap' instead, with -- id as the map. -- --

Examples

-- -- Basic usage: -- --
--   >>> fold [[1, 2, 3], [4, 5], [6], []]
--   [1,2,3,4,5,6]
--   
-- --
--   >>> fold $ Node (Leaf (Sum 1)) (Sum 3) (Leaf (Sum 5))
--   Sum {getSum = 9}
--   
-- -- Folds of unbounded structures do not terminate when the monoid's -- (<>) operator is strict: -- --
--   >>> fold (repeat Nothing)
--   * Hangs forever *
--   
-- -- Lazy corecursive folds of unbounded structures are fine: -- --
--   >>> take 12 $ fold $ map (\i -> [i..i+2]) [0..]
--   [0,1,2,1,2,3,2,3,4,3,4,5]
--   
--   >>> sum $ take 4000000 $ fold $ map (\i -> [i..i+2]) [0..]
--   2666668666666
--   
fold :: (Foldable t, Monoid m) => t m -> m -- | Map each element of the structure into a monoid, and combine the -- results with (<>). This fold is -- right-associative and lazy in the accumulator. For strict -- left-associative folds consider foldMap' instead. -- --

Examples

-- -- Basic usage: -- --
--   >>> foldMap Sum [1, 3, 5]
--   Sum {getSum = 9}
--   
-- --
--   >>> foldMap Product [1, 3, 5]
--   Product {getProduct = 15}
--   
-- --
--   >>> foldMap (replicate 3) [1, 2, 3]
--   [1,1,1,2,2,2,3,3,3]
--   
-- -- When a Monoid's (<>) is lazy in its second -- argument, foldMap can return a result even from an unbounded -- structure. For example, lazy accumulation enables -- Data.ByteString.Builder to efficiently serialise large data -- structures and produce the output incrementally: -- --
--   >>> import qualified Data.ByteString.Lazy as L
--   
--   >>> import qualified Data.ByteString.Builder as B
--   
--   >>> let bld :: Int -> B.Builder; bld i = B.intDec i <> B.word8 0x20
--   
--   >>> let lbs = B.toLazyByteString $ foldMap bld [0..]
--   
--   >>> L.take 64 lbs
--   "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24"
--   
foldMap :: (Foldable t, Monoid m) => (a -> m) -> t a -> m -- | A left-associative variant of foldMap that is strict in the -- accumulator. Use this method for strict reduction when partial results -- are merged via (<>). -- --

Examples

-- -- Define a Monoid over finite bit strings under xor. Use -- it to strictly compute the xor of a list of Int -- values. -- --
--   >>> :set -XGeneralizedNewtypeDeriving
--   
--   >>> import Data.Bits (Bits, FiniteBits, xor, zeroBits)
--   
--   >>> import Data.Foldable (foldMap')
--   
--   >>> import Numeric (showHex)
--   
--   >>> 
--   
--   >>> newtype X a = X a deriving (Eq, Bounded, Enum, Bits, FiniteBits)
--   
--   >>> instance Bits a => Semigroup (X a) where X a <> X b = X (a `xor` b)
--   
--   >>> instance Bits a => Monoid    (X a) where mempty     = X zeroBits
--   
--   >>> 
--   
--   >>> let bits :: [Int]; bits = [0xcafe, 0xfeed, 0xdeaf, 0xbeef, 0x5411]
--   
--   >>> (\ (X a) -> showString "0x" . showHex a $ "") $ foldMap' X bits
--   "0x42"
--   
foldMap' :: (Foldable t, Monoid m) => (a -> m) -> t a -> m -- | Right-associative fold of a structure, lazy in the accumulator. -- -- 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, given an -- operator lazy in its right argument, foldr can produce a -- terminating expression from an unbounded list. -- -- For a general Foldable structure this should be semantically -- identical to, -- --
--   foldr f z = foldr f z . toList
--   
-- --

Examples

-- -- Basic usage: -- --
--   >>> foldr (||) False [False, True, False]
--   True
--   
-- --
--   >>> foldr (||) False []
--   False
--   
-- --
--   >>> foldr (\c acc -> acc ++ [c]) "foo" ['a', 'b', 'c', 'd']
--   "foodcba"
--   
-- --
Infinite structures
-- -- ⚠️ Applying foldr to infinite structures usually doesn't -- terminate. -- -- It may still terminate under one of the following conditions: -- -- -- --
Short-circuiting
-- -- (||) short-circuits on True values, so the -- following terminates because there is a True value finitely far -- from the left side: -- --
--   >>> foldr (||) False (True : repeat False)
--   True
--   
-- -- But the following doesn't terminate: -- --
--   >>> foldr (||) False (repeat False ++ [True])
--   * Hangs forever *
--   
-- --
Laziness in the second argument
-- -- Applying foldr to infinite structures terminates when the -- operator is lazy in its second argument (the initial accumulator is -- never used in this case, and so could be left undefined, but -- [] is more clear): -- --
--   >>> take 5 $ foldr (\i acc -> i : fmap (+3) acc) [] (repeat 1)
--   [1,4,7,10,13]
--   
foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b -- | Right-associative fold of a structure, strict in the accumulator. This -- is rarely what you want. foldr' :: Foldable t => (a -> b -> b) -> b -> t a -> b -- | Left-associative fold of a structure, lazy in the accumulator. This is -- rarely what you want, but can work well for structures with efficient -- right-to-left sequencing and an operator that is lazy in its left -- argument. -- -- 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. Like all left-associative folds, -- foldl will diverge if given an infinite list. -- -- If you want an efficient strict left-fold, you probably want to use -- foldl' instead of foldl. The reason for this is that the -- 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 <math> -- 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
--   
-- --

Examples

-- -- The first example is a strict fold, which in practice is best -- performed with foldl'. -- --
--   >>> foldl (+) 42 [1,2,3,4]
--   52
--   
-- -- Though the result below is lazy, the input is reversed before -- prepending it to the initial accumulator, so corecursion begins only -- after traversing the entire input string. -- --
--   >>> foldl (\acc c -> c : acc) "abcd" "efgh"
--   "hgfeabcd"
--   
-- -- A left fold of a structure that is infinite on the right cannot -- terminate, even when for any finite input the fold just returns the -- initial accumulator: -- --
--   >>> foldl (\a _ -> a) 0 $ repeat 1
--   * Hangs forever *
--   
-- -- WARNING: When it comes to lists, you always want to use either -- foldl' or foldr instead. foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b -- | Left-associative fold of a structure but with strict application of -- the operator. -- -- This ensures that each step of the fold is forced to Weak Head Normal -- Form before being applied, avoiding the collection of thunks that -- would otherwise occur. This is often what you want to strictly reduce -- a finite structure to a single strict result (e.g. sum). -- -- 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 foldr that has no base case, and thus may only be -- applied to non-empty structures. -- -- This function is non-total and will raise a runtime exception if the -- structure happens to be empty. -- --

Examples

-- -- Basic usage: -- --
--   >>> foldr1 (+) [1..4]
--   10
--   
-- --
--   >>> foldr1 (+) []
--   Exception: Prelude.foldr1: empty list
--   
-- --
--   >>> foldr1 (+) Nothing
--   *** Exception: foldr1: empty structure
--   
-- --
--   >>> foldr1 (-) [1..4]
--   -2
--   
-- --
--   >>> foldr1 (&&) [True, False, True, True]
--   False
--   
-- --
--   >>> foldr1 (||) [False, False, True, True]
--   True
--   
-- --
--   >>> foldr1 (+) [1..]
--   * Hangs forever *
--   
foldr1 :: Foldable t => (a -> a -> a) -> t a -> a -- | A variant of foldl that has no base case, and thus may only be -- applied to non-empty structures. -- -- This function is non-total and will raise a runtime exception if the -- structure happens to be empty. -- --
--   foldl1 f = foldl1 f . toList
--   
-- --

Examples

-- -- Basic usage: -- --
--   >>> foldl1 (+) [1..4]
--   10
--   
-- --
--   >>> foldl1 (+) []
--   *** Exception: Prelude.foldl1: empty list
--   
-- --
--   >>> foldl1 (+) Nothing
--   *** Exception: foldl1: empty structure
--   
-- --
--   >>> foldl1 (-) [1..4]
--   -8
--   
-- --
--   >>> foldl1 (&&) [True, False, True, True]
--   False
--   
-- --
--   >>> foldl1 (||) [False, False, True, True]
--   True
--   
-- --
--   >>> foldl1 (+) [1..]
--   * Hangs forever *
--   
foldl1 :: Foldable t => (a -> a -> a) -> t a -> a -- | Test whether the structure is empty. The default implementation is -- Left-associative and lazy in both the initial element and the -- accumulator. Thus optimised for structures where the first element can -- be accessed in constant time. Structures where this is not the case -- should have a non-default implementation. -- --

Examples

-- -- Basic usage: -- --
--   >>> null []
--   True
--   
-- --
--   >>> null [1]
--   False
--   
-- -- null is expected to terminate even for infinite structures. The -- default implementation terminates provided the structure is bounded on -- the left (there is a leftmost element). -- --
--   >>> null [1..]
--   False
--   
null :: Foldable t => t a -> Bool -- | Returns the size/length of a finite structure as an Int. The -- default implementation just counts elements starting with the -- leftmost. Instances for structures that can compute the element count -- faster than via element-by-element counting, should provide a -- specialised implementation. -- --

Examples

-- -- Basic usage: -- --
--   >>> length []
--   0
--   
-- --
--   >>> length ['a', 'b', 'c']
--   3
--   
--   >>> length [1..]
--   * Hangs forever *
--   
length :: Foldable t => t a -> Int -- | Does the element occur in the structure? -- -- Note: elem is often used in infix form. -- --

Examples

-- -- Basic usage: -- --
--   >>> 3 `elem` []
--   False
--   
-- --
--   >>> 3 `elem` [1,2]
--   False
--   
-- --
--   >>> 3 `elem` [1,2,3,4,5]
--   True
--   
-- -- For infinite structures, the default implementation of elem -- terminates if the sought-after value exists at a finite distance from -- the left side of the structure: -- --
--   >>> 3 `elem` [1..]
--   True
--   
-- --
--   >>> 3 `elem` ([4..] ++ [3])
--   * Hangs forever *
--   
elem :: (Foldable t, Eq a) => a -> t a -> Bool -- | The largest element of a non-empty structure. -- -- This function is non-total and will raise a runtime exception if the -- structure happens to be empty. A structure that supports random access -- and maintains its elements in order should provide a specialised -- implementation to return the maximum in faster than linear time. -- --

Examples

-- -- Basic usage: -- --
--   >>> maximum [1..10]
--   10
--   
-- --
--   >>> maximum []
--   *** Exception: Prelude.maximum: empty list
--   
-- --
--   >>> maximum Nothing
--   *** Exception: maximum: empty structure
--   
-- -- WARNING: This function is partial for possibly-empty structures like -- lists. maximum :: (Foldable t, Ord a) => t a -> a -- | The least element of a non-empty structure. -- -- This function is non-total and will raise a runtime exception if the -- structure happens to be empty. A structure that supports random access -- and maintains its elements in order should provide a specialised -- implementation to return the minimum in faster than linear time. -- --

Examples

-- -- Basic usage: -- --
--   >>> minimum [1..10]
--   1
--   
-- --
--   >>> minimum []
--   *** Exception: Prelude.minimum: empty list
--   
-- --
--   >>> minimum Nothing
--   *** Exception: minimum: empty structure
--   
-- -- WARNING: This function is partial for possibly-empty structures like -- lists. minimum :: (Foldable t, Ord a) => t a -> a -- | The sum function computes the sum of the numbers of a -- structure. -- --

Examples

-- -- Basic usage: -- --
--   >>> sum []
--   0
--   
-- --
--   >>> sum [42]
--   42
--   
-- --
--   >>> sum [1..10]
--   55
--   
-- --
--   >>> sum [4.1, 2.0, 1.7]
--   7.8
--   
-- --
--   >>> sum [1..]
--   * Hangs forever *
--   
sum :: (Foldable t, Num a) => t a -> a -- | The product function computes the product of the numbers of a -- structure. -- --

Examples

-- -- Basic usage: -- --
--   >>> product []
--   1
--   
-- --
--   >>> product [42]
--   42
--   
-- --
--   >>> product [1..10]
--   3628800
--   
-- --
--   >>> product [4.1, 2.0, 1.7]
--   13.939999999999998
--   
-- --
--   >>> product [1..]
--   * Hangs forever *
--   
product :: (Foldable t, Num a) => t a -> a infix 4 `elem` -- | Functors representing data structures that can be transformed to -- structures of the same shape by performing an -- Applicative (or, therefore, Monad) action on each -- element from left to right. -- -- A more detailed description of what same shape means, the -- various methods, how traversals are constructed, and example advanced -- use-cases can be found in the Overview section of -- Data.Traversable#overview. -- -- For the class laws see the Laws section of -- Data.Traversable#laws. class (Functor t, Foldable t) => Traversable (t :: Type -> Type) -- | 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_. -- --

Examples

-- -- Basic usage: -- -- In the first two examples we show each evaluated action mapping to the -- output structure. -- --
--   >>> traverse Just [1,2,3,4]
--   Just [1,2,3,4]
--   
-- --
--   >>> traverse id [Right 1, Right 2, Right 3, Right 4]
--   Right [1,2,3,4]
--   
-- -- In the next examples, we show that Nothing and Left -- values short circuit the created structure. -- --
--   >>> traverse (const Nothing) [1,2,3,4]
--   Nothing
--   
-- --
--   >>> traverse (\x -> if odd x then Just x else Nothing)  [1,2,3,4]
--   Nothing
--   
-- --
--   >>> traverse id [Right 1, Right 2, Right 3, Right 4, Left 0]
--   Left 0
--   
traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b) -- | Evaluate each action in the structure from left to right, and collect -- the results. For a version that ignores the results see -- sequenceA_. -- --

Examples

-- -- Basic usage: -- -- For the first two examples we show sequenceA fully evaluating a a -- structure and collecting the results. -- --
--   >>> sequenceA [Just 1, Just 2, Just 3]
--   Just [1,2,3]
--   
-- --
--   >>> sequenceA [Right 1, Right 2, Right 3]
--   Right [1,2,3]
--   
-- -- The next two example show Nothing and Just will short -- circuit the resulting structure if present in the input. For more -- context, check the Traversable instances for Either and -- Maybe. -- --
--   >>> sequenceA [Just 1, Just 2, Just 3, Nothing]
--   Nothing
--   
-- --
--   >>> sequenceA [Right 1, Right 2, Right 3, Left 4]
--   Left 4
--   
sequenceA :: (Traversable t, Applicative f) => t (f a) -> f (t 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_. -- --

Examples

-- -- mapM is literally a traverse with a type signature -- restricted to Monad. Its implementation may be more efficient -- due to additional power of Monad. 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_. -- --

Examples

-- -- Basic usage: -- -- The first two examples are instances where the input and and output of -- sequence are isomorphic. -- --
--   >>> sequence $ Right [1,2,3,4]
--   [Right 1,Right 2,Right 3,Right 4]
--   
-- --
--   >>> sequence $ [Right 1,Right 2,Right 3,Right 4]
--   Right [1,2,3,4]
--   
-- -- The following examples demonstrate short circuit behavior for -- sequence. -- --
--   >>> sequence $ Left [1,2,3,4]
--   Left [1,2,3,4]
--   
-- --
--   >>> sequence $ [Left 0, Right 1,Right 2,Right 3,Right 4]
--   Left 0
--   
sequence :: (Traversable t, Monad m) => t (m a) -> m (t a) -- | Representable types of kind *. This class is derivable in GHC -- with the DeriveGeneric flag on. -- -- A Generic instance must satisfy the following laws: -- --
--   from . toid
--   to . fromid
--   
class Generic a -- | The class of semigroups (types with an associative binary operation). -- -- Instances should satisfy the following: -- -- class Semigroup a -- | An associative operation. -- --
--   >>> [1,2,3] <> [4,5,6]
--   [1,2,3,4,5,6]
--   
(<>) :: Semigroup a => a -> a -> a -- | Reduce a non-empty list with <> -- -- The default definition should be sufficient, but this can be -- overridden for efficiency. -- --
--   >>> import Data.List.NonEmpty (NonEmpty (..))
--   
--   >>> sconcat $ "Hello" :| [" ", "Haskell", "!"]
--   "Hello Haskell!"
--   
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 <math> by picking -- stimes = stimesIdempotent or stimes = -- stimesIdempotentMonoid respectively. -- --
--   >>> stimes 4 [1]
--   [1,1,1,1]
--   
stimes :: (Semigroup a, Integral b) => b -> a -> a infixr 6 <> -- | The class of monoids (types with an associative binary operation that -- has an identity). Instances should satisfy the following: -- -- -- -- The method names refer to the monoid of lists under concatenation, but -- there are many other instances. -- -- Some types can be viewed as a monoid in more than one way, e.g. both -- addition and multiplication on numbers. In such cases we often define -- newtypes and make those instances of Monoid, e.g. -- Sum and Product. -- -- NOTE: Semigroup is a superclass of Monoid since -- base-4.11.0.0. class Semigroup a => Monoid a -- | Identity of mappend -- --
--   >>> "Hello world" <> mempty
--   "Hello world"
--   
mempty :: Monoid a => a -- | An associative operation -- -- NOTE: This method is redundant and has the default -- implementation mappend = (<>) since -- base-4.11.0.0. Should it be implemented manually, since -- mappend is a synonym for (<>), it is expected that -- the two functions are defined the same way. In a future GHC release -- mappend will be removed from Monoid. 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 ["Hello", " ", "Haskell", "!"]
--   "Hello Haskell!"
--   
mconcat :: Monoid a => [a] -> a -- | Constraint representing the fact that the field x belongs to -- the record type r and has field type a. This will be -- solved automatically, but manual instances may be provided as well. class HasField (x :: k) r a | x r -> a -- | Selector function to extract the field from the record. getField :: HasField x r a => r -> a data Bool False :: Bool True :: Bool -- | A String is a list of characters. String constants in Haskell -- are values of type String. -- -- See Data.List for operations on lists. type String = [Char] -- | The character type Char is an enumeration whose values -- represent Unicode (or equivalently ISO/IEC 10646) code points (i.e. -- characters, see http://www.unicode.org/ for details). This set -- extends the ISO 8859-1 (Latin-1) character set (the first 256 -- characters), which is itself an extension of the ASCII character set -- (the first 128 characters). A character literal in Haskell has type -- Char. -- -- To convert a Char to or from the corresponding Int value -- defined by Unicode, use toEnum and fromEnum from the -- Enum class respectively (or equivalently ord and -- chr). data Char -- | Double-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- double-precision type. data Double -- | Single-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- single-precision type. data Float -- | A fixed-precision integer type with at least the range [-2^29 .. -- 2^29-1]. The exact range for a given implementation can be -- determined by using minBound and maxBound from the -- Bounded class. data Int -- | 8-bit signed integer type data Int8 -- | 16-bit signed integer type data Int16 -- | 32-bit signed integer type data Int32 -- | 64-bit signed integer type data Int64 -- | Arbitrary precision integers. In contrast with fixed-size integral -- types such as Int, the Integer type represents the -- entire infinite range of integers. -- -- Integers are stored in a kind of sign-magnitude form, hence do not -- expect two's complement form when using bit operations. -- -- If the value is small (fit into an Int), IS constructor -- is used. Otherwise Integer and IN constructors are used -- to store a BigNat representing respectively the positive or the -- negative value magnitude. -- -- Invariant: Integer and IN are used iff value doesn't fit -- in IS data Integer -- | Natural number -- -- Invariant: numbers <= 0xffffffffffffffff use the NS -- constructor data Natural -- | 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 -- | Rational numbers, with numerator and denominator of some -- Integral type. -- -- Note that Ratio's instances inherit the deficiencies from the -- type parameter's. For example, Ratio Natural's Num -- instance has similar problems to Natural's. data Ratio a -- | 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 -- | RealWorld is deeply magical. It is primitive, but it -- is not unlifted (hence ptrArg). We never manipulate -- values of type RealWorld; it's only used in the type system, -- to parameterise State#. data RealWorld -- | A stable pointer is a reference to a Haskell expression that is -- guaranteed not to be affected by garbage collection, i.e., it will -- neither be deallocated nor will the value of the stable pointer itself -- change during garbage collection (ordinary references may be relocated -- during garbage collection). Consequently, stable pointers can be -- passed to foreign code, which can treat it as an opaque reference to a -- Haskell value. -- -- A value of type StablePtr a is a stable pointer to a Haskell -- expression of type a. data StablePtr a -- | A value of type IO a is a computation which, when -- performed, does some I/O before returning a value of type a. -- -- There is really only one way to "perform" an I/O action: bind it to -- Main.main in your program. When your program is run, the I/O -- will be performed. It isn't possible to perform I/O from an arbitrary -- function, unless that function is itself in the IO monad and -- called at some point, directly or indirectly, from Main.main. -- -- IO is a monad, so IO actions can be combined using -- either the do-notation or the >> and >>= -- operations from the Monad class. data IO a -- | A Word is an unsigned integral type, with the same size as -- Int. data Word -- | 8-bit unsigned integer type data Word8 -- | 16-bit unsigned integer type data Word16 -- | 32-bit unsigned integer type data Word32 -- | 64-bit unsigned integer type data Word64 -- | A value of type Ptr a represents a pointer to an -- object, or an array of objects, which may be marshalled to or from -- Haskell values of type a. -- -- The type a will often be an instance of class Storable -- which provides the marshalling operations. However this is not -- essential, and you can provide your own operations to access the -- pointer. For example you might write small foreign functions to get or -- set the fields of a C struct. data Ptr a -- | A value of type FunPtr a is a pointer to a function -- callable from foreign code. The type a will normally be a -- foreign type, a function type with zero or more arguments where -- -- -- -- A value of type FunPtr a may be a pointer to a foreign -- function, either returned by another foreign function or imported with -- a a static address import like -- --
--   foreign import ccall "stdlib.h &free"
--     p_free :: FunPtr (Ptr a -> IO ())
--   
-- -- or a pointer to a Haskell function created using a wrapper stub -- declared to produce a FunPtr of the correct type. For example: -- --
--   type Compare = Int -> Int -> Bool
--   foreign import ccall "wrapper"
--     mkCompare :: Compare -> IO (FunPtr Compare)
--   
-- -- Calls to wrapper stubs like mkCompare allocate storage, which -- should be released with freeHaskellFunPtr when no longer -- required. -- -- To convert FunPtr values to corresponding Haskell functions, -- one can define a dynamic stub for the specific foreign type, -- e.g. -- --
--   type IntFunction = CInt -> IO ()
--   foreign import ccall "dynamic"
--     mkFun :: FunPtr IntFunction -> IntFunction
--   
data FunPtr a -- | The Either type represents values with two possibilities: a -- value of type Either a b is either Left -- a or Right b. -- -- The Either type is sometimes used to represent a value which is -- either correct or an error; by convention, the Left constructor -- is used to hold an error value and the Right constructor is -- used to hold a correct value (mnemonic: "right" also means "correct"). -- --

Examples

-- -- The type Either String Int is the type -- of values which can be either a String or an Int. The -- Left constructor can be used only on Strings, and the -- Right constructor can be used only on Ints: -- --
--   >>> 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 -- | Non-empty (and non-strict) list type. data NonEmpty a (:|) :: a -> [a] -> NonEmpty a infixr 5 :| -- | Coercible is a two-parameter class that has instances for -- types a and b if the compiler can infer that they -- have the same representation. This class does not have regular -- instances; instead they are created on-the-fly during type-checking. -- Trying to manually declare an instance of Coercible is an -- error. -- -- Nevertheless one can pretend that the following three kinds of -- instances exist. First, as a trivial base-case: -- --
--   instance Coercible a a
--   
-- -- Furthermore, for every type constructor there is an instance that -- allows to coerce under the type constructor. For example, let -- D be a prototypical type constructor (data or -- newtype) with three type arguments, which have roles -- nominal, representational resp. phantom. -- Then there is an instance of the form -- --
--   instance Coercible b b' => Coercible (D a b c) (D a b' c')
--   
-- -- Note that the nominal type arguments are equal, the -- representational type arguments can differ, but need to have -- a Coercible instance themself, and the phantom type -- arguments can be changed arbitrarily. -- -- The third kind of instance exists for every newtype NT = MkNT -- T and comes in two variants, namely -- --
--   instance Coercible a T => Coercible a NT
--   
-- --
--   instance Coercible T b => Coercible NT b
--   
-- -- This instance is only usable if the constructor MkNT is in -- scope. -- -- If, as a library author of a type constructor like Set a, you -- want to prevent a user of your module to write coerce :: Set T -- -> Set NT, you need to set the role of Set's type -- parameter to nominal, by writing -- --
--   type role Set nominal
--   
-- -- For more details about this feature, please refer to Safe -- Coercions by Joachim Breitner, Richard A. Eisenberg, Simon Peyton -- Jones and Stephanie Weirich. class a ~R# b => Coercible (a :: k) (b :: k) -- | This type is treated magically within GHC. Any pattern match of the -- form case unsafeEqualityProof of UnsafeRefl -> body gets -- transformed just into body. This is ill-typed, but the -- transformation takes place after type-checking is complete. It is used -- to implement unsafeCoerce. You probably don't want to use -- UnsafeRefl in an expression, but you might conceivably want to -- pattern-match on it. Use unsafeEqualityProof to create one of -- these. data UnsafeEquality (a :: k) (b :: k) [UnsafeRefl] :: forall {k} (a :: k). UnsafeEquality a a data TyCon -- | Promote a function to a monad. liftM :: Monad m => (a1 -> r) -> m a1 -> m r -- | Dual function arrows. newtype Op a b Op :: (b -> a) -> Op a b [getOp] :: Op a b -> b -> a -- | 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. -- --

Examples

-- -- We create two values of type Either String -- Int, one using the Left constructor and another -- using the Right constructor. Then we apply "either" the -- length function (if we have a String) or the "times-two" -- function (if we have an Int): -- --
--   >>> 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 -- | The class of contravariant functors. -- -- Whereas in Haskell, one can think of a Functor as containing or -- producing values, a contravariant functor is a functor that can be -- thought of as consuming values. -- -- As an example, consider the type of predicate functions a -> -- Bool. One such predicate might be negative x = x < 0, -- which classifies integers as to whether they are negative. However, -- given this predicate, we can re-use it in other situations, providing -- we have a way to map values to integers. For instance, we can -- use the negative predicate on a person's bank balance to work -- out if they are currently overdrawn: -- --
--   newtype Predicate a = Predicate { getPredicate :: a -> Bool }
--   
--   instance Contravariant Predicate where
--     contramap :: (a' -> a) -> (Predicate a -> Predicate a')
--     contramap f (Predicate p) = Predicate (p . f)
--                                            |   `- First, map the input...
--                                            `----- then apply the predicate.
--   
--   overdrawn :: Predicate Person
--   overdrawn = contramap personBankBalance negative
--   
-- -- Any instance should be subject to the following laws: -- -- -- -- Note, that the second law follows from the free theorem of the type of -- contramap and the first law, so you need only check that the -- former condition holds. class Contravariant (f :: Type -> Type) contramap :: Contravariant f => (a' -> a) -> f a -> f a' -- | Replace all locations in the output with the same value. The default -- definition is contramap . const, but this may -- be overridden with a more efficient version. (>$) :: Contravariant f => b -> f b -> f a infixl 4 >$ -- | See examples in Control.Monad.Reader. Note, the partially -- applied function type (->) r is a simple reader monad. See -- the instance declaration below. class Monad m => MonadReader r (m :: Type -> Type) | m -> r -- | Retrieves the monad environment. ask :: MonadReader r m => m r -- | Executes a computation in a modified environment. local :: MonadReader r m => (r -> r) -> m a -> m a -- | Retrieves a function of the current environment. reader :: MonadReader r m => (r -> a) -> m a -- | Minimal definition is either both of get and put or -- just state class Monad m => MonadState s (m :: Type -> Type) | m -> s -- | Return the state from the internals of the monad. get :: MonadState s m => m s -- | Replace the state inside the monad. put :: MonadState s m => s -> m () -- | Embed a simple state action into the monad. state :: MonadState s m => (s -> (a, s)) -> m a -- | 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 -- | Haskell defines operations to read and write characters from and to -- files, represented by values of type Handle. Each value of -- this type is a handle: a record used by the Haskell run-time -- system to manage I/O with file system objects. A handle has at -- least the following properties: -- -- -- -- Most handles will also have a current I/O position indicating where -- the next input or output operation will occur. A handle is -- readable if it manages only input or both input and output; -- likewise, it is writable if it manages only output or both -- input and output. A handle is open when first allocated. Once -- it is closed it can no longer be used for either input or output, -- though an implementation cannot re-use its storage while references -- remain to it. Handles are in the Show and Eq classes. -- The string produced by showing a handle is system dependent; it should -- include enough information to identify the handle for debugging. A -- handle is equal according to == only to itself; no attempt is -- made to compare the internal state of different handles for equality. data Handle -- | The strict ST monad. The ST monad allows for destructive -- updates, but is escapable (unlike IO). A computation of type -- ST s a returns a value of type a, and execute -- in "thread" s. The s parameter is either -- -- -- -- It serves to keep the internal states of different invocations of -- runST separate from each other and from invocations of -- stToIO. -- -- The >>= and >> operations are strict in the -- state (though not in values stored in the state). For example, -- --
--   runST (writeSTRef _|_ v >>= f) = _|_
--   
data ST s a newtype Predicate a Predicate :: (a -> Bool) -> Predicate a [getPredicate] :: Predicate a -> a -> Bool -- | This data type represents an equivalence relation. -- -- Equivalence relations are expected to satisfy three laws: -- -- -- -- The types alone do not enforce these laws, so you'll have to check -- them yourself. newtype Equivalence a Equivalence :: (a -> a -> Bool) -> Equivalence a [getEquivalence] :: Equivalence a -> a -> a -> Bool -- | Defines a total ordering on a type as per compare. -- -- This condition is not checked by the types. You must ensure that the -- supplied values are valid total orderings yourself. newtype Comparison a Comparison :: (a -> a -> Ordering) -> Comparison a [getComparison] :: Comparison a -> a -> a -> Ordering -- | If f is both Functor and Contravariant then by -- the time you factor in the laws of each of those classes, it can't -- actually use its argument in any meaningful capacity. -- -- This method is surprisingly useful. Where both instances exist and are -- lawful we have the following laws: -- --
--   fmap      f ≡ phantom
--   contramap f ≡ phantom
--   
phantom :: (Functor f, Contravariant f) => f a -> f b -- | Check for equivalence with ==. -- -- Note: The instances for Double and Float violate -- reflexivity for NaN. defaultEquivalence :: Eq a => Equivalence a -- | Compare using compare. defaultComparison :: Ord a => Comparison a comparisonEquivalence :: Comparison a -> Equivalence a -- | This is an infix alias for contramap. (>$<) :: Contravariant f => (a -> b) -> f b -> f a infixl 4 >$< -- | This is an infix version of contramap with the arguments -- flipped. (>$$<) :: Contravariant f => f b -> (a -> b) -> f a infixl 4 >$$< -- | This is >$ with its arguments flipped. ($<) :: Contravariant f => f b -> b -> f a infixl 4 $< -- | Right-to-left composition of functors. The composition of applicative -- functors is always applicative, but the composition of monads is not -- always a monad. newtype Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) Compose :: f (g a) -> Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) [getCompose] :: Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) -> f (g a) infixr 9 `Compose` infixr 9 `Compose` -- | Lifting of the Show class to binary type constructors. class Show2 (f :: TYPE LiftedRep -> TYPE LiftedRep -> TYPE LiftedRep) -- | showsPrec function for an application of the type constructor -- based on showsPrec and showList functions for the -- argument types. liftShowsPrec2 :: Show2 f => (Int -> a -> ShowS) -> ([a] -> ShowS) -> (Int -> b -> ShowS) -> ([b] -> ShowS) -> Int -> f a b -> ShowS -- | showList function for an application of the type constructor -- based on showsPrec and showList functions for the -- argument types. The default implementation using standard list syntax -- is correct for most types. liftShowList2 :: Show2 f => (Int -> a -> ShowS) -> ([a] -> ShowS) -> (Int -> b -> ShowS) -> ([b] -> ShowS) -> [f a b] -> ShowS -- | Lifting of the Show class to unary type constructors. class Show1 (f :: TYPE LiftedRep -> TYPE LiftedRep) -- | showsPrec function for an application of the type constructor -- based on showsPrec and showList functions for the -- argument type. liftShowsPrec :: Show1 f => (Int -> a -> ShowS) -> ([a] -> ShowS) -> Int -> f a -> ShowS -- | showList function for an application of the type constructor -- based on showsPrec and showList functions for the -- argument type. The default implementation using standard list syntax -- is correct for most types. liftShowList :: Show1 f => (Int -> a -> ShowS) -> ([a] -> ShowS) -> [f a] -> ShowS -- | Lifting of the Read class to binary type constructors. -- -- Both liftReadsPrec2 and liftReadPrec2 exist to match the -- interface provided in the Read type class, but it is -- recommended to implement Read2 instances using -- liftReadPrec2 as opposed to liftReadsPrec2, since the -- former is more efficient than the latter. For example: -- --
--   instance Read2 T where
--     liftReadPrec2     = ...
--     liftReadListPrec2 = liftReadListPrec2Default
--   
-- -- For more information, refer to the documentation for the Read -- class. class Read2 (f :: Type -> Type -> Type) -- | readsPrec function for an application of the type constructor -- based on readsPrec and readList functions for the -- argument types. liftReadsPrec2 :: Read2 f => (Int -> ReadS a) -> ReadS [a] -> (Int -> ReadS b) -> ReadS [b] -> Int -> ReadS (f a b) -- | readList function for an application of the type constructor -- based on readsPrec and readList functions for the -- argument types. The default implementation using standard list syntax -- is correct for most types. liftReadList2 :: Read2 f => (Int -> ReadS a) -> ReadS [a] -> (Int -> ReadS b) -> ReadS [b] -> ReadS [f a b] -- | readPrec function for an application of the type constructor -- based on readPrec and readListPrec functions for the -- argument types. liftReadPrec2 :: Read2 f => ReadPrec a -> ReadPrec [a] -> ReadPrec b -> ReadPrec [b] -> ReadPrec (f a b) -- | readListPrec function for an application of the type -- constructor based on readPrec and readListPrec functions -- for the argument types. -- -- The default definition uses liftReadList2. Instances that -- define liftReadPrec2 should also define -- liftReadListPrec2 as liftReadListPrec2Default. liftReadListPrec2 :: Read2 f => ReadPrec a -> ReadPrec [a] -> ReadPrec b -> ReadPrec [b] -> ReadPrec [f a b] -- | Lifting of the Read class to unary type constructors. -- -- Both liftReadsPrec and liftReadPrec exist to match the -- interface provided in the Read type class, but it is -- recommended to implement Read1 instances using -- liftReadPrec as opposed to liftReadsPrec, since the -- former is more efficient than the latter. For example: -- --
--   instance Read1 T where
--     liftReadPrec     = ...
--     liftReadListPrec = liftReadListPrecDefault
--   
-- -- For more information, refer to the documentation for the Read -- class. class Read1 (f :: Type -> Type) -- | readsPrec function for an application of the type constructor -- based on readsPrec and readList functions for the -- argument type. liftReadsPrec :: Read1 f => (Int -> ReadS a) -> ReadS [a] -> Int -> ReadS (f a) -- | readList function for an application of the type constructor -- based on readsPrec and readList functions for the -- argument type. The default implementation using standard list syntax -- is correct for most types. liftReadList :: Read1 f => (Int -> ReadS a) -> ReadS [a] -> ReadS [f a] -- | readPrec function for an application of the type constructor -- based on readPrec and readListPrec functions for the -- argument type. liftReadPrec :: Read1 f => ReadPrec a -> ReadPrec [a] -> ReadPrec (f a) -- | readListPrec function for an application of the type -- constructor based on readPrec and readListPrec functions -- for the argument type. -- -- The default definition uses liftReadList. Instances that define -- liftReadPrec should also define liftReadListPrec as -- liftReadListPrecDefault. liftReadListPrec :: Read1 f => ReadPrec a -> ReadPrec [a] -> ReadPrec [f a] -- | Lifting of the Ord class to binary type constructors. class Eq2 f => Ord2 (f :: Type -> Type -> Type) -- | Lift compare functions through the type constructor. -- -- The function will usually be applied to comparison functions, but the -- more general type ensures that the implementation uses them to compare -- elements of the first container with elements of the second. liftCompare2 :: Ord2 f => (a -> b -> Ordering) -> (c -> d -> Ordering) -> f a c -> f b d -> Ordering -- | Lifting of the Ord class to unary type constructors. class Eq1 f => Ord1 (f :: Type -> Type) -- | Lift a compare function through the type constructor. -- -- The function will usually be applied to a comparison function, but the -- more general type ensures that the implementation uses it to compare -- elements of the first container with elements of the second. liftCompare :: Ord1 f => (a -> b -> Ordering) -> f a -> f b -> Ordering -- | Lifting of the Eq class to binary type constructors. class Eq2 (f :: Type -> Type -> Type) -- | Lift equality tests through the type constructor. -- -- The function will usually be applied to equality functions, but the -- more general type ensures that the implementation uses them to compare -- elements of the first container with elements of the second. liftEq2 :: Eq2 f => (a -> b -> Bool) -> (c -> d -> Bool) -> f a c -> f b d -> Bool -- | Lifting of the Eq class to unary type constructors. class Eq1 (f :: Type -> Type) -- | Lift an equality test through the type constructor. -- -- The function will usually be applied to an equality function, but the -- more general type ensures that the implementation uses it to compare -- elements of the first container with elements of the second. liftEq :: Eq1 f => (a -> b -> Bool) -> f a -> f b -> Bool -- | showsUnaryWith sp n d x produces the string -- representation of a unary data constructor with name n and -- argument x, in precedence context d. showsUnaryWith :: (Int -> a -> ShowS) -> String -> Int -> a -> ShowS -- | showsUnary1 n d x produces the string representation -- of a unary data constructor with name n and argument -- x, in precedence context d. showsUnary1 :: (Show1 f, Show a) => String -> Int -> f a -> ShowS -- | showsUnary n d x produces the string representation of -- a unary data constructor with name n and argument x, -- in precedence context d. showsUnary :: Show a => String -> Int -> a -> ShowS -- | Lift the standard showsPrec function through the type -- constructor. showsPrec2 :: (Show2 f, Show a, Show b) => Int -> f a b -> ShowS -- | Lift the standard showsPrec and showList functions -- through the type constructor. showsPrec1 :: (Show1 f, Show a) => Int -> f a -> ShowS -- | showsBinaryWith sp1 sp2 n d x y produces the string -- representation of a binary data constructor with name n and -- arguments x and y, in precedence context d. showsBinaryWith :: (Int -> a -> ShowS) -> (Int -> b -> ShowS) -> String -> Int -> a -> b -> ShowS -- | showsBinary1 n d x y produces the string -- representation of a binary data constructor with name n and -- arguments x and y, in precedence context d. showsBinary1 :: (Show1 f, Show1 g, Show a) => String -> Int -> f a -> g a -> ShowS -- | readsUnaryWith rp n c n' matches the name of a unary -- data constructor and then parses its argument using rp. readsUnaryWith :: (Int -> ReadS a) -> String -> (a -> t) -> String -> ReadS t -- | readsUnary1 n c n' matches the name of a unary data -- constructor and then parses its argument using readsPrec1. readsUnary1 :: (Read1 f, Read a) => String -> (f a -> t) -> String -> ReadS t -- | readsUnary n c n' matches the name of a unary data -- constructor and then parses its argument using readsPrec. readsUnary :: Read a => String -> (a -> t) -> String -> ReadS t -- | Lift the standard readsPrec function through the type -- constructor. readsPrec2 :: (Read2 f, Read a, Read b) => Int -> ReadS (f a b) -- | Lift the standard readsPrec and readList functions -- through the type constructor. readsPrec1 :: (Read1 f, Read a) => Int -> ReadS (f a) -- | readsData p d is a parser for datatypes where each -- alternative begins with a data constructor. It parses the constructor -- and passes it to p. Parsers for various constructors can be -- constructed with readsUnary, readsUnary1 and -- readsBinary1, and combined with mappend from the -- Monoid class. readsData :: (String -> ReadS a) -> Int -> ReadS a -- | readsBinaryWith rp1 rp2 n c n' matches the name of a -- binary data constructor and then parses its arguments using -- rp1 and rp2 respectively. readsBinaryWith :: (Int -> ReadS a) -> (Int -> ReadS b) -> String -> (a -> b -> t) -> String -> ReadS t -- | readsBinary1 n c n' matches the name of a binary data -- constructor and then parses its arguments using readsPrec1. readsBinary1 :: (Read1 f, Read1 g, Read a) => String -> (f a -> g a -> t) -> String -> ReadS t -- | readUnaryWith rp n c' matches the name of a unary data -- constructor and then parses its argument using rp. readUnaryWith :: ReadPrec a -> String -> (a -> t) -> ReadPrec t -- | Lift the standard readPrec function through the type -- constructor. readPrec2 :: (Read2 f, Read a, Read b) => ReadPrec (f a b) -- | Lift the standard readPrec and readListPrec functions -- through the type constructor. readPrec1 :: (Read1 f, Read a) => ReadPrec (f a) -- | readData p is a parser for datatypes where each -- alternative begins with a data constructor. It parses the constructor -- and passes it to p. Parsers for various constructors can be -- constructed with readUnaryWith and readBinaryWith, and -- combined with (<|>) from the Alternative class. readData :: ReadPrec a -> ReadPrec a -- | readBinaryWith rp1 rp2 n c' matches the name of a -- binary data constructor and then parses its arguments using -- rp1 and rp2 respectively. readBinaryWith :: ReadPrec a -> ReadPrec b -> String -> (a -> b -> t) -> ReadPrec t -- | A possible replacement definition for the liftReadListPrec -- method, defined using liftReadPrec. liftReadListPrecDefault :: Read1 f => ReadPrec a -> ReadPrec [a] -> ReadPrec [f a] -- | A possible replacement definition for the liftReadListPrec2 -- method, defined using liftReadPrec2. liftReadListPrec2Default :: Read2 f => ReadPrec a -> ReadPrec [a] -> ReadPrec b -> ReadPrec [b] -> ReadPrec [f a b] -- | A possible replacement definition for the liftReadList method. -- This is only needed for Read1 instances where -- liftReadListPrec isn't defined as -- liftReadListPrecDefault. liftReadListDefault :: Read1 f => (Int -> ReadS a) -> ReadS [a] -> ReadS [f a] -- | A possible replacement definition for the liftReadList2 method. -- This is only needed for Read2 instances where -- liftReadListPrec2 isn't defined as -- liftReadListPrec2Default. liftReadList2Default :: Read2 f => (Int -> ReadS a) -> ReadS [a] -> (Int -> ReadS b) -> ReadS [b] -> ReadS [f a b] -- | Lift the standard (==) function through the type -- constructor. eq2 :: (Eq2 f, Eq a, Eq b) => f a b -> f a b -> Bool -- | Lift the standard (==) function through the type -- constructor. eq1 :: (Eq1 f, Eq a) => f a -> f a -> Bool -- | Lift the standard compare function through the type -- constructor. compare2 :: (Ord2 f, Ord a, Ord b) => f a b -> f a b -> Ordering -- | Lift the standard compare function through the type -- constructor. compare1 :: (Ord1 f, Ord a) => f a -> f a -> Ordering -- | Complex numbers are an algebraic type. -- -- For a complex number z, abs z is a number -- with the magnitude of z, but oriented in the positive real -- direction, whereas signum z has the phase of -- z, but unit magnitude. -- -- The Foldable and Traversable instances traverse the real -- part first. -- -- Note that Complex's instances inherit the deficiencies from the -- type parameter's. For example, Complex Float's Ord -- instance has similar problems to Float's. data Complex a -- | forms a complex number from its real and imaginary rectangular -- components. (:+) :: !a -> !a -> Complex a infix 6 :+ -- | Extracts the real part of a complex number. realPart :: Complex a -> a -- | The function polar takes a complex number and returns a -- (magnitude, phase) pair in canonical form: the magnitude is -- nonnegative, and the phase in the range (-pi, -- pi]; if the magnitude is zero, then so is the phase. polar :: RealFloat a => Complex a -> (a, a) -- | The phase of a complex number, in the range (-pi, -- pi]. If the magnitude is zero, then so is the phase. phase :: RealFloat a => Complex a -> a -- | Form a complex number from polar components of magnitude and phase. mkPolar :: Floating a => a -> a -> Complex a -- | The nonnegative magnitude of a complex number. magnitude :: RealFloat a => Complex a -> a -- | Extracts the imaginary part of a complex number. imagPart :: Complex a -> a -- | The conjugate of a complex number. conjugate :: Num a => Complex a -> Complex a -- | cis t is a complex value with magnitude 1 and -- phase t (modulo 2*pi). cis :: Floating a => a -> Complex a -- | resolution of 1, this works the same as Integer type Uni = Fixed E0 -- | resolution of 10^-12 = .000000000001 type Pico = Fixed E12 -- | resolution of 10^-9 = .000000001 type Nano = Fixed E9 -- | resolution of 10^-3 = .001 type Milli = Fixed E3 -- | resolution of 10^-6 = .000001 type Micro = Fixed E6 class HasResolution (a :: k) resolution :: HasResolution a => p a -> Integer -- | The type parameter should be an instance of HasResolution. newtype Fixed (a :: k) MkFixed :: Integer -> Fixed (a :: k) data E9 data E6 data E3 data E2 data E12 data E1 data E0 -- | resolution of 10^-1 = .1 type Deci = Fixed E1 -- | resolution of 10^-2 = .01, useful for many monetary currencies type Centi = Fixed E2 -- | First arg is whether to chop off trailing zeros showFixed :: forall {k} (a :: k). HasResolution a => Bool -> Fixed a -> String -- | Generalisation of mod to any instance of Real mod' :: Real a => a -> a -> a -- | Generalisation of divMod to any instance of Real divMod' :: (Real a, Integral b) => a -> a -> (b, a) -- | Generalisation of div to any instance of Real div' :: (Real a, Integral b) => a -> a -> b -- | Uninhabited data type data Void -- | If Void is uninhabited then any Functor that holds only -- values of type Void is holding no values. It is implemented in -- terms of fmap absurd. vacuous :: Functor f => f Void -> f a -- | Since Void values logically don't exist, this witnesses the -- logical reasoning tool of "ex falso quodlibet". -- --
--   >>> let x :: Either Void Int; x = Right 5
--   
--   >>> :{
--   case x of
--       Right r -> r
--       Left l  -> absurd l
--   :}
--   5
--   
absurd :: Void -> 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 newtype Min a Min :: a -> Min a [getMin] :: Min a -> a newtype Max a Max :: a -> Max a [getMax] :: Max a -> a newtype Last a Last :: a -> Last a [getLast] :: Last a -> a newtype First a First :: a -> First a [getFirst] :: First a -> a -- |
--   >>> Min (Arg 0 ()) <> Min (Arg 1 ())
--   Min {getMin = Arg 0 ()}
--   
type ArgMin a b = Min Arg a b -- |
--   >>> Max (Arg 0 ()) <> Max (Arg 1 ())
--   Max {getMax = Arg 1 ()}
--   
type ArgMax a b = Max Arg a b -- | 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. -- --
--   >>> minimum [ Arg (x * x) x | x <- [-10 .. 10] ]
--   Arg 0 0
--   
data Arg a b Arg :: a -> b -> Arg a b -- | 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 -- | This lets you use a difference list of a Semigroup as a -- Monoid. -- --

Example:

-- --
--   >>> let hello = diff "Hello, "
--   
--   >>> appEndo hello "World!"
--   "Hello, World!"
--   
--   >>> appEndo (hello <> mempty) "World!"
--   "Hello, World!"
--   
--   >>> appEndo (mempty <> hello) "World!"
--   "Hello, World!"
--   
--   >>> let world = diff "World"
--   
--   >>> let excl = diff "!"
--   
--   >>> appEndo (hello <> (world <> excl)) mempty
--   "Hello, World!"
--   
--   >>> appEndo ((hello <> world) <> excl) mempty
--   "Hello, World!"
--   
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 -- | The Item type function returns the type of items of the -- structure l. type family Item l -- | The sortWith function sorts a list of elements using the user -- supplied function to project something out of each element sortWith :: Ord b => (a -> b) -> [a] -> [a] -- | Fixity of constructors data Fixity Prefix :: Fixity Infix :: Fixity -- | Representation of datatypes. A package of constructor representations -- with names of type and module. data DataType -- | Public representation of datatypes data DataRep AlgRep :: [Constr] -> DataRep IntRep :: DataRep FloatRep :: DataRep CharRep :: DataRep NoRep :: DataRep -- | Public representation of constructors data ConstrRep AlgConstr :: ConIndex -> ConstrRep IntConstr :: Integer -> ConstrRep FloatConstr :: Rational -> ConstrRep CharConstr :: Char -> ConstrRep -- | Representation of constructors. Note that equality on constructors -- with different types may not work -- i.e. the constructors for -- False and Nothing may compare equal. data Constr -- | Unique index for datatype constructors, counting from 1 in the order -- they are given in the program text. type ConIndex = Int -- | Gets the unqualified type constructor: drop *.*.*... before name tyconUQname :: String -> String -- | Gets the module of a type constructor: take *.*.*... before name tyconModule :: String -> String -- | Gets the string for a constructor showConstr :: Constr -> String -- | Look up a constructor by its representation repConstr :: DataType -> ConstrRep -> Constr -- | Lookup a constructor via a string readConstr :: DataType -> String -> Maybe Constr mkRealConstr :: (Real a, Show a) => DataType -> a -> Constr -- | Constructs a non-representation for a non-representable type mkNoRepType :: String -> DataType mkIntegralConstr :: (Integral a, Show a) => DataType -> a -> Constr -- | Constructs the Int type mkIntType :: String -> DataType -- | Constructs the Float type mkFloatType :: String -> DataType -- | Constructs an algebraic datatype mkDataType :: String -> [Constr] -> DataType -- | Constructs a constructor mkConstrTag :: DataType -> String -> Int -> [String] -> Fixity -> Constr -- | Constructs a constructor mkConstr :: DataType -> String -> [String] -> Fixity -> Constr -- | Constructs the Char type mkCharType :: String -> DataType -- | Makes a constructor for Char. mkCharConstr :: DataType -> Char -> Constr -- | Gets the maximum constructor index of an algebraic datatype maxConstrIndex :: DataType -> ConIndex -- | Test for a non-representable type isNorepType :: DataType -> Bool -- | Test for an algebraic type isAlgType :: DataType -> Bool -- | Gets the constructor for an index (algebraic datatypes only) indexConstr :: DataType -> ConIndex -> Constr -- | Monadic variation on fromConstrB fromConstrM :: (Monad m, Data a) => (forall d. Data d => m d) -> Constr -> m a -- | Build a term and use a generic function for subterms fromConstrB :: Data a => (forall d. Data d => d) -> Constr -> a -- | Build a term skeleton fromConstr :: Data a => Constr -> a -- | Gets the public presentation of a datatype dataTypeRep :: DataType -> DataRep -- | Gets the type constructor including the module dataTypeName :: DataType -> String -- | Gets the constructors of an algebraic datatype dataTypeConstrs :: DataType -> [Constr] -- | Gets the datatype of a constructor constrType :: Constr -> DataType -- | Gets the public presentation of constructors constrRep :: Constr -> ConstrRep -- | Gets the index of a constructor (algebraic datatypes only) constrIndex :: Constr -> ConIndex -- | Gets the fixity of a constructor constrFixity :: Constr -> Fixity -- | Gets the field labels of a constructor. The list of labels is returned -- in the same order as they were given in the original constructor -- declaration. constrFields :: Constr -> [String] -- | An exception thrown to a thread by timeout to interrupt a -- timed-out computation. data Timeout -- | Wrap an IO computation to time out and return Nothing -- in case no result is available within n microseconds -- (1/10^6 seconds). In case a result is available before the -- timeout expires, Just a is returned. A negative timeout -- interval means "wait indefinitely". When specifying long timeouts, be -- careful not to exceed maxBound :: Int. -- --
--   >>> timeout 1000000 (threadDelay 1000 *> pure "finished on time")
--   Just "finished on time"
--   
-- --
--   >>> timeout 10000 (threadDelay 100000 *> pure "finished on time")
--   Nothing
--   
-- -- The design of this combinator was guided by the objective that -- timeout n f should behave exactly the same as f as -- long as f doesn't time out. This means that f has -- the same myThreadId it would have without the timeout wrapper. -- Any exceptions f might throw cancel the timeout and propagate -- further up. It also possible for f to receive exceptions -- thrown to it by another thread. -- -- A tricky implementation detail is the question of how to abort an -- IO computation. This combinator relies on asynchronous -- exceptions internally (namely throwing the computation the -- Timeout exception). The technique works very well for -- computations executing inside of the Haskell runtime system, but it -- doesn't work at all for non-Haskell code. Foreign function calls, for -- example, cannot be timed out with this combinator simply because an -- arbitrary C function cannot receive asynchronous exceptions. When -- timeout is used to wrap an FFI call that blocks, no timeout -- event can be delivered until the FFI call returns, which pretty much -- negates the purpose of the combinator. In practice, however, this -- limitation is less severe than it may sound. Standard I/O functions -- like hGetBuf, hPutBuf, Network.Socket.accept, or -- hWaitForInput appear to be blocking, but they really don't -- because the runtime system uses scheduling mechanisms like -- select(2) to perform asynchronous I/O, so it is possible to -- interrupt standard socket I/O or file I/O using this combinator. timeout :: Int -> IO a -> IO (Maybe a) -- | Returns an STM action that can be used to wait until data can be -- written to a file descriptor. The second returned value is an IO -- action that can be used to deregister interest in the file descriptor. threadWaitWriteSTM :: Fd -> IO (STM (), IO ()) -- | Block the current thread until data can be written to the given file -- descriptor (GHC only). -- -- This will throw an IOError if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor that -- has been used with threadWaitWrite, use closeFdWith. threadWaitWrite :: Fd -> IO () -- | Returns an STM action that can be used to wait for data to read from a -- file descriptor. The second returned value is an IO action that can be -- used to deregister interest in the file descriptor. threadWaitReadSTM :: Fd -> IO (STM (), IO ()) -- | Block the current thread until data is available to read on the given -- file descriptor (GHC only). -- -- This will throw an IOError if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor that -- has been used with threadWaitRead, use closeFdWith. threadWaitRead :: Fd -> IO () -- | Run the IO computation passed as the first argument. If the -- calling thread is bound, an unbound thread is created -- temporarily using forkIO. runInBoundThread doesn't -- finish until the IO computation finishes. -- -- Use this function only in the rare case that you have actually -- observed a performance loss due to the use of bound threads. A program -- that doesn't need its main thread to be bound and makes heavy -- use of concurrency (e.g. a web server), might want to wrap its -- main action in runInUnboundThread. -- -- Note that exceptions which are thrown to the current thread are thrown -- in turn to the thread that is executing the given computation. This -- ensures there's always a way of killing the forked thread. runInUnboundThread :: IO a -> IO a -- | Run the IO computation passed as the first argument. If the -- calling thread is not bound, a bound thread is created -- temporarily. runInBoundThread doesn't finish until the -- IO computation finishes. -- -- You can wrap a series of foreign function calls that rely on -- thread-local state with runInBoundThread so that you can use -- them without knowing whether the current thread is bound. runInBoundThread :: IO a -> IO a -- | True if bound threads are supported. If -- rtsSupportsBoundThreads is False, -- isCurrentThreadBound will always return False and both -- forkOS and runInBoundThread will fail. rtsSupportsBoundThreads :: Bool -- | Returns True if the calling thread is bound, that is, if -- it is safe to use foreign libraries that rely on thread-local state -- from the calling thread. isCurrentThreadBound :: IO Bool -- | Like forkIOWithUnmask, but the child thread is a bound thread, -- as with forkOS. forkOSWithUnmask :: ((forall a. () => IO a -> IO a) -> IO ()) -> IO ThreadId -- | Like forkIO, this sparks off a new thread to run the IO -- computation passed as the first argument, and returns the -- ThreadId of the newly created thread. -- -- However, forkOS creates a bound thread, which is -- necessary if you need to call foreign (non-Haskell) libraries that -- make use of thread-local state, such as OpenGL (see -- Control.Concurrent#boundthreads). -- -- Using forkOS instead of forkIO makes no difference at -- all to the scheduling behaviour of the Haskell runtime system. It is a -- common misconception that you need to use forkOS instead of -- forkIO to avoid blocking all the Haskell threads when making a -- foreign call; this isn't the case. To allow foreign calls to be made -- without blocking all the Haskell threads (with GHC), it is only -- necessary to use the -threaded option when linking your -- program, and to make sure the foreign import is not marked -- unsafe. forkOS :: IO () -> IO ThreadId -- | Fork a thread and call the supplied function when the thread is about -- to terminate, with an exception or a returned value. The function is -- called with asynchronous exceptions masked. -- --
--   forkFinally action and_then =
--     mask $ \restore ->
--       forkIO $ try (restore action) >>= and_then
--   
-- -- This function is useful for informing the parent when a child -- terminates, for example. forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId -- | Chan is an abstract type representing an unbounded FIFO -- channel. data Chan a -- | Write an entire list of items to a Chan. writeList2Chan :: Chan a -> [a] -> IO () -- | Write a value to a Chan. writeChan :: Chan a -> a -> IO () -- | Read the next value from the Chan. Blocks when the channel is -- empty. Since the read end of a channel is an MVar, this -- operation inherits fairness guarantees of MVars (e.g. threads -- blocked in this operation are woken up in FIFO order). -- -- Throws BlockedIndefinitelyOnMVar when the channel is empty and -- no other thread holds a reference to the channel. readChan :: Chan a -> IO a -- | Build and returns a new instance of Chan. newChan :: IO (Chan a) -- | Return a lazy list representing the contents of the supplied -- Chan, much like hGetContents. getChanContents :: Chan a -> IO [a] -- | Duplicate a Chan: the duplicate channel begins empty, but data -- written to either channel from then on will be available from both. -- Hence this creates a kind of broadcast channel, where data written by -- anyone is seen by everyone else. -- -- (Note that a duplicated channel is not equal to its original. So: -- fmap (c /=) $ dupChan c returns True for all -- c.) dupChan :: Chan a -> IO (Chan a) -- | QSem is a quantity semaphore in which the resource is acquired -- and released in units of one. It provides guaranteed FIFO ordering for -- satisfying blocked waitQSem calls. -- -- The pattern -- --
--   bracket_ waitQSem signalQSem (...)
--   
-- -- is safe; it never loses a unit of the resource. data QSem -- | Wait for a unit to become available waitQSem :: QSem -> IO () -- | Signal that a unit of the QSem is available signalQSem :: QSem -> IO () -- | Build a new QSem with a supplied initial quantity. The initial -- quantity must be at least 0. newQSem :: Int -> IO QSem -- | QSemN is a quantity semaphore in which the resource is acquired -- and released in units of one. It provides guaranteed FIFO ordering for -- satisfying blocked waitQSemN calls. -- -- The pattern -- --
--   bracket_ (waitQSemN n) (signalQSemN n) (...)
--   
-- -- is safe; it never loses any of the resource. data QSemN -- | Wait for the specified quantity to become available waitQSemN :: QSemN -> Int -> IO () -- | Signal that a given quantity is now available from the QSemN. signalQSemN :: QSemN -> Int -> IO () -- | Build a new QSemN with a supplied initial quantity. The initial -- quantity must be at least 0. newQSemN :: Int -> IO QSemN -- | A bifunctor is a type constructor that takes two type arguments and is -- a functor in both arguments. That is, unlike with -- Functor, a type constructor such as Either does not need -- to be partially applied for a Bifunctor instance, and the -- methods in this class permit mapping functions over the Left -- value or the Right value, or both at the same time. -- -- Formally, the class Bifunctor represents a bifunctor from -- Hask -> Hask. -- -- Intuitively it is a bifunctor where both the first and second -- arguments are covariant. -- -- You can define a Bifunctor by either defining bimap or -- by defining both first and second. -- -- If you supply bimap, you should ensure that: -- --
--   bimap id idid
--   
-- -- If you supply first and second, ensure: -- --
--   first idid
--   second idid
--   
-- -- If you supply both, you should also ensure: -- --
--   bimap f g ≡ first f . second g
--   
-- -- These ensure by parametricity: -- --
--   bimap  (f . g) (h . i) ≡ bimap f h . bimap g i
--   first  (f . g) ≡ first  f . first  g
--   second (f . g) ≡ second f . second g
--   
class Bifunctor (p :: Type -> Type -> Type) -- | Map over both arguments at the same time. -- --
--   bimap f g ≡ first f . second g
--   
-- --

Examples

-- --
--   >>> bimap toUpper (+1) ('j', 3)
--   ('J',4)
--   
-- --
--   >>> bimap toUpper (+1) (Left 'j')
--   Left 'J'
--   
-- --
--   >>> bimap toUpper (+1) (Right 3)
--   Right 4
--   
bimap :: Bifunctor p => (a -> b) -> (c -> d) -> p a c -> p b d -- | Map covariantly over the first argument. -- --
--   first f ≡ bimap f id
--   
-- --

Examples

-- --
--   >>> first toUpper ('j', 3)
--   ('J',3)
--   
-- --
--   >>> first toUpper (Left 'j')
--   Left 'J'
--   
first :: Bifunctor p => (a -> b) -> p a c -> p b c -- | Map covariantly over the second argument. -- --
--   secondbimap id
--   
-- --

Examples

-- --
--   >>> second (+1) ('j', 3)
--   ('j',4)
--   
-- --
--   >>> second (+1) (Right 3)
--   Right 4
--   
second :: Bifunctor p => (b -> c) -> p a b -> p a c -- | Monads in which IO computations may be embedded. Any monad -- built by applying a sequence of monad transformers to the IO -- monad will be an instance of this class. -- -- Instances should satisfy the following laws, which state that -- liftIO is a transformer of monads: -- -- class Monad m => MonadIO (m :: Type -> Type) -- | Lift a computation from the IO monad. This allows us to run IO -- computations in any monadic stack, so long as it supports these kinds -- of operations (i.e. IO is the base monad for the stack). -- --

Example

-- --
--   import Control.Monad.Trans.State -- from the "transformers" library
--   
--   printState :: Show s => StateT s IO ()
--   printState = do
--     state <- get
--     liftIO $ print state
--   
-- -- Had we omitted liftIO, we would have ended up with -- this error: -- --
--   • Couldn't match type ‘IO’ with ‘StateT s IO’
--    Expected type: StateT s IO ()
--      Actual type: IO ()
--   
-- -- The important part here is the mismatch between StateT s IO -- () and IO (). -- -- Luckily, we know of a function that takes an IO a and -- returns an (m a): liftIO, enabling us to run -- the program and see the expected results: -- --
--   > evalStateT printState "hello"
--   "hello"
--   
--   > evalStateT printState 3
--   3
--   
liftIO :: MonadIO m => IO a -> m a -- | approxRational, applied to two real fractional numbers -- x and epsilon, returns the simplest rational number -- within epsilon of x. A rational number y is -- said to be simpler than another y' if -- -- -- -- Any real interval contains a unique simplest rational; in particular, -- note that 0/1 is the simplest rational of all. approxRational :: RealFrac a => a -> a -> Rational -- | Strict version of modifySTRef modifySTRef' :: STRef s a -> (a -> a) -> ST s () -- | Mutate the contents of an STRef. -- --
--   >>> :{
--   runST (do
--       ref <- newSTRef ""
--       modifySTRef ref (const "world")
--       modifySTRef ref (++ "!")
--       modifySTRef ref ("Hello, " ++)
--       readSTRef ref )
--   :}
--   "Hello, world!"
--   
-- -- Be warned that modifySTRef does not apply the function -- strictly. This means if the program calls modifySTRef many -- times, but seldom uses the value, thunks will pile up in memory -- resulting in a space leak. This is a common mistake made when using an -- STRef as a counter. For example, the following will leak memory -- and may produce a stack overflow: -- --
--   >>> import Control.Monad (replicateM_)
--   
--   >>> :{
--   print (runST (do
--       ref <- newSTRef 0
--       replicateM_ 1000 $ modifySTRef ref (+1)
--       readSTRef ref ))
--   :}
--   1000
--   
-- -- To avoid this problem, use modifySTRef' instead. modifySTRef :: STRef s a -> (a -> a) -> ST s () -- | An abstract unique object. Objects of type Unique may be -- compared for equality and ordering and hashed into Int. -- --
--   >>> :{
--   do x <- newUnique
--      print (x == x)
--      y <- newUnique
--      print (x == y)
--   :}
--   True
--   False
--   
data Unique -- | Creates a new object of type Unique. The value returned will -- not compare equal to any other value of type Unique returned by -- previous calls to newUnique. There is no limit on the number of -- times newUnique may be called. newUnique :: IO Unique -- | Hashes a Unique into an Int. Two Uniques may hash -- to the same value, although in practice this is unlikely. The -- Int returned makes a good hash key. hashUnique :: Unique -> Int class IsLabel (x :: Symbol) a fromLabel :: IsLabel x a => a -- | An abstract name for an object, that supports equality and hashing. -- -- Stable names have the following property: -- -- -- -- The reverse is not necessarily true: if two stable names are not -- equal, then the objects they name may still be equal. Note in -- particular that makeStableName may return a different -- StableName after an object is evaluated. -- -- Stable Names are similar to Stable Pointers -- (Foreign.StablePtr), but differ in the following ways: -- -- data StableName a -- | Makes a StableName for an arbitrary object. The object passed -- as the first argument is not evaluated by makeStableName. makeStableName :: a -> IO (StableName a) -- | Convert a StableName to an Int. The Int returned -- is not necessarily unique; several StableNames may map to the -- same Int (in practice however, the chances of this are small, -- so the result of hashStableName makes a good hash key). hashStableName :: StableName a -> Int -- | Equality on StableName that does not require that the types of -- the arguments match. eqStableName :: StableName a -> StableName b -> Bool -- | withProgName name act - while executing action -- act, have getProgName return name. withProgName :: String -> IO a -> IO a -- | withArgs args act - while executing action -- act, have getArgs return args. withArgs :: [String] -> IO a -> IO a -- | 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 () -- | setEnv name value sets the specified environment variable to -- value. -- -- Early versions of this function operated under the mistaken belief -- that setting an environment variable to the empty string on -- Windows removes that environment variable from the environment. For -- the sake of compatibility, it adopted that behavior on POSIX. In -- particular -- --
--   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 () -- | Return the value of the environment variable var, or -- Nothing if there is no such value. -- -- For POSIX users, this is equivalent to getEnv. lookupEnv :: String -> IO (Maybe 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 -- | 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)] -- | 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: -- -- getEnv :: String -> IO String -- | Computation getArgs returns a list of the program's command -- line arguments (not including the program name). getArgs :: IO [String] -- | Returns the absolute pathname of the current executable. -- -- Note that for scripts and interactive sessions, this is the path to -- the interpreter (e.g. ghci.) -- -- Since base 4.11.0.0, getExecutablePath resolves symlinks on -- Windows. If an executable is launched through a symlink, -- getExecutablePath returns the absolute path of the original -- executable. getExecutablePath :: IO FilePath -- | Computation exitWith code throws ExitCode -- code. Normally this terminates the program, returning -- code to the program's caller. -- -- On program termination, the standard Handles stdout and -- stderr are flushed automatically; any other buffered -- Handles need to be flushed manually, otherwise the buffered -- data will be discarded. -- -- A program that fails in any other way is treated as if it had called -- exitFailure. A program that terminates successfully without -- calling exitWith explicitly is treated as if it had called -- exitWith ExitSuccess. -- -- As an ExitCode is not an IOException, exitWith -- bypasses the error handling in the IO monad and cannot be -- intercepted by catch from the Prelude. However it is a -- SomeException, and can be caught using the functions of -- Control.Exception. This means that cleanup computations added -- with bracket (from Control.Exception) are also executed -- properly on exitWith. -- -- Note: in GHC, exitWith should be called from the main program -- thread in order to exit the process. When called from another thread, -- exitWith will throw an ExitException as normal, but -- the exception will not cause the process itself to exit. exitWith :: ExitCode -> IO a -- | The computation exitSuccess is equivalent to exitWith -- ExitSuccess, It terminates the program successfully. exitSuccess :: IO a -- | The computation exitFailure is equivalent to exitWith -- (ExitFailure exitfail), where -- exitfail is implementation-dependent. exitFailure :: IO a -- | Write given error message to stderr and terminate with -- exitFailure. die :: String -> IO a -- | Triggers an immediate minor garbage collection. performMinorGC :: IO () -- | Triggers an immediate major garbage collection. performMajorGC :: IO () -- | Triggers an immediate major garbage collection. performGC :: IO () -- | Format a variable number of arguments with the C-style formatting -- string. -- --
--   >>> printf "%s, %d, %.4f" "hello" 123 pi
--   hello, 123, 3.1416
--   
-- -- The return value is either String or (IO a) -- (which should be (IO ()), but Haskell's type system -- makes this hard). -- -- The format string consists of ordinary characters and conversion -- specifications, which specify how to format one of the arguments -- to printf in the output string. A format specification is -- introduced by the % character; this character can be -- self-escaped into the format string using %%. A format -- specification ends with a format character that provides the -- primary information about how to format the value. The rest of the -- conversion specification is optional. In order, one may have flag -- characters, a width specifier, a precision specifier, and -- type-specific modifier characters. -- -- Unlike C printf(3), the formatting of this printf is -- driven by the argument type; formatting is type specific. The types -- formatted by printf "out of the box" are: -- -- -- -- printf is also extensible to support other types: see below. -- -- A conversion specification begins with the character %, -- followed by zero or more of the following flags: -- --
--   -      left adjust (default is right adjust)
--   +      always use a sign (+ or -) for signed conversions
--   space  leading space for positive numbers in signed conversions
--   0      pad with zeros rather than spaces
--   #      use an \"alternate form\": see below
--   
-- -- When both flags are given, - overrides 0 and -- + overrides space. A negative width specifier in a * -- conversion is treated as positive but implies the left adjust flag. -- -- The "alternate form" for unsigned radix conversions is as in C -- printf(3): -- --
--   %o           prefix with a leading 0 if needed
--   %x           prefix with a leading 0x if nonzero
--   %X           prefix with a leading 0X if nonzero
--   %b           prefix with a leading 0b if nonzero
--   %[eEfFgG]    ensure that the number contains a decimal point
--   
-- -- Any flags are followed optionally by a field width: -- --
--   num    field width
--   *      as num, but taken from argument list
--   
-- -- The field width is a minimum, not a maximum: it will be expanded as -- needed to avoid mutilating a value. -- -- Any field width is followed optionally by a precision: -- --
--   .num   precision
--   .      same as .0
--   .*     as num, but taken from argument list
--   
-- -- Negative precision is taken as 0. The meaning of the precision depends -- on the conversion type. -- --
--   Integral    minimum number of digits to show
--   RealFloat   number of digits after the decimal point
--   String      maximum number of characters
--   
-- -- The precision for Integral types is accomplished by zero-padding. If -- both precision and zero-pad are given for an Integral field, the -- zero-pad is ignored. -- -- Any precision is followed optionally for Integral types by a width -- modifier; the only use of this modifier being to set the implicit size -- of the operand for conversion of a negative operand to unsigned: -- --
--   hh     Int8
--   h      Int16
--   l      Int32
--   ll     Int64
--   L      Int64
--   
-- -- The specification ends with a format character: -- --
--   c      character               Integral
--   d      decimal                 Integral
--   o      octal                   Integral
--   x      hexadecimal             Integral
--   X      hexadecimal             Integral
--   b      binary                  Integral
--   u      unsigned decimal        Integral
--   f      floating point          RealFloat
--   F      floating point          RealFloat
--   g      general format float    RealFloat
--   G      general format float    RealFloat
--   e      exponent format float   RealFloat
--   E      exponent format float   RealFloat
--   s      string                  String
--   v      default format          any type
--   
-- -- The "%v" specifier is provided for all built-in types, and should be -- provided for user-defined type formatters as well. It picks a "best" -- representation for the given type. For the built-in types the "%v" -- specifier is converted as follows: -- --
--   c      Char
--   u      other unsigned Integral
--   d      other signed Integral
--   g      RealFloat
--   s      String
--   
-- -- Mismatch between the argument types and the format string, as well as -- any other syntactic or semantic errors in the format string, will -- cause an exception to be thrown at runtime. -- -- Note that the formatting for RealFloat types is currently a bit -- different from that of C printf(3), conforming instead to -- showEFloat, showFFloat and showGFloat (and their -- alternate versions showFFloatAlt and showGFloatAlt). -- This is hard to fix: the fixed versions would format in a -- backward-incompatible way. In any case the Haskell behavior is -- generally more sensible than the C behavior. A brief summary of some -- key differences: -- -- printf :: PrintfType r => String -> r -- | Similar to printf, except that output is via the specified -- Handle. The return type is restricted to (IO -- a). hPrintf :: HPrintfType r => Handle -> String -> r -- | zipWithM_ is the extension of zipWithM which ignores the -- final result. zipWithM_ :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m () -- | The zipWithM function generalizes zipWith to arbitrary -- applicative functors. zipWithM :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m [c] -- | The reverse of when. unless :: Applicative f => Bool -> f () -> f () -- | Like replicateM, but discards the result. -- --

Examples

-- --
--   >>> replicateM_ 3 (putStrLn "a")
--   a
--   a
--   a
--   
replicateM_ :: Applicative m => Int -> m a -> m () -- | replicateM n act performs the action act -- n times, and then returns the list of results: -- --

Examples

-- --
--   >>> import Control.Monad.State
--   
--   >>> runState (replicateM 3 $ state $ \s -> (s, s + 1)) 1
--   ([1,2,3],4)
--   
replicateM :: Applicative m => Int -> m a -> m [a] -- | Direct MonadPlus equivalent of filter. -- --

Examples

-- -- The filter function is just mfilter specialized to the -- list monad: -- --
--   filter = ( mfilter :: (a -> Bool) -> [a] -> [a] )
--   
-- -- An example using mfilter with the Maybe monad: -- --
--   >>> mfilter odd (Just 1)
--   Just 1
--   
--   >>> mfilter odd (Just 2)
--   Nothing
--   
mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a -- | The mapAndUnzipM function maps its first argument over a list, -- returning the result as a pair of lists. This function is mainly used -- with complicated data structures or a state monad. mapAndUnzipM :: Applicative m => (a -> m (b, c)) -> [a] -> m ([b], [c]) -- | Repeat an action indefinitely. -- --

Examples

-- -- A common use of forever is to process input from network -- sockets, Handles, and channels (e.g. MVar and -- Chan). -- -- For example, here is how we might implement an echo server, -- using forever both to listen for client connections on a -- network socket and to echo client input on client connection handles: -- --
--   echoServer :: Socket -> IO ()
--   echoServer socket = forever $ do
--     client <- accept socket
--     forkFinally (echo client) (\_ -> hClose client)
--     where
--       echo :: Handle -> IO ()
--       echo client = forever $
--         hGetLine client >>= hPutStrLn client
--   
-- -- Note that "forever" isn't necessarily non-terminating. If the action -- is in a MonadPlus and short-circuits after some number -- of iterations. then forever actually returns -- mzero, effectively short-circuiting its caller. forever :: Applicative f => f a -> f b -- | Like foldM, but discards the result. foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m () -- | The foldM function is analogous to foldl, except that -- its result is encapsulated in a monad. Note that foldM works -- from left-to-right over the list arguments. This could be an issue -- where (>>) and the `folded function' are not -- commutative. -- --
--   foldM f a1 [x1, x2, ..., xm]
--   
--   ==
--   
--   do
--     a2 <- f a1 x1
--     a3 <- f a2 x2
--     ...
--     f am xm
--   
-- -- If right-to-left evaluation is required, the input list should be -- reversed. -- -- Note: foldM is the same as foldlM foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | This generalizes the list-based filter function. filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a] -- | Left-to-right composition of Kleisli arrows. -- -- '(bs >=> cs) a' can be understood as the -- do expression -- --
--   do b <- bs a
--      cs b
--   
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 >=> -- | Right-to-left composition of Kleisli arrows. -- (>=>), with the arguments flipped. -- -- Note how this operator resembles function composition -- (.): -- --
--   (.)   ::            (b ->   c) -> (a ->   b) -> a ->   c
--   (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
--   
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c infixr 1 <=< -- | Strict version of <$>. (<$!>) :: Monad m => (a -> b) -> m a -> m b infixl 4 <$!> -- | Provides one possible concrete representation for Version. For -- a version with versionBranch = [1,2,3] and -- versionTags = ["tag1","tag2"], the output will be -- 1.2.3-tag1-tag2. showVersion :: Version -> String -- | A parser for versions in the format produced by showVersion. parseVersion :: ReadP Version -- | like trace, but additionally prints a call stack if one is -- available. -- -- In the current GHC implementation, the call stack is only available if -- the program was compiled with -prof; otherwise -- traceStack behaves exactly like trace. Entries in the -- call stack correspond to SCC annotations, so it is a good -- idea to use -fprof-auto or -fprof-auto-calls to add -- SCC annotations automatically. traceStack :: String -> a -> a -- | 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 () -- | 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 uses show on the argument to convert it -- to a String. -- -- This makes it convenient for printing the values of interesting -- variables or expressions inside a function. For example here we print -- the value of the variables x and y: -- --
--   >>> let f x y = traceShow (x,y) (x + y) in f (1+2) 5
--   (3,5)
--   8
--   
traceShow :: Show a => a -> b -> b -- | The traceMarkerIO function emits a marker to the eventlog, if -- eventlog profiling is available and enabled at runtime. -- -- Compared to traceMarker, traceMarkerIO sequences the -- event with respect to other IO actions. traceMarkerIO :: String -> IO () -- | The traceMarker function emits a marker to the eventlog, if -- eventlog profiling is available and enabled at runtime. The -- String is the name of the marker. The name is just used in -- the profiling tools to help you keep clear which marker is which. -- -- This function is suitable for use in pure code. In an IO context use -- traceMarkerIO instead. -- -- Note that when using GHC's SMP runtime, it is possible (but rare) to -- get duplicate events emitted if two CPUs simultaneously evaluate the -- same thunk that uses traceMarker. traceMarker :: String -> 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 trace but returns the message instead of a third value. -- --
--   >>> traceId "hello"
--   hello
--   "hello"
--   
traceId :: String -> String -- | The traceIO function outputs the trace message from the IO -- monad. This sequences the output with respect to other IO actions. traceIO :: String -> IO () -- | The traceEventIO function emits a message to the eventlog, if -- eventlog profiling is available and enabled at runtime. -- -- Compared to traceEvent, traceEventIO sequences the event -- with respect to other IO actions. traceEventIO :: String -> IO () -- | The traceEvent function behaves like trace with the -- difference that the message is emitted to the eventlog, if eventlog -- profiling is available and enabled at runtime. -- -- It is suitable for use in pure code. In an IO context use -- traceEventIO instead. -- -- Note that when using GHC's SMP runtime, it is possible (but rare) to -- get duplicate events emitted if two CPUs simultaneously evaluate the -- same thunk that uses traceEvent. traceEvent :: String -> a -> a putTraceMsg :: String -> IO () -- | Immediately flush the event log, if enabled. flushEventLog :: IO () -- | The isSubsequenceOf function takes two lists and returns -- True if all the elements of the first list occur, in order, in -- the second. The elements do not have to occur consecutively. -- -- isSubsequenceOf x y is equivalent to elem x -- (subsequences y). -- --

Examples

-- --
--   >>> isSubsequenceOf "GHC" "The Glorious Haskell Compiler"
--   True
--   
--   >>> isSubsequenceOf ['a','d'..'z'] ['a'..'z']
--   True
--   
--   >>> isSubsequenceOf [1..10] [10,9..0]
--   False
--   
isSubsequenceOf :: Eq a => [a] -> [a] -> Bool -- | The mapAccumR function behaves like a combination of -- fmap and foldr; it applies a function to each element of -- a structure, passing an accumulating parameter from right to left, and -- returning a final value of this accumulator together with the new -- structure. -- --

Examples

-- -- Basic usage: -- --
--   >>> mapAccumR (\a b -> (a + b, a)) 0 [1..10]
--   (55,[54,52,49,45,40,34,27,19,10,0])
--   
-- --
--   >>> mapAccumR (\a b -> (a <> show b, a)) "0" [1..5]
--   ("054321",["05432","0543","054","05","0"])
--   
mapAccumR :: Traversable t => (s -> a -> (s, b)) -> s -> t a -> (s, t b) -- | The mapAccumL function behaves like a combination of -- fmap and foldl; it applies a function to each element of -- a structure, passing an accumulating parameter from left to right, and -- returning a final value of this accumulator together with the new -- structure. -- --

Examples

-- -- Basic usage: -- --
--   >>> mapAccumL (\a b -> (a + b, a)) 0 [1..10]
--   (55,[0,1,3,6,10,15,21,28,36,45])
--   
-- --
--   >>> mapAccumL (\a b -> (a <> show b, a)) "0" [1..5]
--   ("012345",["0","01","012","0123","01234"])
--   
mapAccumL :: Traversable t => (s -> a -> (s, b)) -> s -> t a -> (s, t b) -- | forM is mapM with its arguments flipped. For a version -- that ignores the results see forM_. forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b) -- | for is traverse with its arguments flipped. For a -- version that ignores the results see for_. for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b) -- | This function may be used as a value for foldMap in a -- Foldable instance. -- --
--   foldMapDefault f ≡ getConst . traverse (Const . f)
--   
foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m -- | This function may be used as a value for fmap in a -- Functor instance, provided that traverse is defined. -- (Using fmapDefault with a Traversable instance defined -- only by sequenceA will result in infinite recursion.) -- --
--   fmapDefault f ≡ runIdentity . traverse (Identity . f)
--   
fmapDefault :: Traversable t => (a -> b) -> t a -> t b -- | Lists, but with an Applicative functor based on zipping. newtype ZipList a ZipList :: [a] -> ZipList a [getZipList] :: ZipList a -> [a] newtype WrappedMonad (m :: Type -> Type) a WrapMonad :: m a -> WrappedMonad (m :: Type -> Type) a [unwrapMonad] :: WrappedMonad (m :: Type -> Type) a -> m a newtype WrappedArrow (a :: Type -> Type -> Type) b c WrapArrow :: a b c -> WrappedArrow (a :: Type -> Type -> Type) b c [unwrapArrow] :: WrappedArrow (a :: Type -> Type -> Type) b c -> a b c -- | One or none. -- -- It is useful for modelling any computation that is allowed to fail. -- --

Examples

-- -- Using the Alternative instance of Control.Monad.Except, -- the following functions: -- --
--   >>> import Control.Monad.Except
--   
-- --
--   >>> canFail = throwError "it failed" :: Except String Int
--   
--   >>> final = return 42                :: Except String Int
--   
-- -- Can be combined by allowing the first function to fail: -- --
--   >>> runExcept $ canFail *> final
--   Left "it failed"
--   
--   >>> runExcept $ optional canFail *> final
--   Right 42
--   
optional :: Alternative f => f a -> f (Maybe a) -- | Kleisli arrows of a monad. newtype Kleisli (m :: Type -> Type) a b Kleisli :: (a -> m b) -> Kleisli (m :: Type -> Type) a b [runKleisli] :: Kleisli (m :: Type -> Type) a b -> a -> m b class Arrow a => ArrowZero (a :: TYPE LiftedRep -> TYPE LiftedRep -> Type) zeroArrow :: ArrowZero a => a b c -- | A monoid on arrows. class ArrowZero a => ArrowPlus (a :: TYPE LiftedRep -> TYPE LiftedRep -> Type) -- | An associative operation with identity zeroArrow. (<+>) :: ArrowPlus a => a b c -> a b c -> a b c infixr 5 <+> -- | The ArrowApply class is equivalent to Monad: any monad -- gives rise to a Kleisli arrow, and any instance of -- ArrowApply defines a monad. newtype ArrowMonad (a :: Type -> Type -> Type) b ArrowMonad :: a () b -> ArrowMonad (a :: Type -> Type -> Type) b -- | The loop operator expresses computations in which an output -- value is fed back as input, although the computation occurs only once. -- It underlies the rec value recursion construct in arrow -- notation. loop should satisfy the following laws: -- -- -- -- where -- --
--   assoc ((a,b),c) = (a,(b,c))
--   unassoc (a,(b,c)) = ((a,b),c)
--   
class Arrow a => ArrowLoop (a :: TYPE LiftedRep -> TYPE LiftedRep -> Type) loop :: ArrowLoop a => a (b, d) (c, d) -> a b c -- | Choice, for arrows that support it. This class underlies the -- if and case constructs in arrow notation. -- -- Instances should satisfy the following laws: -- -- -- -- where -- --
--   assocsum (Left (Left x)) = Left x
--   assocsum (Left (Right y)) = Right (Left y)
--   assocsum (Right z) = Right (Right z)
--   
-- -- The other combinators have sensible default definitions, which may be -- overridden for efficiency. class Arrow a => ArrowChoice (a :: TYPE LiftedRep -> TYPE LiftedRep -> Type) -- | Feed marked inputs through the argument arrow, passing the rest -- through unchanged to the output. left :: ArrowChoice a => a b c -> a (Either b d) (Either c d) -- | A mirror image of left. -- -- The default definition may be overridden with a more efficient version -- if desired. right :: ArrowChoice a => a b c -> a (Either d b) (Either d c) -- | Split the input between the two argument arrows, retagging and merging -- their outputs. Note that this is in general not a functor. -- -- The default definition may be overridden with a more efficient version -- if desired. (+++) :: ArrowChoice a => a b c -> a b' c' -> a (Either b b') (Either c c') -- | Fanin: Split the input between the two argument arrows and merge their -- outputs. -- -- The default definition may be overridden with a more efficient version -- if desired. (|||) :: ArrowChoice a => a b d -> a c d -> a (Either b c) d infixr 2 ||| infixr 2 +++ -- | Some arrows allow application of arrow inputs to other inputs. -- Instances should satisfy the following laws: -- -- -- -- Such arrows are equivalent to monads (see ArrowMonad). class Arrow a => ArrowApply (a :: TYPE LiftedRep -> TYPE LiftedRep -> Type) app :: ArrowApply a => a (a b c, b) c -- | The basic arrow class. -- -- Instances should satisfy the following laws: -- -- -- -- where -- --
--   assoc ((a,b),c) = (a,(b,c))
--   
-- -- The other combinators have sensible default definitions, which may be -- overridden for efficiency. class Category a => Arrow (a :: TYPE LiftedRep -> TYPE LiftedRep -> Type) -- | Lift a function to an arrow. arr :: Arrow a => (b -> c) -> a b c -- | Split the input between the two argument arrows and combine their -- output. Note that this is in general not a functor. -- -- The default definition may be overridden with a more efficient version -- if desired. (***) :: Arrow a => a b c -> a b' c' -> a (b, b') (c, c') -- | Fanout: send the input to both argument arrows and combine their -- output. -- -- The default definition may be overridden with a more efficient version -- if desired. (&&&) :: Arrow a => a b c -> a b c' -> a b (c, c') infixr 3 &&& infixr 3 *** -- | The identity arrow, which plays the role of return in arrow -- notation. returnA :: Arrow a => a b b -- | Any instance of ArrowApply can be made into an instance of -- ArrowChoice by defining left = leftApp. leftApp :: ArrowApply a => a b c -> a (Either b d) (Either c d) -- | Precomposition with a pure function. (^>>) :: Arrow a => (b -> c) -> a c d -> a b d infixr 1 ^>> -- | Postcomposition with a pure function (right-to-left variant). (^<<) :: Arrow a => (c -> d) -> a b c -> a b d infixr 1 ^<< -- | Postcomposition with a pure function. (>>^) :: Arrow a => a b c -> (c -> d) -> a b d infixr 1 >>^ -- | Precomposition with a pure function (right-to-left variant). (<<^) :: Arrow a => a c d -> (b -> c) -> a b d infixr 1 <<^ -- | Identity functor and monad. (a non-strict monad) newtype Identity a Identity :: a -> Identity a [runIdentity] :: Identity a -> a -- | The computation writeFile file str function writes the -- string str, to the file file. writeFile :: FilePath -> String -> IO () -- | The readLn function combines getLine and readIO. readLn :: Read a => IO a -- | 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 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 same as putStr, but adds a newline character. putStrLn :: String -> IO () -- | Write a string to the standard output device (same as hPutStr -- stdout). putStr :: String -> IO () -- | Write a character to the standard output device (same as -- hPutChar stdout). putChar :: Char -> IO () -- | 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 () -- | Read a line from the standard input device (same as hGetLine -- stdin). getLine :: IO String -- | 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 character from the standard input device (same as -- hGetChar stdin). getChar :: IO Char -- | The computation appendFile file str function appends -- the string str, to the file file. -- -- Note that writeFile and appendFile write a literal -- string to a file. To write a value of any printable type, as with -- print, use the show function to convert the value to a -- string first. -- --
--   main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
--   
appendFile :: FilePath -> String -> IO () -- | Computation hClose hdl makes handle hdl -- closed. Before the computation finishes, if hdl is writable -- its buffer is flushed as for hFlush. Performing hClose -- on a handle that has already been closed has no effect; doing so is -- not an error. All other operations on a closed handle will fail. If -- hClose fails for any reason, any further operations (apart from -- hClose) on the handle will still fail as if hdl had -- been successfully closed. -- -- hClose is an interruptible operation in the sense -- described in Control.Exception. If hClose is interrupted -- by an asynchronous exception in the process of flushing its buffers, -- then the I/O device (e.g., file) will be closed anyway. hClose :: Handle -> IO () -- | Suspends the current thread for a given number of microseconds (GHC -- only). -- -- There is no guarantee that the thread will be rescheduled promptly -- when the delay has expired, but the thread will never continue to run -- earlier than specified. threadDelay :: Int -> IO () -- | Switch the value of returned TVar from initial value -- False to True after a given number of microseconds. The -- caveats associated with threadDelay also apply. registerDelay :: Int -> IO (TVar Bool) ioManagerCapabilitiesChanged :: IO () ensureIOManagerIsRunning :: IO () -- | Close a file descriptor in a concurrency-safe way (GHC only). If you -- are using threadWaitRead or threadWaitWrite to perform -- blocking I/O, you must use this function to close file -- descriptors, or blocked threads may not be woken. -- -- Any threads that are blocked on the file descriptor via -- threadWaitRead or threadWaitWrite will be unblocked by -- having IO exceptions thrown. closeFdWith :: (Fd -> IO ()) -> Fd -> IO () type Signal = CInt type HandlerFun = ForeignPtr Word8 -> IO () setHandler :: Signal -> Maybe (HandlerFun, Dynamic) -> IO (Maybe (HandlerFun, Dynamic)) runHandlers :: ForeignPtr Word8 -> Signal -> IO () -- | Like withMVar, but the IO action in the second -- argument is executed with asynchronous exceptions masked. withMVarMasked :: MVar a -> (a -> IO b) -> IO b -- | withMVar is an exception-safe wrapper for operating on the -- contents of an MVar. This operation is exception-safe: it will -- replace the original contents of the MVar if an exception is -- raised (see Control.Exception). However, it is only atomic if -- there are no other producers for this MVar. withMVar :: MVar a -> (a -> IO b) -> IO b -- | Take a value from an MVar, put a new value into the MVar -- and return the value taken. This function is atomic only if there are -- no other producers for this MVar. swapMVar :: MVar a -> a -> IO a -- | An exception-safe wrapper for modifying the contents of an -- MVar. Like withMVar, modifyMVar will replace the -- original contents of the MVar if an exception is raised during -- the operation. This function is only atomic if there are no other -- producers for this MVar. modifyMVar_ :: MVar a -> (a -> IO a) -> IO () -- | Like modifyMVar_, but the IO action in the second -- argument is executed with asynchronous exceptions masked. modifyMVarMasked_ :: MVar a -> (a -> IO a) -> IO () -- | Like modifyMVar, but the IO action in the second -- argument is executed with asynchronous exceptions masked. modifyMVarMasked :: MVar a -> (a -> IO (a, b)) -> IO b -- | A slight variation on modifyMVar_ that allows a value to be -- returned (b) in addition to the modified value of the -- MVar. modifyMVar :: MVar a -> (a -> IO (a, b)) -> IO b -- | Make a Weak pointer to an MVar, using the second -- argument as a finalizer to run when MVar is garbage-collected mkWeakMVar :: MVar a -> IO () -> IO (Weak (MVar a)) addMVarFinalizer :: MVar a -> IO () -> IO () -- | 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 -- | You need this when using catches. data Handler a Handler :: (e -> IO a) -> Handler a -- | 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 -- | 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 () -- | Allow the result of an ST computation to be used (lazily) -- inside the computation. -- -- Note that if f is strict, fixST f = _|_. fixST :: (a -> ST s a) -> ST s a -- | I/O error that is programmer-defined. userErrorType :: IOErrorType -- | The construct tryIOError comp exposes IO errors which -- occur within a computation, and which are not fully handled. -- -- Non-I/O exceptions are not caught by this variant; to catch all -- exceptions, use try from Control.Exception. tryIOError :: IO a -> IO (Either IOError a) -- | I/O error where the operation failed because the resource vanished. -- This happens when, for example, attempting to write to a closed socket -- or attempting to write to a named pipe that was deleted. resourceVanishedErrorType :: IOErrorType -- | I/O error where the operation failed because the user does not have -- sufficient operating system privilege to perform that operation. permissionErrorType :: IOErrorType -- | Catch any IOException that occurs in the computation and throw -- a modified version. modifyIOError :: (IOError -> IOError) -> IO a -> IO a -- | Construct an IOException of the given type where the second -- argument describes the error location and the third and fourth -- argument contain the file handle and file path of the file involved in -- the error if applicable. mkIOError :: IOErrorType -> String -> Maybe Handle -> Maybe FilePath -> IOError -- | I/O error that is programmer-defined. isUserErrorType :: IOErrorType -> Bool -- | A programmer-defined error value constructed using userError. isUserError :: IOError -> Bool -- | I/O error where the operation failed because the resource vanished. -- See resourceVanishedErrorType. isResourceVanishedErrorType :: IOErrorType -> Bool -- | An error indicating that the operation failed because the resource -- vanished. See resourceVanishedErrorType. isResourceVanishedError :: IOError -> Bool -- | I/O error where the operation failed because the user does not have -- sufficient operating system privilege to perform that operation. isPermissionErrorType :: IOErrorType -> Bool -- | An error indicating that an IO operation failed because the -- user does not have sufficient operating system privilege to perform -- that operation. isPermissionError :: IOError -> Bool -- | I/O error where the operation is not possible. isIllegalOperationErrorType :: IOErrorType -> Bool -- | An error indicating that an IO operation failed because the -- operation was not possible. Any computation which returns an IO -- result may fail with isIllegalOperation. In some cases, an -- implementation will not be able to distinguish between the possible -- error causes. In this case it should fail with -- isIllegalOperation. isIllegalOperation :: IOError -> Bool -- | I/O error where the operation failed because the device is full. isFullErrorType :: IOErrorType -> Bool -- | An error indicating that an IO operation failed because the -- device is full. isFullError :: IOError -> Bool -- | I/O error where the operation failed because the end of file has been -- reached. isEOFErrorType :: IOErrorType -> Bool -- | An error indicating that an IO operation failed because the end -- of file has been reached. isEOFError :: IOError -> Bool -- | I/O error where the operation failed because one of its arguments does -- not exist. isDoesNotExistErrorType :: IOErrorType -> Bool -- | An error indicating that an IO operation failed because one of -- its arguments does not exist. isDoesNotExistError :: IOError -> Bool -- | I/O error where the operation failed because one of its arguments is a -- single-use resource, which is already being used. isAlreadyInUseErrorType :: IOErrorType -> Bool -- | An error indicating that an IO operation failed because one of -- its arguments is a single-use resource, which is already being used -- (for example, opening the same file twice for writing might give this -- error). isAlreadyInUseError :: IOError -> Bool -- | I/O error where the operation failed because one of its arguments -- already exists. isAlreadyExistsErrorType :: IOErrorType -> Bool -- | An error indicating that an IO operation failed because one of -- its arguments already exists. isAlreadyExistsError :: IOError -> Bool ioeSetLocation :: IOError -> String -> IOError ioeSetHandle :: IOError -> Handle -> IOError ioeSetFileName :: IOError -> FilePath -> IOError ioeSetErrorType :: IOError -> IOErrorType -> IOError ioeSetErrorString :: IOError -> String -> IOError ioeGetLocation :: IOError -> String ioeGetHandle :: IOError -> Maybe Handle ioeGetFileName :: IOError -> Maybe FilePath ioeGetErrorType :: IOError -> IOErrorType ioeGetErrorString :: IOError -> String -- | I/O error where the operation is not possible. illegalOperationErrorType :: IOErrorType -- | I/O error where the operation failed because the device is full. fullErrorType :: IOErrorType -- | I/O error where the operation failed because the end of file has been -- reached. eofErrorType :: IOErrorType -- | I/O error where the operation failed because one of its arguments does -- not exist. doesNotExistErrorType :: IOErrorType -- | The catchIOError function establishes a handler that receives -- any IOException raised in the action protected by -- catchIOError. An IOException is caught by the most -- recent handler established by one of the exception handling functions. -- These handlers are not selective: all IOExceptions are caught. -- Exception propagation must be explicitly provided in a handler by -- re-raising any unwanted exceptions. For example, in -- --
--   f = catchIOError g (\e -> if IO.isEOFError e then return [] else ioError e)
--   
-- -- the function f returns [] when an end-of-file -- exception (cf. isEOFError) occurs in g; otherwise, the -- exception is propagated to the next outer handler. -- -- When an exception propagates outside the main program, the Haskell -- system prints the associated IOException value and exits the -- program. -- -- Non-I/O exceptions are not caught by this variant; to catch all -- exceptions, use catch from Control.Exception. catchIOError :: IO a -> (IOError -> IO a) -> IO a -- | Adds a location description and maybe a file path and file handle to -- an IOException. If any of the file handle or file path is not -- given the corresponding value in the IOException remains -- unaltered. annotateIOError :: IOError -> String -> Maybe Handle -> Maybe FilePath -> IOError -- | I/O error where the operation failed because one of its arguments is a -- single-use resource, which is already being used. alreadyInUseErrorType :: IOErrorType -- | I/O error where the operation failed because one of its arguments -- already exists. alreadyExistsErrorType :: IOErrorType -- | 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 -- | 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 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 pattern match failed. The String gives information about -- the source location of the pattern. newtype PatternMatchFail PatternMatchFail :: String -> PatternMatchFail -- | 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 -- | 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 -- | Thrown when the program attempts to call atomically, from the -- stm package, inside another call to atomically. data NestedAtomically NestedAtomically :: NestedAtomically -- | 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 then it will be propagated up to the next -- enclosing exception handler. -- --
--   try a = catch (Right `liftM` a) (return . Left)
--   
try :: Exception e => IO a -> IO (Either e a) -- | Like finally, but only performs the final action if there was -- an exception raised by the computation. onException :: IO a -> IO b -> IO a -- | This function maps one exception into another as proposed in the paper -- "A semantics for imprecise exceptions". mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a -- | 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 -- | A specialised variant of bracket with just a computation to run -- afterward. finally :: IO a -> IO b -> 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 variant of bracket where the return value from the first -- computation is not required. bracket_ :: IO a -> IO b -> IO c -> IO c -- | 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 -- | When you want to acquire a resource, do some work with it, and then -- release the resource, it is a good idea to use bracket, because -- bracket will install the necessary exception handler to release -- the resource in the event that an exception is raised during the -- computation. If an exception is raised, then bracket will -- re-raise the exception (after performing the release). -- -- A common example is opening a file: -- --
--   bracket
--     (openFile "filename" ReadMode)
--     (hClose)
--     (\fileHandle -> do { ... })
--   
-- -- The arguments to bracket are in this order so that we can -- partially apply it, e.g.: -- --
--   withFile name mode = bracket (openFile name mode) hClose
--   
-- -- Bracket wraps the release action with mask, which is sufficient -- to ensure that the release action executes to completion when it does -- not invoke any interruptible actions, even in the presence of -- asynchronous exceptions. For example, hClose is -- uninterruptible when it is not racing other uses of the handle. -- Similarly, closing a socket (from "network" package) is also -- uninterruptible under similar conditions. An example of an -- interruptible action is killThread. Completion of interruptible -- release actions can be ensured by wrapping them in in -- uninterruptibleMask_, but this risks making the program -- non-responsive to Control-C, or timeouts. Another option is -- to run the release action asynchronously in its own thread: -- --
--   void $ uninterruptibleMask_ $ forkIO $ do { ... }
--   
-- -- The resource will be released as soon as possible, but the thread that -- invoked bracket will not block in an uninterruptible state. bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c -- | The current status of a thread data ThreadStatus -- | the thread is currently runnable or running ThreadRunning :: ThreadStatus -- | the thread has finished ThreadFinished :: ThreadStatus -- | the thread is blocked on some resource ThreadBlocked :: BlockReason -> ThreadStatus -- | the thread received an uncaught exception ThreadDied :: ThreadStatus -- | A ThreadId is an abstract type representing a handle to a -- thread. ThreadId is an instance of Eq, Ord and -- Show, where the Ord instance implements an arbitrary -- total ordering over ThreadIds. The Show instance lets -- you convert an arbitrary-valued ThreadId to string form; -- showing a ThreadId value is occasionally useful when debugging -- or diagnosing the behaviour of a concurrent program. -- -- Note: in GHC, if you have a ThreadId, you essentially -- have a pointer to the thread itself. This means the thread itself -- can't be garbage collected until you drop the ThreadId. This -- misfeature will hopefully be corrected at a later date. data ThreadId ThreadId :: ThreadId# -> ThreadId -- | Shared memory locations that support atomic memory transactions. data TVar a TVar :: TVar# RealWorld a -> TVar a -- | A monad supporting atomic memory transactions. newtype STM a STM :: (State# RealWorld -> (# State# RealWorld, a #)) -> STM a data PrimMVar data BlockReason -- | blocked on MVar BlockedOnMVar :: BlockReason -- | blocked on a computation in progress by another thread BlockedOnBlackHole :: BlockReason -- | blocked in throwTo BlockedOnException :: BlockReason -- | blocked in retry in an STM transaction BlockedOnSTM :: BlockReason -- | currently in a foreign call BlockedOnForeignCall :: BlockReason -- | blocked on some other resource. Without -threaded, I/O and -- threadDelay show up as BlockedOnOther, with -- -threaded they show up as BlockedOnMVar. BlockedOnOther :: BlockReason -- | The yield action allows (forces, in a co-operative multitasking -- implementation) a context-switch to any other currently runnable -- threads (if any), and is occasionally useful when implementing -- concurrency abstractions. yield :: IO () -- | Write the supplied value into a TVar. writeTVar :: TVar a -> a -> STM () -- | Unsafely performs IO in the STM monad. Beware: this is a highly -- dangerous thing to do. -- -- unsafeIOToSTM :: IO a -> STM a -- | 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 () -- | A variant of throw that can only be used within the STM -- monad. -- -- Throwing an exception in STM aborts the transaction and -- propagates the exception. If the exception is caught via -- catchSTM, only the changes enclosed by the catch are rolled -- back; changes made outside of catchSTM persist. -- -- If the exception is not caught inside of the STM, it is -- re-thrown by atomically, and the entire STM is rolled -- back. -- -- Although throwSTM has a type that is an instance of the type of -- throw, the two functions are subtly different: -- --
--   throw e    `seq` x  ===> throw e
--   throwSTM e `seq` x  ===> x
--   
-- -- The first example will cause the exception e to be raised, -- whereas the second one won't. In fact, throwSTM will only cause -- an exception to be raised when it is used within the STM monad. -- The throwSTM variant should be used in preference to -- throw to raise an exception within the STM monad because -- it guarantees ordering with respect to other STM operations, -- whereas throw does not. throwSTM :: Exception e => e -> STM a threadStatus :: ThreadId -> IO ThreadStatus -- | Returns the number of the capability on which the thread is currently -- running, and a boolean indicating whether the thread is locked to that -- capability or not. A thread is locked to a capability if it was -- created with forkOn. threadCapability :: ThreadId -> IO (Int, Bool) setUncaughtExceptionHandler :: (SomeException -> IO ()) -> IO () -- | Set the number of Haskell threads that can run truly simultaneously -- (on separate physical processors) at any given time. The number passed -- to forkOn is interpreted modulo this value. The initial value -- is given by the +RTS -N runtime flag. -- -- This is also the number of threads that will participate in parallel -- garbage collection. It is strongly recommended that the number of -- capabilities is not set larger than the number of physical processor -- cores, and it may often be beneficial to leave one or more cores free -- to avoid contention with other processes in the machine. setNumCapabilities :: Int -> IO () -- | Every thread has an allocation counter that tracks how much memory has -- been allocated by the thread. The counter is initialized to zero, and -- setAllocationCounter sets the current value. The allocation -- counter counts *down*, so in the absence of a call to -- setAllocationCounter its value is the negation of the number of -- bytes of memory allocated by the thread. -- -- There are two things that you can do with this counter: -- -- -- -- Allocation accounting is accurate only to about 4Kbytes. setAllocationCounter :: Int64 -> IO () -- | Internal function used by the RTS to run sparks. runSparks :: IO () -- | Retry execution of the current memory transaction because it has seen -- values in TVars which mean that it should not continue (e.g. -- the TVars represent a shared buffer that is now empty). The -- implementation may block the thread until one of the TVars that -- it has read from has been updated. (GHC only) retry :: STM a reportStackOverflow :: IO () reportHeapOverflow :: IO () reportError :: SomeException -> IO () -- | Return the current value stored in a TVar. This is equivalent -- to -- --
--   readTVarIO = atomically . readTVar
--   
-- -- but works much faster, because it doesn't perform a complete -- transaction, it just reads the current value of the TVar. readTVarIO :: TVar a -> IO a -- | Return the current value stored in a TVar. readTVar :: TVar a -> STM a pseq :: a -> b -> b infixr 0 `pseq` par :: a -> b -> b infixr 0 `par` -- | Returns the number of sparks currently in the local spark pool numSparks :: IO Int -- | the value passed to the +RTS -N flag. This is the number of -- Haskell threads that can run truly simultaneously at any given time, -- and is typically set to the number of physical processor cores on the -- machine. -- -- Strictly speaking it is better to use getNumCapabilities, -- because the number of capabilities might vary at runtime. numCapabilities :: Int -- | IO version of newTVar. This is useful for creating -- top-level TVars using unsafePerformIO, because using -- atomically inside unsafePerformIO isn't possible. newTVarIO :: a -> IO (TVar a) -- | Create a new TVar holding a value supplied newTVar :: a -> STM (TVar a) -- | Make a StablePtr that can be passed to the C function -- hs_try_putmvar(). The RTS wants a StablePtr to the -- underlying MVar#, but a StablePtr# can only refer to -- lifted types, so we have to cheat by coercing. newStablePtrPrimMVar :: MVar () -> IO (StablePtr PrimMVar) -- | Returns the ThreadId of the calling thread (GHC only). myThreadId :: IO ThreadId -- | Make a weak pointer to a ThreadId. It can be important to do -- this if you want to hold a reference to a ThreadId while still -- allowing the thread to receive the BlockedIndefinitely family -- of exceptions (e.g. BlockedIndefinitelyOnMVar). Holding a -- normal ThreadId reference will prevent the delivery of -- BlockedIndefinitely exceptions because the reference could be -- used as the target of throwTo at any time, which would unblock -- the thread. -- -- Holding a Weak ThreadId, on the other hand, will not prevent -- the thread from receiving BlockedIndefinitely exceptions. It -- is still possible to throw an exception to a Weak ThreadId, -- but the caller must use deRefWeak first to determine whether -- the thread still exists. mkWeakThreadId :: ThreadId -> IO (Weak ThreadId) -- | labelThread stores a string as identifier for this thread. This -- identifier will be used in the debugging output to make distinction of -- different threads easier (otherwise you only have the thread state -- object's address in the heap). It also emits an event to the RTS -- eventlog. -- -- Other applications like the graphical Concurrent Haskell Debugger -- (http://www.informatik.uni-kiel.de/~fhu/chd/) may choose to -- overload labelThread for their purposes as well. labelThread :: ThreadId -> String -> IO () -- | killThread raises the ThreadKilled exception in the -- given thread (GHC only). -- --
--   killThread tid = throwTo tid ThreadKilled
--   
killThread :: ThreadId -> IO () getUncaughtExceptionHandler :: IO (SomeException -> IO ()) -- | Returns the number of CPUs that the machine has getNumProcessors :: IO Int -- | Returns the number of Haskell threads that can run truly -- simultaneously (on separate physical processors) at any given time. To -- change this value, use setNumCapabilities. getNumCapabilities :: IO Int -- | Return the current value of the allocation counter for the current -- thread. getAllocationCounter :: IO Int64 -- | Like forkIOWithUnmask, but the child thread is pinned to the -- given CPU, as with forkOn. forkOnWithUnmask :: Int -> ((forall a. () => IO a -> IO a) -> IO ()) -> IO ThreadId -- | Like forkIO, but lets you specify on which capability the -- thread should run. Unlike a forkIO thread, a thread created by -- forkOn will stay on the same capability for its entire lifetime -- (forkIO threads can migrate between capabilities according to -- the scheduling policy). forkOn is useful for overriding the -- scheduling policy when you know in advance how best to distribute the -- threads. -- -- The Int argument specifies a capability number (see -- getNumCapabilities). Typically capabilities correspond to -- physical processors, but the exact behaviour is -- implementation-dependent. The value passed to forkOn is -- interpreted modulo the total number of capabilities as returned by -- getNumCapabilities. -- -- GHC note: the number of capabilities is specified by the +RTS -- -N option when the program is started. Capabilities can be fixed -- to actual processor cores with +RTS -qa if the underlying -- operating system supports that, although in practice this is usually -- unnecessary (and may actually degrade performance in some cases - -- experimentation is recommended). forkOn :: Int -> IO () -> IO ThreadId -- | Like forkIO, but the child thread is passed a function that can -- be used to unmask asynchronous exceptions. This function is typically -- used in the following way -- --
--   ... mask_ $ forkIOWithUnmask $ \unmask ->
--                  catch (unmask ...) handler
--   
-- -- so that the exception handler in the child thread is established with -- asynchronous exceptions masked, meanwhile the main body of the child -- thread is executed in the unmasked state. -- -- Note that the unmask function passed to the child thread should only -- be used in that thread; the behaviour is undefined if it is invoked in -- a different thread. forkIOWithUnmask :: ((forall a. () => IO a -> IO a) -> IO ()) -> IO ThreadId -- | Creates a new thread to run the IO computation passed as the -- first argument, and returns the ThreadId of the newly created -- thread. -- -- The new thread will be a lightweight, unbound thread. Foreign -- calls made by this thread are not guaranteed to be made by any -- particular OS thread; if you need foreign calls to be made by a -- particular OS thread, then use forkOS instead. -- -- The new thread inherits the masked state of the parent (see -- mask). -- -- The newly created thread has an exception handler that discards the -- exceptions BlockedIndefinitelyOnMVar, -- BlockedIndefinitelyOnSTM, and ThreadKilled, and passes -- all other exceptions to the uncaught exception handler. forkIO :: IO () -> IO ThreadId -- | Enables the allocation counter to be treated as a limit for the -- current thread. When the allocation limit is enabled, if the -- allocation counter counts down below zero, the thread will be sent the -- AllocationLimitExceeded asynchronous exception. When this -- happens, the counter is reinitialised (by default to 100K, but tunable -- with the +RTS -xq option) so that it can handle the exception -- and perform any necessary clean up. If it exhausts this additional -- allowance, another AllocationLimitExceeded exception is sent, -- and so forth. Like other asynchronous exceptions, the -- AllocationLimitExceeded exception is deferred while the thread -- is inside mask or an exception handler in catch. -- -- Note that memory allocation is unrelated to live memory, also -- known as heap residency. A thread can allocate a large amount -- of memory and retain anything between none and all of it. It is better -- to think of the allocation limit as a limit on CPU time, rather -- than a limit on memory. -- -- Compared to using timeouts, allocation limits don't count time spent -- blocked or in foreign calls. enableAllocationLimit :: IO () -- | Disable allocation limit processing for the current thread. disableAllocationLimit :: IO () childHandler :: SomeException -> IO () -- | Exception handling within STM actions. -- -- catchSTM m f catches any exception thrown by -- m using throwSTM, using the function f to -- handle the exception. If an exception is thrown, any changes made by -- m are rolled back, but changes prior to m persist. catchSTM :: Exception e => STM a -> (e -> STM a) -> STM a -- | Perform a series of STM actions atomically. -- -- Using atomically inside an unsafePerformIO or -- unsafeInterleaveIO subverts some of guarantees that STM -- provides. It makes it possible to run a transaction inside of another -- transaction, depending on when the thunk is evaluated. If a nested -- transaction is attempted, an exception is thrown by the runtime. It is -- possible to safely use atomically inside unsafePerformIO -- or unsafeInterleaveIO, but the typechecker does not rule out -- programs that may attempt nested transactions, meaning that the -- programmer must take special care to prevent these. -- -- However, there are functions for creating transactional variables that -- can always be safely called in unsafePerformIO. See: -- newTVarIO, newTChanIO, newBroadcastTChanIO, -- newTQueueIO, newTBQueueIO, and newTMVarIO. -- -- Using unsafePerformIO inside of atomically is also -- dangerous but for different reasons. See unsafeIOToSTM for more -- on this. atomically :: STM a -> IO a -- | A value of type Dynamic is an object encapsulated together with -- its type. -- -- A Dynamic may only represent a monomorphic value; an attempt to -- create a value of type Dynamic from a polymorphically-typed -- expression will result in an ambiguity error (see toDyn). -- -- Showing a value of type Dynamic returns a pretty-printed -- representation of the object's type; useful for debugging. data Dynamic [Dynamic] :: forall a. TypeRep a -> a -> Dynamic -- | Converts a Dynamic object back into an ordinary Haskell value -- of the correct type. See also fromDyn. fromDynamic :: Typeable a => Dynamic -> Maybe a -- | Converts a Dynamic object back into an ordinary Haskell value -- of the correct type. See also fromDynamic. fromDyn :: Typeable a => Dynamic -> a -> a dynTypeRep :: Dynamic -> SomeTypeRep dynApply :: Dynamic -> Dynamic -> Maybe Dynamic dynApp :: Dynamic -> Dynamic -> Dynamic -- | Superclass for asynchronous exceptions. data SomeAsyncException SomeAsyncException :: e -> SomeAsyncException -- | An abstract type that contains a value for each variant of -- IOException. data IOErrorType AlreadyExists :: IOErrorType NoSuchThing :: IOErrorType ResourceBusy :: IOErrorType ResourceExhausted :: IOErrorType EOF :: IOErrorType IllegalOperation :: IOErrorType PermissionDenied :: IOErrorType UserError :: IOErrorType UnsatisfiedConstraints :: IOErrorType SystemError :: IOErrorType ProtocolError :: IOErrorType OtherError :: IOErrorType InvalidArgument :: IOErrorType InappropriateType :: IOErrorType HardwareFault :: IOErrorType UnsupportedOperation :: IOErrorType TimeExpired :: IOErrorType ResourceVanished :: IOErrorType Interrupted :: IOErrorType -- | The exception thrown when an infinite cycle is detected in -- fixIO. data FixIOException FixIOException :: FixIOException -- | Defines the exit codes that a program can return. data ExitCode -- | indicates successful termination; ExitSuccess :: ExitCode -- | indicates program failure with an exit code. The exact interpretation -- of the code is operating-system dependent. In particular, some values -- may be prohibited (e.g. 0 on a POSIX-compliant system). ExitFailure :: Int -> ExitCode -- | There are no runnable threads, so the program is deadlocked. The -- Deadlock exception is raised in the main thread only. data Deadlock Deadlock :: Deadlock -- | 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 -- | 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 -- | 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 -- | 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: -- -- HeapOverflow :: AsyncException -- | This exception is raised by another thread calling killThread, -- or by the system if it needs to terminate the thread for some reason. ThreadKilled :: AsyncException -- | This exception is raised by default in the main thread of the program -- when the user requests to terminate the program via the usual -- mechanism(s) (e.g. Control-C in the console). UserInterrupt :: AsyncException -- | assert was applied to False. newtype AssertionFailed AssertionFailed :: String -> AssertionFailed -- | Exceptions generated by array operations data ArrayException -- | An attempt was made to index an array outside its declared bounds. IndexOutOfBounds :: String -> ArrayException -- | An attempt was made to evaluate an element of an array that had not -- been initialized. UndefinedElement :: String -> ArrayException -- | This thread has exceeded its allocation limit. See -- setAllocationCounter and enableAllocationLimit. data AllocationLimitExceeded AllocationLimitExceeded :: AllocationLimitExceeded untangle :: Addr# -> String -> String stackOverflow :: SomeException ioException :: IOException -> IO a -- | Raise an IOException in the IO monad. ioError :: IOError -> IO a heapOverflow :: SomeException cannotCompactPinned :: SomeException cannotCompactMutable :: SomeException cannotCompactFunction :: SomeException blockedIndefinitelyOnSTM :: SomeException blockedIndefinitelyOnMVar :: SomeException asyncExceptionToException :: Exception e => e -> SomeException asyncExceptionFromException :: Exception e => SomeException -> Maybe e allocationLimitExceeded :: SomeException -- | Strict version of modifyIORef modifyIORef' :: IORef a -> (a -> a) -> IO () -- | Mutate the contents of an IORef. -- -- Be warned that modifyIORef does not apply the function -- strictly. This means if the program calls modifyIORef many -- times, but seldom uses the value, thunks will pile up in memory -- resulting in a space leak. This is a common mistake made when using an -- IORef as a counter. For example, the following will likely produce a -- stack overflow: -- --
--   ref <- newIORef 0
--   replicateM_ 1000000 $ modifyIORef ref (+1)
--   readIORef ref >>= print
--   
-- -- To avoid this problem, use modifyIORef' instead. modifyIORef :: IORef a -> (a -> a) -> IO () -- | Make a Weak pointer to an IORef, using the second -- argument as a finalizer to run when IORef is garbage-collected mkWeakIORef :: IORef a -> IO () -> IO (Weak (IORef a)) -- | Variant of writeIORef with the "barrier to reordering" property -- that atomicModifyIORef has. atomicWriteIORef :: IORef a -> a -> IO () -- | Atomically modifies the contents of an IORef. -- -- This function is useful for using IORef in a safe way in a -- multithreaded program. If you only have one IORef, then using -- atomicModifyIORef to access and modify it will prevent race -- conditions. -- -- Extending the atomicity to multiple IORefs is problematic, so -- it is recommended that if you need to do anything more complicated -- then using MVar instead is a good idea. -- -- atomicModifyIORef does not apply the function strictly. This is -- important to know even if all you are doing is replacing the value. -- For example, this will leak memory: -- --
--   ref <- newIORef '1'
--   forever $ atomicModifyIORef ref (\_ -> ('2', ()))
--   
-- -- Use atomicModifyIORef' or atomicWriteIORef to avoid this -- problem. atomicModifyIORef :: IORef a -> (a -> (a, b)) -> IO b -- | 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) -- | 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) -- | 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) -- | 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) -- | 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 () -- | 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 -- | This function ensures that the foreign object in question is alive at -- the given place in the sequence of IO actions. However, this comes -- with a significant caveat: the contract above does not hold if GHC can -- demonstrate that the code preceeding touchForeignPtr diverges -- (e.g. by looping infinitely or throwing an exception). For this -- reason, you are strongly advised to use instead withForeignPtr -- where possible. -- -- Also, 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 () -- | 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 -- | 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 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) -- | 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) -- | Causes the finalizers associated with a foreign pointer to be run -- immediately. The foreign pointer must not be used again after this -- function is called. If the foreign pointer does not support -- finalizers, this is a no-op. finalizeForeignPtr :: ForeignPtr a -> IO () -- | This function casts a ForeignPtr parameterised by one type into -- another type. castForeignPtr :: ForeignPtr a -> ForeignPtr b -- | Like addForeignPtrFinalizer but the finalizer is passed an -- additional environment parameter. addForeignPtrFinalizerEnv :: FinalizerEnvPtr env a -> Ptr env -> ForeignPtr a -> IO () -- | 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 () -- | A mutable variable in the IO monad data IORef a -- | Write a new value into an IORef writeIORef :: IORef a -> a -> IO () -- | Read the value of an IORef readIORef :: IORef a -> IO a -- | Build a new IORef newIORef :: a -> IO (IORef a) -- | Strict version of atomicModifyIORef. This forces both the value -- stored in the IORef and the value returned. The new value is -- installed in the IORef before the returned value is forced. So -- --
--   atomicModifyIORef' ref (x -> (x+1, undefined))
--   
-- -- will increment the IORef and then throw an exception in the -- calling thread. atomicModifyIORef' :: IORef a -> (a -> (a, b)) -> IO b -- | 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 -- | 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 -- | Like uninterruptibleMask, but does not pass a restore -- action to the argument. uninterruptibleMask_ :: IO 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 -- | 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 -- | Embed a strict state thread in an IO action. The -- RealWorld parameter indicates that the internal state used by -- the ST computation is a special one supplied by the IO -- monad, and thus distinct from those used by invocations of -- runST. stToIO :: ST RealWorld a -> IO a -- | Like mask, but does not pass a restore action to the -- argument. mask_ :: 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 new thread in an unmasked state use -- forkIOWithUnmask. mask :: ((forall a. () => IO a -> IO a) -> IO b) -> IO b -- | 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 -- | Returns the MaskingState for the current thread. getMaskingState :: IO MaskingState -- | Evaluate the argument to weak head normal form. -- -- evaluate is typically used to uncover any exceptions that a -- lazy value may contain, and possibly handle them. -- -- evaluate only evaluates to weak head normal form. If -- deeper evaluation is needed, the force function from -- Control.DeepSeq may be handy: -- --
--   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 -- | This is the simplest of the exception-catching functions. It takes a -- single argument, runs it, and if an exception is raised the "handler" -- is executed, with the value of the exception passed as an argument. -- Otherwise, the result is returned as normal. For example: -- --
--   catch (readFile f)
--         (\e -> do let err = show (e :: IOException)
--                   hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err)
--                   return "")
--   
-- -- Note that we have to give a type signature to e, or the -- program will not typecheck as the type is ambiguous. While it is -- possible to catch exceptions of any type, see the section "Catching -- all exceptions" (in Control.Exception) for an explanation of -- the problems with doing so. -- -- For catching exceptions in pure (non-IO) expressions, see the -- function evaluate. -- -- Note that due to Haskell's unspecified evaluation order, an expression -- may throw one of several possible exceptions: consider the expression -- (error "urk") + (1 `div` 0). Does the expression throw -- ErrorCall "urk", or DivideByZero? -- -- The answer is "it might throw either"; the choice is -- non-deterministic. If you are catching any type of exception then you -- might catch either. If you are calling catch with type IO -- Int -> (ArithException -> IO Int) -> IO Int then the -- handler may get run with DivideByZero as an argument, or an -- ErrorCall "urk" exception may be propagated further up. If -- you call it again, you might get the opposite behaviour. This is ok, -- because catch is an IO computation. catch :: Exception e => IO a -> (e -> IO a) -> IO a -- | 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 IOError :: Maybe Handle -> IOErrorType -> String -> String -> Maybe CInt -> Maybe FilePath -> IOException [ioe_handle] :: IOException -> Maybe Handle [ioe_type] :: IOException -> IOErrorType [ioe_location] :: IOException -> String [ioe_description] :: IOException -> String [ioe_errno] :: IOException -> Maybe CInt [ioe_filename] :: IOException -> Maybe FilePath -- | The Haskell 2010 type for exceptions in the IO monad. Any I/O -- operation may raise an IOException instead of returning a -- result. For a more general type of exception, including also those -- that arise in pure code, see Exception. -- -- In Haskell 2010, this is an opaque type. type IOError = IOException -- | Construct an IOException value with a string describing the -- error. The fail method of the IO instance of the -- Monad class raises a userError, thus: -- --
--   instance Monad IO where
--     ...
--     fail s = ioError (userError s)
--   
userError :: String -> IOError unsupportedOperation :: IOError -- | 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 pattern ErrorCall :: String -> ErrorCall -- | Throw an exception. Exceptions may be thrown from purely functional -- code, but may only be caught within the IO monad. throw :: forall (r :: RuntimeRep) (a :: TYPE r) e. Exception e => e -> a -- | 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 -- | Arithmetic exceptions. data ArithException Overflow :: ArithException Underflow :: ArithException LossOfPrecision :: ArithException DivideByZero :: ArithException Denormal :: ArithException RatioZeroDenominator :: ArithException -- | A quantified type representation. type TypeRep = SomeTypeRep -- | Observe the type constructor of a quantified type representation. typeRepTyCon :: TypeRep -> TyCon -- | Takes a value of type a and returns a concrete representation -- of that type. typeRepFingerprint :: TypeRep -> Fingerprint -- | Observe the argument types of a type representation typeRepArgs :: TypeRep -> [TypeRep] -- | Takes a value of type a and returns a concrete representation -- of that type. typeRep :: forall {k} proxy (a :: k). Typeable a => proxy a -> TypeRep typeOf7 :: Typeable t => t a b c d e f g -> TypeRep typeOf6 :: Typeable t => t a b c d e f -> TypeRep typeOf5 :: Typeable t => t a b c d e -> TypeRep typeOf4 :: Typeable t => t a b c d -> TypeRep typeOf3 :: Typeable t => t a b c -> TypeRep typeOf2 :: Typeable t => t a b -> TypeRep typeOf1 :: Typeable t => t a -> TypeRep -- | Observe a type representation for the type of a value. typeOf :: Typeable a => a -> TypeRep -- | Splits a type constructor application. Note that if the type -- constructor is polymorphic, this will not return the kinds that were -- used. splitTyConApp :: TypeRep -> (TyCon, [TypeRep]) -- | Show a type representation showsTypeRep :: TypeRep -> ShowS -- | Force a TypeRep to normal form. rnfTypeRep :: TypeRep -> () -- | Build a function type. mkFunTy :: TypeRep -> TypeRep -> TypeRep -- | Cast over k1 -> k2 -> k3 gcast2 :: forall {k1} {k2} {k3} c (t :: k2 -> k3 -> k1) (t' :: k2 -> k3 -> k1) (a :: k2) (b :: k3). (Typeable t, Typeable t') => c (t a b) -> Maybe (c (t' a b)) -- | Cast over k1 -> k2 gcast1 :: forall {k1} {k2} c (t :: k2 -> k1) (t' :: k2 -> k1) (a :: k2). (Typeable t, Typeable t') => c (t a) -> Maybe (c (t' a)) -- | A flexible variation parameterised in a type constructor gcast :: forall {k} (a :: k) (b :: k) c. (Typeable a, Typeable b) => c a -> Maybe (c b) -- | Applies a type to a function type. Returns: Just u if the -- first argument represents a function of type t -> u and -- the second argument represents a function of type t. -- Otherwise, returns Nothing. funResultTy :: TypeRep -> TypeRep -> Maybe TypeRep -- | Extract a witness of equality of two types eqT :: forall {k} (a :: k) (b :: k). (Typeable a, Typeable b) => Maybe (a :~: b) -- | The type-safe cast operation cast :: (Typeable a, Typeable b) => a -> Maybe b tyConPackage :: TyCon -> String tyConName :: TyCon -> String tyConModule :: TyCon -> String tyConFingerprint :: TyCon -> Fingerprint trLiftedRep :: TypeRep ('BoxedRep 'Lifted) rnfTyCon :: TyCon -> () -- | The Const functor. newtype Const a (b :: k) Const :: a -> Const a (b :: k) [getConst] :: Const a (b :: k) -> a -- | Map each element of a structure to an Applicative action, -- evaluate these actions from left to right, and ignore the results. For -- a version that doesn't ignore the results see traverse. -- -- traverse_ is just like mapM_, but generalised to -- Applicative actions. -- --

Examples

-- -- Basic usage: -- --
--   >>> traverse_ print ["Hello", "world", "!"]
--   "Hello"
--   "world"
--   "!"
--   
traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f () -- | 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. -- -- sequence_ is just like sequenceA_, but specialised to -- monadic actions. sequence_ :: (Foldable t, Monad m) => t (m a) -> m () -- | Evaluate each action in the structure from left to right, and ignore -- the results. For a version that doesn't ignore the results see -- sequenceA. -- -- sequenceA_ is just like sequence_, but generalised to -- Applicative actions. -- --

Examples

-- -- Basic usage: -- --
--   >>> sequenceA_ [print "Hello", print "world", print "!"]
--   "Hello"
--   "world"
--   "!"
--   
sequenceA_ :: (Foldable t, Applicative f) => t (f a) -> f () -- | 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. -- --

Examples

-- -- Basic usage: -- --
--   >>> or []
--   False
--   
-- --
--   >>> or [True]
--   True
--   
-- --
--   >>> or [False]
--   False
--   
-- --
--   >>> or [True, True, False]
--   True
--   
-- --
--   >>> or (True : repeat False) -- Infinite list [True,False,False,False,...
--   True
--   
-- --
--   >>> or (repeat False)
--   * Hangs forever *
--   
or :: Foldable t => t Bool -> Bool -- | notElem is the negation of elem. -- --

Examples

-- -- Basic usage: -- --
--   >>> 3 `notElem` []
--   True
--   
-- --
--   >>> 3 `notElem` [1,2]
--   True
--   
-- --
--   >>> 3 `notElem` [1,2,3,4,5]
--   False
--   
-- -- For infinite structures, notElem terminates if the value exists -- at a finite distance from the left side of the structure: -- --
--   >>> 3 `notElem` [1..]
--   False
--   
-- --
--   >>> 3 `notElem` ([4..] ++ [3])
--   * Hangs forever *
--   
notElem :: (Foldable t, Eq a) => a -> t a -> Bool infix 4 `notElem` -- | The sum of a collection of actions, generalizing concat. -- -- msum is just like asum, but specialised to -- MonadPlus. msum :: (Foldable t, MonadPlus m) => t (m a) -> m a -- | The least element of a non-empty structure with respect to the given -- comparison function. -- --

Examples

-- -- Basic usage: -- --
--   >>> minimumBy (compare `on` length) ["Hello", "World", "!", "Longest", "bar"]
--   "!"
--   
-- -- WARNING: This function is partial for possibly-empty structures like -- lists. minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a -- | The largest element of a non-empty structure with respect to the given -- comparison function. -- --

Examples

-- -- Basic usage: -- --
--   >>> maximumBy (compare `on` length) ["Hello", "World", "!", "Longest", "bar"]
--   "Longest"
--   
-- -- WARNING: This function is partial for possibly-empty structures like -- lists. maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a -- | 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. -- -- mapM_ is just like traverse_, but specialised to monadic -- actions. mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m () -- | for_ is traverse_ with its arguments flipped. For a -- version that doesn't ignore the results see for. This is -- forM_ generalised to Applicative actions. -- -- for_ is just like forM_, but generalised to -- Applicative actions. -- --

Examples

-- -- Basic usage: -- --
--   >>> for_ [1..4] print
--   1
--   2
--   3
--   4
--   
for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f () -- | forM_ is mapM_ with its arguments flipped. For a version -- that doesn't ignore the results see forM. -- -- forM_ is just like for_, but specialised to monadic -- actions. forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m () -- | Right-to-left monadic fold over the elements of a structure. -- -- Given a structure t with elements (a, b, c, ..., x, -- y), the result of a fold with an operator function f is -- equivalent to: -- --
--   foldrM f z t = do
--       yy <- f y z
--       xx <- f x yy
--       ...
--       bb <- f b cc
--       aa <- f a bb
--       return aa -- Just @return z@ when the structure is empty
--   
-- -- For a Monad m, given two functions f1 :: a -> m b -- and f2 :: b -> m c, their Kleisli composition (f1 -- >=> f2) :: a -> m c is defined by: -- --
--   (f1 >=> f2) a = f1 a >>= f2
--   
-- -- Another way of thinking about foldrM is that it amounts to an -- application to z of a Kleisli composition: -- --
--   foldrM f z t = f y >=> f x >=> ... >=> f b >=> f a $ z
--   
-- -- The monadic effects of foldrM are sequenced from right to -- left, and e.g. folds of infinite lists will diverge. -- -- If at some step the bind operator (>>=) -- short-circuits (as with, e.g., mzero in a MonadPlus), -- the evaluated effects will be from a tail of the element sequence. If -- you want to evaluate the monadic effects in left-to-right order, or -- perhaps be able to short-circuit after an initial sequence of -- elements, you'll need to use foldlM instead. -- -- If the monadic effects don't short-circuit, the outermost application -- of f is to the leftmost element a, so that, ignoring -- effects, the result looks like a right fold: -- --
--   a `f` (b `f` (c `f` (... (x `f` (y `f` z))))).
--   
-- --

Examples

-- -- Basic usage: -- --
--   >>> let f i acc = do { print i ; return $ i : acc }
--   
--   >>> foldrM f [] [0..3]
--   3
--   2
--   1
--   0
--   [0,1,2,3]
--   
foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b -- | Left-to-right monadic fold over the elements of a structure. -- -- Given a structure t with elements (a, b, ..., w, x, -- y), the result of a fold with an operator function f is -- equivalent to: -- --
--   foldlM f z t = do
--       aa <- f z a
--       bb <- f aa b
--       ...
--       xx <- f ww x
--       yy <- f xx y
--       return yy -- Just @return z@ when the structure is empty
--   
-- -- For a Monad m, given two functions f1 :: a -> m b -- and f2 :: b -> m c, their Kleisli composition (f1 -- >=> f2) :: a -> m c is defined by: -- --
--   (f1 >=> f2) a = f1 a >>= f2
--   
-- -- Another way of thinking about foldlM is that it amounts to an -- application to z of a Kleisli composition: -- --
--   foldlM f z t =
--       flip f a >=> flip f b >=> ... >=> flip f x >=> flip f y $ z
--   
-- -- The monadic effects of foldlM are sequenced from left to -- right. -- -- If at some step the bind operator (>>=) -- short-circuits (as with, e.g., mzero in a MonadPlus), -- the evaluated effects will be from an initial segment of the element -- sequence. If you want to evaluate the monadic effects in right-to-left -- order, or perhaps be able to short-circuit after processing a tail of -- the sequence of elements, you'll need to use foldrM instead. -- -- If the monadic effects don't short-circuit, the outermost application -- of f is to the rightmost element y, so that, -- ignoring effects, the result looks like a left fold: -- --
--   ((((z `f` a) `f` b) ... `f` w) `f` x) `f` y
--   
-- --

Examples

-- -- Basic usage: -- --
--   >>> let f a e = do { print e ; return $ e : a }
--   
--   >>> foldlM f [] [0..3]
--   0
--   1
--   2
--   3
--   [3,2,1,0]
--   
foldlM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | The find function takes a predicate and a structure and returns -- the leftmost element of the structure matching the predicate, or -- Nothing if there is no such element. -- --

Examples

-- -- Basic usage: -- --
--   >>> find (> 42) [0, 5..]
--   Just 45
--   
-- --
--   >>> find (> 12) [1..7]
--   Nothing
--   
find :: Foldable t => (a -> Bool) -> t a -> Maybe a -- | Map a function over all the elements of a container and concatenate -- the resulting lists. -- --

Examples

-- -- Basic usage: -- --
--   >>> concatMap (take 3) [[1..], [10..], [100..], [1000..]]
--   [1,2,3,10,11,12,100,101,102,1000,1001,1002]
--   
-- --
--   >>> concatMap (take 3) (Just [1..])
--   [1,2,3]
--   
concatMap :: Foldable t => (a -> [b]) -> t a -> [b] -- | The concatenation of all the elements of a container of lists. -- --

Examples

-- -- Basic usage: -- --
--   >>> concat (Just [1, 2, 3])
--   [1,2,3]
--   
-- --
--   >>> concat (Left 42)
--   []
--   
-- --
--   >>> concat [[1, 2, 3], [4, 5], [6], []]
--   [1,2,3,4,5,6]
--   
concat :: Foldable t => t [a] -> [a] -- | The sum of a collection of actions, generalizing concat. -- -- asum is just like msum, but generalised to -- Alternative. -- --

Examples

-- -- Basic usage: -- --
--   >>> asum [Just "Hello", Nothing, Just "World"]
--   Just "Hello"
--   
asum :: (Foldable t, Alternative f) => t (f a) -> f a -- | Determines whether any element of the structure satisfies the -- predicate. -- --

Examples

-- -- Basic usage: -- --
--   >>> any (> 3) []
--   False
--   
-- --
--   >>> any (> 3) [1,2]
--   False
--   
-- --
--   >>> any (> 3) [1,2,3,4,5]
--   True
--   
-- --
--   >>> any (> 3) [1..]
--   True
--   
-- --
--   >>> any (> 3) [0, -1..]
--   * Hangs forever *
--   
any :: 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. -- --

Examples

-- -- Basic usage: -- --
--   >>> and []
--   True
--   
-- --
--   >>> and [True]
--   True
--   
-- --
--   >>> and [False]
--   False
--   
-- --
--   >>> and [True, True, False]
--   False
--   
-- --
--   >>> and (False : repeat True) -- Infinite list [False,True,True,True,...
--   False
--   
-- --
--   >>> and (repeat True)
--   * Hangs forever *
--   
and :: Foldable t => t Bool -> Bool -- | Determines whether all elements of the structure satisfy the -- predicate. -- --

Examples

-- -- Basic usage: -- --
--   >>> all (> 3) []
--   True
--   
-- --
--   >>> all (> 3) [1,2]
--   False
--   
-- --
--   >>> all (> 3) [1,2,3,4,5]
--   False
--   
-- --
--   >>> all (> 3) [1..]
--   False
--   
-- --
--   >>> all (> 3) [4..]
--   * Hangs forever *
--   
all :: Foldable t => (a -> Bool) -> t a -> Bool -- | The zipWith7 function takes a function which combines seven -- elements, as well as seven lists and returns a list of their -- point-wise combination, analogous to zipWith. It is capable of -- list fusion, but it is restricted to its first list argument and its -- resulting list. zipWith7 :: (a -> b -> c -> d -> e -> f -> g -> h) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [h] -- | The zipWith6 function takes a function which combines six -- elements, as well as six lists and returns a list of their point-wise -- combination, analogous to zipWith. It is capable of list -- fusion, but it is restricted to its first list argument and its -- resulting list. zipWith6 :: (a -> b -> c -> d -> e -> f -> g) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -- | The zipWith5 function takes a function which combines five -- elements, as well as five lists and returns a list of their point-wise -- combination, analogous to zipWith. It is capable of list -- fusion, but it is restricted to its first list argument and its -- resulting list. zipWith5 :: (a -> b -> c -> d -> e -> f) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -- | The zipWith4 function takes a function which combines four -- elements, as well as four lists and returns a list of their point-wise -- combination, analogous to zipWith. It is capable of list -- fusion, but it is restricted to its first list argument and its -- resulting list. zipWith4 :: (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e] -- | The zip7 function takes seven lists and returns a list of -- seven-tuples, analogous to zip. It is capable of list fusion, -- but it is restricted to its first list argument and its resulting -- list. zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a, b, c, d, e, f, g)] -- | The zip6 function takes six lists and returns a list of -- six-tuples, analogous to zip. It is capable of list fusion, but -- it is restricted to its first list argument and its resulting list. zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a, b, c, d, e, f)] -- | The zip5 function takes five lists and returns a list of -- five-tuples, analogous to zip. It is capable of list fusion, -- but it is restricted to its first list argument and its resulting -- list. zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a, b, c, d, e)] -- | The zip4 function takes four lists and returns a list of -- quadruples, analogous to zip. It is capable of list fusion, but -- it is restricted to its first list argument and its resulting list. zip4 :: [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)] -- | 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] -- | The unzip7 function takes a list of seven-tuples and returns -- seven lists, analogous to unzip. unzip7 :: [(a, b, c, d, e, f, g)] -> ([a], [b], [c], [d], [e], [f], [g]) -- | The unzip6 function takes a list of six-tuples and returns six -- lists, analogous to unzip. unzip6 :: [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f]) -- | The unzip5 function takes a list of five-tuples and returns -- five lists, analogous to unzip. unzip5 :: [(a, b, c, d, e)] -> ([a], [b], [c], [d], [e]) -- | The unzip4 function takes a list of quadruples and returns four -- lists, analogous to unzip. unzip4 :: [(a, b, c, d)] -> ([a], [b], [c], [d]) -- | unwords is an inverse operation to words. It joins words -- with separating spaces. -- --
--   >>> unwords ["Lorem", "ipsum", "dolor"]
--   "Lorem ipsum dolor"
--   
unwords :: [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 -- | The unionBy function is the non-overloaded version of -- union. unionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a] -- | The union function returns the list union of the two lists. For -- example, -- --
--   >>> "dog" `union` "cow"
--   "dogcw"
--   
-- -- Duplicates, and elements of the first list, are removed from the the -- second list, but if the first list contains duplicates, so will the -- result. It is a special case of unionBy, which allows the -- programmer to supply their own equality test. union :: Eq a => [a] -> [a] -> [a] -- | The unfoldr function is a `dual' to foldr: while -- foldr reduces a list to a summary value, unfoldr builds -- a list from a seed value. The function takes the element and returns -- Nothing if it is done producing the list or returns Just -- (a,b), in which case, a is a prepended to the list -- and b is used as the next element in a recursive call. For -- example, -- --
--   iterate f == unfoldr (\x -> Just (x, f x))
--   
-- -- In some cases, unfoldr can undo a foldr operation: -- --
--   unfoldr f' (foldr f z xs) == xs
--   
-- -- if the following holds: -- --
--   f' (f x y) = Just (x,y)
--   f' z       = Nothing
--   
-- -- A simple use of unfoldr: -- --
--   >>> unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10
--   [10,9,8,7,6,5,4,3,2,1]
--   
unfoldr :: (b -> Maybe (a, b)) -> b -> [a] -- | The transpose function transposes the rows and columns of its -- argument. For example, -- --
--   >>> transpose [[1,2,3],[4,5,6]]
--   [[1,4],[2,5],[3,6]]
--   
-- -- If some of the rows are shorter than the following rows, their -- elements are skipped: -- --
--   >>> transpose [[10,11],[20],[],[30,31,32]]
--   [[10,20,30],[11,31],[32]]
--   
transpose :: [[a]] -> [[a]] -- | <math>. The tails function returns all final segments of -- the argument, longest first. For example, -- --
--   >>> tails "abc"
--   ["abc","bc","c",""]
--   
-- -- Note that tails has the following strictness property: -- tails _|_ = _|_ : _|_ tails :: [a] -> [[a]] -- | The subsequences function returns the list of all subsequences -- of the argument. -- --
--   >>> subsequences "abc"
--   ["","a","b","ab","c","ac","bc","abc"]
--   
subsequences :: [a] -> [[a]] -- | <math>. The stripPrefix function drops the given prefix -- from a list. It returns Nothing if the list did not start with -- the prefix given, or Just the list after the prefix, if it -- does. -- --
--   >>> stripPrefix "foo" "foobar"
--   Just "bar"
--   
-- --
--   >>> stripPrefix "foo" "foo"
--   Just ""
--   
-- --
--   >>> stripPrefix "foo" "barfoo"
--   Nothing
--   
-- --
--   >>> stripPrefix "foo" "barfoobaz"
--   Nothing
--   
stripPrefix :: Eq a => [a] -> [a] -> Maybe [a] -- | Sort a list by comparing the results of a key function applied to each -- element. sortOn f is equivalent to sortBy (comparing -- f), but has the performance advantage of only evaluating -- f once for each element in the input list. This is called the -- decorate-sort-undecorate paradigm, or Schwartzian transform. -- -- Elements are arranged from lowest to highest, keeping duplicates in -- the order they appeared in the input. -- --
--   >>> sortOn fst [(2, "world"), (4, "!"), (1, "Hello")]
--   [(1,"Hello"),(2,"world"),(4,"!")]
--   
sortOn :: Ord b => (a -> b) -> [a] -> [a] -- | The sortBy function is the non-overloaded version of -- sort. -- --
--   >>> sortBy (\(a,_) (b,_) -> compare a b) [(2, "world"), (4, "!"), (1, "Hello")]
--   [(1,"Hello"),(2,"world"),(4,"!")]
--   
sortBy :: (a -> a -> Ordering) -> [a] -> [a] -- | The sort function implements a stable sorting algorithm. It is -- a special case of sortBy, which allows the programmer to supply -- their own comparison function. -- -- Elements are arranged from lowest to highest, keeping duplicates in -- the order they appeared in the input. -- --
--   >>> sort [1,6,4,3,2,5]
--   [1,2,3,4,5,6]
--   
sort :: Ord a => [a] -> [a] -- | Produce singleton list. -- --
--   >>> singleton True
--   [True]
--   
singleton :: a -> [a] -- | The permutations function returns the list of all permutations -- of the argument. -- --
--   >>> permutations "abc"
--   ["abc","bac","cba","bca","cab","acb"]
--   
permutations :: [a] -> [[a]] -- | The partition function takes a predicate and a list, and -- returns the pair of lists of elements which do and do not satisfy the -- predicate, respectively; i.e., -- --
--   partition p xs == (filter p xs, filter (not . p) xs)
--   
-- --
--   >>> partition (`elem` "aeiou") "Hello World!"
--   ("eoo","Hll Wrld!")
--   
partition :: (a -> Bool) -> [a] -> ([a], [a]) -- | The nubBy function behaves just like nub, except it uses -- a user-supplied equality predicate instead of the overloaded == -- function. -- --
--   >>> nubBy (\x y -> mod x 3 == mod y 3) [1,2,4,5,6]
--   [1,2,6]
--   
nubBy :: (a -> a -> Bool) -> [a] -> [a] -- | <math>. 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 -- equality test. -- --
--   >>> nub [1,2,3,4,3,2,1,2,4,3,5]
--   [1,2,3,4,5]
--   
nub :: Eq a => [a] -> [a] -- | 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] -- | The isSuffixOf function takes two lists and returns True -- iff the first list is a suffix of the second. The second list must be -- finite. -- --
--   >>> "ld!" `isSuffixOf` "Hello World!"
--   True
--   
-- --
--   >>> "World" `isSuffixOf` "Hello World!"
--   False
--   
isSuffixOf :: Eq a => [a] -> [a] -> Bool -- | <math>. The isPrefixOf function takes two lists and -- returns True iff the first list is a prefix of the second. -- --
--   >>> "Hello" `isPrefixOf` "Hello World!"
--   True
--   
-- --
--   >>> "Hello" `isPrefixOf` "Wello Horld!"
--   False
--   
isPrefixOf :: Eq a => [a] -> [a] -> Bool -- | The isInfixOf function takes two lists and returns True -- iff the first list is contained, wholly and intact, anywhere within -- the second. -- --
--   >>> isInfixOf "Haskell" "I really like Haskell."
--   True
--   
-- --
--   >>> isInfixOf "Ial" "I really like Haskell."
--   False
--   
isInfixOf :: Eq a => [a] -> [a] -> Bool -- | <math>. The intersperse function takes an element and a -- list and `intersperses' that element between the elements of the list. -- For example, -- --
--   >>> intersperse ',' "abcde"
--   "a,b,c,d,e"
--   
intersperse :: a -> [a] -> [a] -- | The intersectBy function is the non-overloaded version of -- intersect. intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a] -- | The intersect function takes the list intersection of two -- lists. For example, -- --
--   >>> [1,2,3,4] `intersect` [2,4,6,8]
--   [2,4]
--   
-- -- If the first list contains duplicates, so will the result. -- --
--   >>> [1,2,2,3,4] `intersect` [6,4,4,2]
--   [2,2,4]
--   
-- -- It is a special case of intersectBy, which allows the -- programmer to supply their own equality test. If the element is found -- in both the first and the second list, the element from the first list -- will be used. intersect :: Eq a => [a] -> [a] -> [a] -- | intercalate xs xss is equivalent to (concat -- (intersperse xs xss)). It inserts the list xs in -- between the lists in xss and concatenates the result. -- --
--   >>> intercalate ", " ["Lorem", "ipsum", "dolor"]
--   "Lorem, ipsum, dolor"
--   
intercalate :: [a] -> [[a]] -> [a] -- | <math>. The non-overloaded version of insert. insertBy :: (a -> a -> Ordering) -> a -> [a] -> [a] -- | <math>. The insert function takes an element and a list -- and inserts the element into the list at the first position where it -- is less than or equal to the next element. In particular, if the list -- is sorted before the call, the result will also be sorted. It is a -- special case of insertBy, which allows the programmer to supply -- their own comparison function. -- --
--   >>> insert 4 [1,2,3,5,6,7]
--   [1,2,3,4,5,6,7]
--   
insert :: Ord a => a -> [a] -> [a] -- | The inits function returns all initial segments of the -- argument, shortest first. For example, -- --
--   >>> inits "abc"
--   ["","a","ab","abc"]
--   
-- -- Note that inits has the following strictness property: -- inits (xs ++ _|_) = inits xs ++ _|_ -- -- In particular, inits _|_ = [] : _|_ inits :: [a] -> [[a]] -- | The groupBy function is the non-overloaded version of -- group. groupBy :: (a -> a -> Bool) -> [a] -> [[a]] -- | The group function takes a list and returns a list of lists -- such that the concatenation of the result is equal to the argument. -- Moreover, each sublist in the result contains only equal elements. For -- example, -- --
--   >>> group "Mississippi"
--   ["M","i","ss","i","ss","i","pp","i"]
--   
-- -- It is a special case of groupBy, which allows the programmer to -- supply their own equality test. group :: Eq a => [a] -> [[a]] -- | The genericTake function is an overloaded version of -- take, which accepts any Integral value as the number of -- elements to take. genericTake :: Integral i => i -> [a] -> [a] -- | The genericSplitAt function is an overloaded version of -- splitAt, which accepts any Integral value as the -- position at which to split. genericSplitAt :: Integral i => i -> [a] -> ([a], [a]) -- | The genericReplicate function is an overloaded version of -- replicate, which accepts any Integral value as the -- number of repetitions to make. genericReplicate :: Integral i => i -> a -> [a] -- | <math>. The genericLength function is an overloaded -- version of length. In particular, instead of returning an -- Int, it returns any type which is an instance of Num. It -- is, however, less efficient than length. -- --
--   >>> genericLength [1, 2, 3] :: Int
--   3
--   
--   >>> genericLength [1, 2, 3] :: Float
--   3.0
--   
genericLength :: Num i => [a] -> i -- | The genericIndex function is an overloaded version of -- !!, which accepts any Integral value as the index. genericIndex :: Integral i => [a] -> i -> a -- | The genericDrop function is an overloaded version of -- drop, which accepts any Integral value as the number of -- elements to drop. genericDrop :: Integral i => i -> [a] -> [a] -- | The findIndices function extends findIndex, by returning -- the indices of all elements satisfying the predicate, in ascending -- order. -- --
--   >>> findIndices (`elem` "aeiou") "Hello World!"
--   [1,4,7]
--   
findIndices :: (a -> Bool) -> [a] -> [Int] -- | The findIndex function takes a predicate and a list and returns -- the index of the first element in the list satisfying the predicate, -- or Nothing if there is no such element. -- --
--   >>> findIndex isSpace "Hello World!"
--   Just 5
--   
findIndex :: (a -> Bool) -> [a] -> Maybe Int -- | The elemIndices function extends elemIndex, by returning -- the indices of all elements equal to the query element, in ascending -- order. -- --
--   >>> elemIndices 'o' "Hello World"
--   [4,7]
--   
elemIndices :: Eq a => a -> [a] -> [Int] -- | The elemIndex function returns the index of the first element -- in the given list which is equal (by ==) to the query element, -- or Nothing if there is no such element. -- --
--   >>> elemIndex 4 [0..]
--   Just 4
--   
elemIndex :: Eq a => a -> [a] -> Maybe Int -- | The dropWhileEnd function drops the largest suffix of a list in -- which the given predicate holds for all elements. For example: -- --
--   >>> dropWhileEnd isSpace "foo\n"
--   "foo"
--   
-- --
--   >>> dropWhileEnd isSpace "foo bar"
--   "foo bar"
--   
-- --
--   dropWhileEnd isSpace ("foo\n" ++ undefined) == "foo" ++ undefined
--   
dropWhileEnd :: (a -> Bool) -> [a] -> [a] -- | The deleteFirstsBy function takes a predicate and two lists and -- returns the first list with the first occurrence of each element of -- the second list removed. deleteFirstsBy :: (a -> a -> Bool) -> [a] -> [a] -> [a] -- | <math>. The deleteBy function behaves like delete, -- but takes a user-supplied equality predicate. -- --
--   >>> deleteBy (<=) 4 [1..10]
--   [1,2,3,5,6,7,8,9,10]
--   
deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a] -- | <math>. delete x removes the first occurrence of -- x from its list argument. For example, -- --
--   >>> delete 'a' "banana"
--   "bnana"
--   
-- -- It is a special case of deleteBy, which allows the programmer -- to supply their own equality test. delete :: Eq a => a -> [a] -> [a] -- | The \\ function is list difference (non-associative). In the -- result of xs \\ ys, the first occurrence of -- each element of ys in turn (if any) has been removed from -- xs. Thus -- --
--   (xs ++ ys) \\ xs == ys.
--   
-- --
--   >>> "Hello World!" \\ "ell W"
--   "Hoorld!"
--   
-- -- It is a special case of deleteFirstsBy, which allows the -- programmer to supply their own equality test. (\\) :: Eq a => [a] -> [a] -> [a] infix 5 \\ -- | This data type witnesses the lifting of a Monoid into an -- Applicative pointwise. newtype Ap (f :: k -> Type) (a :: k) Ap :: f a -> Ap (f :: k -> Type) (a :: k) [getAp] :: Ap (f :: k -> Type) (a :: k) -> f a -- | 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 -- | 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 -- | 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 -- | 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 getAlt :: Alt f a -> f 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 -- | 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 <math> rather than <math>. stimesIdempotent :: Integral b => b -> a -> a -- | The Down type allows you to reverse sort order conveniently. A -- value of type Down a contains a value of type -- a (represented as Down a). -- -- If a has an Ord instance associated with it -- then comparing two values thus wrapped will give you the opposite of -- their normal sort order. This is particularly useful when sorting in -- generalised list comprehensions, as in: then sortWith by -- Down x. -- --
--   >>> compare True False
--   GT
--   
-- --
--   >>> compare (Down True) (Down False)
--   LT
--   
-- -- If a has a Bounded instance then the wrapped -- instance also respects the reversed ordering by exchanging the values -- of minBound and maxBound. -- --
--   >>> minBound :: Int
--   -9223372036854775808
--   
-- --
--   >>> minBound :: Down Int
--   Down 9223372036854775807
--   
-- -- All other instances of Down a behave as they do for -- a. newtype Down a Down :: a -> Down a [getDown] :: Down a -> a -- |
--   comparing p x y = compare (p x) (p y)
--   
-- -- Useful combinator for use in conjunction with the xxxBy -- family of functions from Data.List, for example: -- --
--   ... sortBy (comparing fst) ...
--   
comparing :: Ord a => (b -> a) -> b -> b -> Ordering -- |
--   clamp (low, high) a = min high (max a low)
--   
-- -- Function for ensursing the value a is within the inclusive -- bounds given by low and high. If it is, a -- is returned unchanged. The result is otherwise low if a -- <= low, or high if high <= a. -- -- When clamp is used at Double and Float, it has NaN propagating -- semantics in its second argument. That is, clamp (l,h) NaN = -- NaN, but clamp (NaN, NaN) x = x. -- --
--   >>> clamp (0, 10) 2
--   2
--   
-- --
--   >>> clamp ('a', 'm') 'x'
--   'm'
--   
clamp :: Ord a => (a, a) -> a -> a -- | An unsigned integral type that can be losslessly converted to and from -- Ptr. This type is also compatible with the C99 type -- uintptr_t, and can be marshalled to and from that type -- safely. newtype WordPtr WordPtr :: Word -> WordPtr -- | A signed integral type that can be losslessly converted to and from -- Ptr. This type is also compatible with the C99 type -- intptr_t, and can be marshalled to and from that type safely. newtype IntPtr IntPtr :: Int -> IntPtr -- | casts a WordPtr to a Ptr wordPtrToPtr :: WordPtr -> Ptr a -- | casts a Ptr to a WordPtr ptrToWordPtr :: Ptr a -> WordPtr -- | casts a Ptr to an IntPtr ptrToIntPtr :: Ptr a -> IntPtr -- | casts an IntPtr to a Ptr intPtrToPtr :: IntPtr -> Ptr a -- | Release the storage associated with the given FunPtr, which -- must have been obtained from a wrapper stub. This should be called -- whenever the return value from a foreign import wrapper function is no -- longer required; otherwise, the storage it uses will leak. freeHaskellFunPtr :: FunPtr a -> IO () -- | The member functions of this class facilitate writing values of -- primitive types to raw memory (which may have been allocated with the -- above mentioned routines) and reading values from blocks of raw -- memory. The class, furthermore, includes support for computing the -- storage requirements and alignment restrictions of storable types. -- -- Memory addresses are represented as values of type Ptr -- a, for some a which is an instance of class -- Storable. The type argument to Ptr helps provide some -- valuable type safety in FFI code (you can't mix pointers of different -- types without an explicit cast), while helping the Haskell type system -- figure out which marshalling method is needed for a given pointer. -- -- All marshalling between Haskell and a foreign language ultimately -- boils down to translating Haskell data structures into the binary -- representation of a corresponding data structure of the foreign -- language and vice versa. To code this marshalling in Haskell, it is -- necessary to manipulate primitive data types stored in unstructured -- memory blocks. The class Storable facilitates this manipulation -- on all types for which it is instantiated, which are the standard -- basic types of Haskell, the fixed size Int types -- (Int8, Int16, Int32, Int64), the fixed -- size Word types (Word8, Word16, Word32, -- Word64), StablePtr, all types from -- Foreign.C.Types, as well as Ptr. class Storable a -- | Computes the storage requirements (in bytes) of the argument. The -- value of the argument is not used. sizeOf :: Storable a => a -> Int -- | Computes the alignment constraint of the argument. An alignment -- constraint x is fulfilled by any address divisible by -- x. The alignment must be a power of two if this instance is -- to be used with alloca or allocaArray. The value of -- the argument is not used. alignment :: Storable a => a -> Int -- | Read a value from a memory area regarded as an array of values of the -- same kind. The first argument specifies the start address of the array -- and the second the index into the array (the first element of the -- array has index 0). The following equality holds, -- --
--   peekElemOff addr idx = IOExts.fixIO $ \result ->
--     peek (addr `plusPtr` (idx * sizeOf result))
--   
-- -- Note that this is only a specification, not necessarily the concrete -- implementation of the function. peekElemOff :: Storable a => Ptr a -> Int -> IO a -- | Write a value to a memory area regarded as an array of values of the -- same kind. The following equality holds: -- --
--   pokeElemOff addr idx x = 
--     poke (addr `plusPtr` (idx * sizeOf x)) x
--   
pokeElemOff :: Storable a => Ptr a -> Int -> a -> IO () -- | Read a value from a memory location given by a base address and -- offset. The following equality holds: -- --
--   peekByteOff addr off = peek (addr `plusPtr` off)
--   
peekByteOff :: Storable a => Ptr b -> Int -> IO a -- | Write a value to a memory location given by a base address and offset. -- The following equality holds: -- --
--   pokeByteOff addr off x = poke (addr `plusPtr` off) x
--   
pokeByteOff :: Storable a => Ptr b -> Int -> a -> IO () -- | Read a value from the given memory location. -- -- Note that the peek and poke functions might require properly aligned -- addresses to function correctly. This is architecture dependent; thus, -- portable code should ensure that when peeking or poking values of some -- type a, the alignment constraint for a, as given by -- the function alignment is fulfilled. peek :: Storable a => Ptr a -> IO a -- | Write the given value to the given memory location. Alignment -- restrictions might apply; see peek. poke :: Storable a => Ptr a -> a -> IO () -- | Dissolve the association between the stable pointer and the Haskell -- value. Afterwards, if the stable pointer is passed to -- deRefStablePtr or freeStablePtr, the behaviour is -- undefined. However, the stable pointer may still be passed to -- castStablePtrToPtr, but the Ptr () value -- returned by castStablePtrToPtr, in this case, is undefined (in -- particular, it may be nullPtr). Nevertheless, the call to -- castStablePtrToPtr is guaranteed not to diverge. freeStablePtr :: StablePtr a -> IO () -- | Obtain the Haskell value referenced by a stable pointer, i.e., the -- same value that was passed to the corresponding call to -- newStablePtr. If the argument to deRefStablePtr has -- already been freed using freeStablePtr, the behaviour of -- deRefStablePtr is undefined. deRefStablePtr :: StablePtr a -> IO a -- | Coerce a stable pointer to an address. No guarantees are made about -- the resulting value, except that the original stable pointer can be -- recovered by castPtrToStablePtr. In particular, the address may -- not refer to an accessible memory location and any attempt to pass it -- to the member functions of the class Storable leads to -- undefined behaviour. castStablePtrToPtr :: StablePtr a -> Ptr () -- | The inverse of castStablePtrToPtr, i.e., we have the identity -- --
--   sp == castPtrToStablePtr (castStablePtrToPtr sp)
--   
-- -- for any stable pointer sp on which freeStablePtr has -- not been executed yet. Moreover, castPtrToStablePtr may only be -- applied to pointers that have been produced by -- castStablePtrToPtr. castPtrToStablePtr :: Ptr () -> StablePtr a unsafeCoerceUnlifted :: forall (a :: UnliftedType) (b :: UnliftedType). a -> b unsafeCoerceAddr :: forall (a :: TYPE 'AddrRep) (b :: TYPE 'AddrRep). a -> b -- | Coerce a value from one type to another, bypassing the type-checker. -- -- There are several legitimate ways to use unsafeCoerce: -- --
    --
  1. To coerce e.g. Int to HValue, put it in a list -- of HValue, and then later coerce it back to Int -- before using it.
  2. --
  3. To produce e.g. (a+b) :~: (b+a) from unsafeCoerce -- Refl. Here the two sides really are the same type -- so nothing -- unsafe is happening -- but GHC is not clever enough to see it.
  4. --
  5. In Data.Typeable we have
  6. --
-- --
--   eqTypeRep :: forall k1 k2 (a :: k1) (b :: k2).
--                TypeRep a -> TypeRep b -> Maybe (a :~~: b)
--   eqTypeRep a b
--     | sameTypeRep a b = Just (unsafeCoerce HRefl)
--     | otherwise       = Nothing
--   
--   
-- -- Here again, the unsafeCoerce HRefl is safe, because the two -- types really are the same -- but the proof of that relies on the -- complex, trusted implementation of Typeable. -- --
    --
  1. The "reflection trick", which takes advantage of the fact that in -- class C a where { op :: ty }, we can safely coerce between -- C a and ty (which have different kinds!) because -- it's really just a newtype. Note: there is no guarantee, at all -- that this behavior will be supported into perpetuity.
  2. --
unsafeCoerce :: a -> b -- | Monoid under bitwise XOR. -- --
--   >>> getXor (Xor 0xab <> Xor 0x12) :: Word8
--   185
--   
newtype Xor a Xor :: a -> Xor a [getXor] :: Xor a -> a -- | Monoid under bitwise inclusive OR. -- --
--   >>> getIor (Ior 0xab <> Ior 0x12) :: Word8
--   187
--   
newtype Ior a Ior :: a -> Ior a [getIor] :: Ior a -> a -- | Monoid under bitwise 'equality'; defined as 1 if the -- corresponding bits match, and 0 otherwise. -- --
--   >>> getIff (Iff 0xab <> Iff 0x12) :: Word8
--   70
--   
newtype Iff a Iff :: a -> Iff a [getIff] :: Iff a -> a -- | Monoid under bitwise AND. -- --
--   >>> getAnd (And 0xab <> And 0x12) :: Word8
--   2
--   
newtype And a And :: a -> And a [getAnd] :: And a -> a -- | A more concise version of complement zeroBits. -- --
--   >>> complement (zeroBits :: Word) == (oneBits :: Word)
--   True
--   
-- --
--   >>> complement (oneBits :: Word) == (zeroBits :: Word)
--   True
--   
-- --

Note

-- -- The constraint on oneBits is arguably too strong. However, as -- some types (such as Natural) have undefined -- complement, this is the only safe choice. oneBits :: FiniteBits a => a -- | Selects Unicode space and separator characters. -- -- This function returns True if its argument has one of the -- following GeneralCategorys, or False otherwise: -- -- -- -- These classes are defined in the Unicode Character Database, -- part of the Unicode standard. The same document defines what is and is -- not a "Separator". -- --

Examples

-- -- Basic usage: -- --
--   >>> isSeparator 'a'
--   False
--   
--   >>> isSeparator '6'
--   False
--   
--   >>> isSeparator ' '
--   True
--   
-- -- Warning: newlines and tab characters are not considered separators. -- --
--   >>> isSeparator '\n'
--   False
--   
--   >>> isSeparator '\t'
--   False
--   
-- -- But some more exotic characters are (like HTML's &nbsp;): -- --
--   >>> isSeparator '\160'
--   True
--   
isSeparator :: Char -> Bool -- | Selects Unicode numeric characters, including digits from various -- scripts, Roman numerals, et cetera. -- -- This function returns True if its argument has one of the -- following GeneralCategorys, or False otherwise: -- -- -- -- These classes are defined in the Unicode Character Database, -- part of the Unicode standard. The same document defines what is and is -- not a "Number". -- --

Examples

-- -- Basic usage: -- --
--   >>> isNumber 'a'
--   False
--   
--   >>> isNumber '%'
--   False
--   
--   >>> isNumber '3'
--   True
--   
-- -- ASCII '0' through '9' are all numbers: -- --
--   >>> and $ map isNumber ['0'..'9']
--   True
--   
-- -- Unicode Roman numerals are "numbers" as well: -- --
--   >>> isNumber 'Ⅸ'
--   True
--   
isNumber :: Char -> Bool -- | Selects Unicode mark characters, for example accents and the like, -- which combine with preceding characters. -- -- This function returns True if its argument has one of the -- following GeneralCategorys, or False otherwise: -- -- -- -- These classes are defined in the Unicode Character Database, -- part of the Unicode standard. The same document defines what is and is -- not a "Mark". -- --

Examples

-- -- Basic usage: -- --
--   >>> isMark 'a'
--   False
--   
--   >>> isMark '0'
--   False
--   
-- -- Combining marks such as accent characters usually need to follow -- another character before they become printable: -- --
--   >>> map isMark "ò"
--   [False,True]
--   
-- -- Puns are not necessarily supported: -- --
--   >>> isMark '✓'
--   False
--   
isMark :: Char -> Bool -- | Selects alphabetic Unicode characters (lower-case, upper-case and -- title-case letters, plus letters of caseless scripts and modifiers -- letters). This function is equivalent to isAlpha. -- -- This function returns True if its argument has one of the -- following GeneralCategorys, or False otherwise: -- -- -- -- These classes are defined in the Unicode Character Database, -- part of the Unicode standard. The same document defines what is and is -- not a "Letter". -- --

Examples

-- -- Basic usage: -- --
--   >>> isLetter 'a'
--   True
--   
--   >>> isLetter 'A'
--   True
--   
--   >>> isLetter 'λ'
--   True
--   
--   >>> isLetter '0'
--   False
--   
--   >>> isLetter '%'
--   False
--   
--   >>> isLetter '♥'
--   False
--   
--   >>> isLetter '\31'
--   False
--   
-- -- Ensure that isLetter and isAlpha are equivalent. -- --
--   >>> let chars = [(chr 0)..]
--   
--   >>> let letters = map isLetter chars
--   
--   >>> let alphas = map isAlpha chars
--   
--   >>> letters == alphas
--   True
--   
isLetter :: Char -> Bool -- | Convert a single digit Char to the corresponding Int. -- This function fails unless its argument satisfies isHexDigit, -- but recognises both upper- and lower-case hexadecimal digits (that is, -- '0'..'9', 'a'..'f', -- 'A'..'F'). -- --

Examples

-- -- Characters '0' through '9' are converted properly to -- 0..9: -- --
--   >>> map digitToInt ['0'..'9']
--   [0,1,2,3,4,5,6,7,8,9]
--   
-- -- Both upper- and lower-case 'A' through 'F' are -- converted as well, to 10..15. -- --
--   >>> map digitToInt ['a'..'f']
--   [10,11,12,13,14,15]
--   
--   >>> map digitToInt ['A'..'F']
--   [10,11,12,13,14,15]
--   
-- -- Anything else throws an exception: -- --
--   >>> digitToInt 'G'
--   *** Exception: Char.digitToInt: not a digit 'G'
--   
--   >>> digitToInt '♥'
--   *** Exception: Char.digitToInt: not a digit '\9829'
--   
digitToInt :: Char -> Int -- | equivalent to readsPrec with a precedence of 0. reads :: Read a => ReadS 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 -- | Parse a string using the Read instance. Succeeds if there is -- exactly one valid result. A Left value indicates a parse error. -- --
--   >>> readEither "123" :: Either String Int
--   Right 123
--   
-- --
--   >>> readEither "hello" :: Either String Int
--   Left "Prelude.read: no parse"
--   
readEither :: Read a => String -> Either String 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 -- | Extracts from a list of Either all the Right elements. -- All the Right elements are extracted in order. -- --

Examples

-- -- Basic usage: -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> rights list
--   [3,7]
--   
rights :: [Either a b] -> [b] -- | Partitions a list of Either into two lists. All the Left -- elements are extracted, in order, to the first component of the -- output. Similarly the Right elements are extracted to the -- second component of the output. -- --

Examples

-- -- Basic usage: -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> partitionEithers list
--   (["foo","bar","baz"],[3,7])
--   
-- -- The pair returned by partitionEithers x should be the -- same pair as (lefts x, rights x): -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> partitionEithers list == (lefts list, rights list)
--   True
--   
partitionEithers :: [Either a b] -> ([a], [b]) -- | Extracts from a list of Either all the Left elements. -- All the Left elements are extracted in order. -- --

Examples

-- -- Basic usage: -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> lefts list
--   ["foo","bar","baz"]
--   
lefts :: [Either a b] -> [a] -- | Return True if the given value is a Right-value, -- False otherwise. -- --

Examples

-- -- Basic usage: -- --
--   >>> 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 True if the given value is a Left-value, -- False otherwise. -- --

Examples

-- -- Basic usage: -- --
--   >>> 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 the contents of a Right-value or a default value -- otherwise. -- --

Examples

-- -- Basic usage: -- --
--   >>> fromRight 1 (Right 3)
--   3
--   
--   >>> fromRight 1 (Left "foo")
--   1
--   
fromRight :: b -> Either a b -> b -- | Return the contents of a Left-value or a default value -- otherwise. -- --

Examples

-- -- Basic usage: -- --
--   >>> fromLeft 1 (Left 3)
--   3
--   
--   >>> fromLeft 1 (Right "foo")
--   1
--   
fromLeft :: a -> Either a b -> a -- | Proxy is a type that holds no data, but has a phantom parameter -- of arbitrary type (or even kind). Its use is to provide type -- information, even though there is no value available of that type (or -- it may be too costly to create one). -- -- Historically, Proxy :: Proxy a is a safer -- alternative to the undefined :: a idiom. -- --
--   >>> Proxy :: Proxy (Void, Int -> Int)
--   Proxy
--   
-- -- Proxy can even hold types of higher kinds, -- --
--   >>> Proxy :: Proxy Either
--   Proxy
--   
-- --
--   >>> Proxy :: Proxy Functor
--   Proxy
--   
-- --
--   >>> Proxy :: Proxy complicatedStructure
--   Proxy
--   
data Proxy (t :: k) Proxy :: Proxy (t :: k) -- | A concrete, promotable proxy type, for use at the kind level. There -- are no instances for this because it is intended at the kind level -- only data KProxy t KProxy :: KProxy t -- | 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 -- | A class for categories. Instances should satisfy the laws -- -- class Category (cat :: k -> k -> Type) -- | the identity morphism id :: forall (a :: k). Category cat => cat a a -- | morphism composition (.) :: forall (b :: k) (c :: k) (a :: k). Category cat => cat b c -> cat a b -> cat a c infixr 9 . -- | Left-to-right composition (>>>) :: forall {k} cat (a :: k) (b :: k) (c :: k). Category cat => cat a b -> cat b c -> cat a c infixr 1 >>> -- | Right-to-left composition (<<<) :: forall {k} cat (b :: k) (c :: k) (a :: k). Category cat => cat b c -> cat a b -> cat a c infixr 1 <<< -- | Kind heterogeneous propositional equality. Like :~:, a :~~: -- b is inhabited by a terminating value if and only if a -- is the same type as b. data (a :: k1) :~~: (b :: k2) [HRefl] :: forall {k1} (a :: k1). a :~~: a infix 4 :~~: -- | Propositional equality. If a :~: b is inhabited by some -- terminating value, then the type a is the same as the type -- b. To use this equality in practice, pattern-match on the -- a :~: b to get out the Refl constructor; in the body -- of the pattern-match, the compiler knows that a ~ b. data (a :: k) :~: (b :: k) [Refl] :: forall {k} (a :: k). a :~: a infix 4 :~: -- | Advances the given address by the given offset in bytes. plusPtr :: Ptr a -> Int -> Ptr b -- | The constant nullPtr contains a distinguished value of -- Ptr that is not associated with a valid memory location. nullPtr :: Ptr a -- | The constant nullFunPtr contains a distinguished value of -- FunPtr that is not associated with a valid memory location. nullFunPtr :: FunPtr a -- | Computes the offset required to get from the second to the first -- argument. We have -- --
--   p2 == p1 `plusPtr` (p2 `minusPtr` p1)
--   
minusPtr :: Ptr a -> Ptr b -> Int -- | Casts a Ptr to a FunPtr. -- -- Note: this is valid only on architectures where data and -- function pointers range over the same set of addresses, and should -- only be used for bindings to external libraries whose interface -- already relies on this assumption. castPtrToFunPtr :: Ptr a -> FunPtr b -- | The castPtr function casts a pointer from one type to another. castPtr :: Ptr a -> Ptr b -- | Casts a FunPtr to a Ptr. -- -- Note: this is valid only on architectures where data and -- function pointers range over the same set of addresses, and should -- only be used for bindings to external libraries whose interface -- already relies on this assumption. castFunPtrToPtr :: FunPtr a -> Ptr b -- | Casts a FunPtr to a FunPtr of a different type. castFunPtr :: FunPtr a -> FunPtr b -- | Given an arbitrary address and an alignment constraint, -- alignPtr yields the next higher address that fulfills the -- alignment constraint. An alignment constraint x is fulfilled -- by any address divisible by x. This operation is idempotent. alignPtr :: Ptr a -> Int -> Ptr a -- | Show non-negative Integral numbers in base 8. showOct :: (Integral a, Show a) => a -> ShowS -- | Shows a non-negative Integral number using the base -- specified by the first argument, and the character representation -- specified by the second. showIntAtBase :: (Integral a, Show a) => a -> (Int -> Char) -> a -> ShowS -- | Show non-negative Integral numbers in base 10. showInt :: Integral a => a -> ShowS -- | Show non-negative Integral numbers in base 16. showHex :: (Integral a, Show a) => 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 -- | 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 signed RealFloat value using standard decimal notation -- for arguments whose absolute value lies between 0.1 and -- 9,999,999, and scientific notation otherwise. -- -- In the call showGFloat digs val, if digs is -- Nothing, the value is shown to full precision; if digs -- is Just d, then at most d digits after the -- decimal point are shown. showGFloat :: RealFloat a => Maybe Int -> a -> ShowS -- | 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 -- (e.g. 245000, 0.0015). -- -- In the call showFFloat digs val, if digs is -- Nothing, the value is shown to full precision; if digs -- is Just d, then at most d digits after the -- decimal point are shown. showFFloat :: RealFloat a => Maybe Int -> a -> ShowS -- | Show a signed RealFloat value using scientific (exponential) -- notation (e.g. 2.45e2, 1.5e-3). -- -- In the call showEFloat digs val, if digs is -- Nothing, the value is shown to full precision; if digs -- is Just d, then at most d digits after the -- decimal point are shown. showEFloat :: RealFloat a => Maybe Int -> a -> ShowS -- | Show non-negative Integral numbers in base 2. showBin :: (Integral a, Show a) => a -> ShowS -- | Reads a signed Real value, given a reader for an -- unsigned value. readSigned :: Real a => ReadS a -> ReadS a -- | Read an unsigned number in octal notation. -- --
--   >>> readOct "0644"
--   [(420,"")]
--   
readOct :: (Eq a, Num a) => ReadS a -- | Reads an unsigned Integral value in an arbitrary base. readInt :: Num a => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a -- | Read an unsigned number in hexadecimal notation. Both upper or lower -- case letters are allowed. -- --
--   >>> readHex "deadbeef"
--   [(3735928559,"")]
--   
readHex :: (Eq a, Num a) => ReadS a -- | Reads an unsigned RealFrac value, expressed in decimal -- scientific notation. readFloat :: RealFrac a => ReadS a -- | Read an unsigned number in decimal notation. -- --
--   >>> readDec "0644"
--   [(644,"")]
--   
readDec :: (Eq a, Num a) => ReadS a -- | Read an unsigned number in binary notation. -- --
--   >>> readBin "10011"
--   [(19,"")]
--   
readBin :: (Eq a, Num a) => ReadS 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 -- | Read a string representation of a character, using Haskell -- source-language escape conventions, and convert it to the character -- that it encodes. For example: -- --
--   readLitChar "\\nHello"  =  [('\n', "Hello")]
--   
readLitChar :: ReadS Char -- | Read a string representation of a character, using Haskell -- source-language escape conventions. For example: -- --
--   lexLitChar  "\\nHello"  =  [("\\n", "Hello")]
--   
lexLitChar :: ReadS String -- | Reads a non-empty string of decimal digits. lexDigits :: ReadS String -- | 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: -- -- lex :: ReadS String data ReadPrec a readS_to_Prec :: (Int -> ReadS a) -> ReadPrec a readPrec_to_S :: ReadPrec a -> Int -> ReadS a readPrec_to_P :: ReadPrec a -> Int -> ReadP a readP_to_Prec :: (Int -> ReadP 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)] data ReadP a -- | Converts a Haskell ReadS-style function into a parser. Warning: This -- introduces local backtracking in the resulting parser, and therefore a -- possible inefficiency. readS_to_P :: ReadS a -> ReadP a -- | Converts a parser into a Haskell ReadS-style function. This is the -- main way in which you can "run" a ReadP parser: the expanded -- type is readP_to_S :: ReadP a -> String -> [(a,String)] -- readP_to_S :: ReadP a -> ReadS a -- | Show a signed RealFloat value to full precision using standard -- decimal notation for arguments whose absolute value lies between -- 0.1 and 9,999,999, and scientific notation -- otherwise. showFloat :: RealFloat a => a -> ShowS -- | Converts a Rational value into any type in class -- RealFloat. fromRat :: RealFloat a => Rational -> a -- | floatToDigits takes a base and a non-negative RealFloat -- number, and returns a list of digits and an exponent. In particular, -- if x>=0, and -- --
--   floatToDigits base x = ([d1,d2,...,dn], e)
--   
-- -- then -- --
    --
  1. n >= 1
  2. --
  3. x = 0.d1d2...dn * (base**e)
  4. --
  5. 0 <= di <= base-1
  6. --
floatToDigits :: RealFloat a => Integer -> a -> ([Int], Int) -- | Reverse order of bytes in Word64. byteSwap64 :: Word64 -> Word64 -- | Reverse order of bytes in Word32. byteSwap32 :: Word32 -> Word32 -- | Reverse order of bytes in Word16. byteSwap16 :: Word16 -> Word16 -- | Reverse the order of the bits in a Word8. bitReverse8 :: Word8 -> Word8 -- | Reverse the order of the bits in a Word64. bitReverse64 :: Word64 -> Word64 -- | Reverse the order of the bits in a Word32. bitReverse32 :: Word32 -> Word32 -- | Reverse the order of the bits in a Word16. bitReverse16 :: Word16 -> Word16 -- | Unicode General Categories (column 2 of the UnicodeData table) in the -- order they are listed in the Unicode standard (the Unicode Character -- Database, in particular). -- --

Examples

-- -- Basic usage: -- --
--   >>> :t OtherLetter
--   OtherLetter :: GeneralCategory
--   
-- -- Eq instance: -- --
--   >>> UppercaseLetter == UppercaseLetter
--   True
--   
--   >>> UppercaseLetter == LowercaseLetter
--   False
--   
-- -- Ord instance: -- --
--   >>> NonSpacingMark <= MathSymbol
--   True
--   
-- -- Enum instance: -- --
--   >>> enumFromTo ModifierLetter SpacingCombiningMark
--   [ModifierLetter,OtherLetter,NonSpacingMark,SpacingCombiningMark]
--   
-- -- Read instance: -- --
--   >>> read "DashPunctuation" :: GeneralCategory
--   DashPunctuation
--   
--   >>> read "17" :: GeneralCategory
--   *** Exception: Prelude.read: no parse
--   
-- -- Show instance: -- --
--   >>> show EnclosingMark
--   "EnclosingMark"
--   
-- -- Bounded instance: -- --
--   >>> minBound :: GeneralCategory
--   UppercaseLetter
--   
--   >>> maxBound :: GeneralCategory
--   NotAssigned
--   
-- -- Ix instance: -- --
--   >>> import Data.Ix ( index )
--   
--   >>> index (OtherLetter,Control) FinalQuote
--   12
--   
--   >>> index (OtherLetter,Control) Format
--   *** Exception: Error in array index
--   
data GeneralCategory -- | Lu: Letter, Uppercase UppercaseLetter :: GeneralCategory -- | Ll: Letter, Lowercase LowercaseLetter :: GeneralCategory -- | Lt: Letter, Titlecase TitlecaseLetter :: GeneralCategory -- | Lm: Letter, Modifier ModifierLetter :: GeneralCategory -- | Lo: Letter, Other OtherLetter :: GeneralCategory -- | Mn: Mark, Non-Spacing NonSpacingMark :: GeneralCategory -- | Mc: Mark, Spacing Combining SpacingCombiningMark :: GeneralCategory -- | Me: Mark, Enclosing EnclosingMark :: GeneralCategory -- | Nd: Number, Decimal DecimalNumber :: GeneralCategory -- | Nl: Number, Letter LetterNumber :: GeneralCategory -- | No: Number, Other OtherNumber :: GeneralCategory -- | Pc: Punctuation, Connector ConnectorPunctuation :: GeneralCategory -- | Pd: Punctuation, Dash DashPunctuation :: GeneralCategory -- | Ps: Punctuation, Open OpenPunctuation :: GeneralCategory -- | Pe: Punctuation, Close ClosePunctuation :: GeneralCategory -- | Pi: Punctuation, Initial quote InitialQuote :: GeneralCategory -- | Pf: Punctuation, Final quote FinalQuote :: GeneralCategory -- | Po: Punctuation, Other OtherPunctuation :: GeneralCategory -- | Sm: Symbol, Math MathSymbol :: GeneralCategory -- | Sc: Symbol, Currency CurrencySymbol :: GeneralCategory -- | Sk: Symbol, Modifier ModifierSymbol :: GeneralCategory -- | So: Symbol, Other OtherSymbol :: GeneralCategory -- | Zs: Separator, Space Space :: GeneralCategory -- | Zl: Separator, Line LineSeparator :: GeneralCategory -- | Zp: Separator, Paragraph ParagraphSeparator :: GeneralCategory -- | Cc: Other, Control Control :: GeneralCategory -- | Cf: Other, Format Format :: GeneralCategory -- | Cs: Other, Surrogate Surrogate :: GeneralCategory -- | Co: Other, Private Use PrivateUse :: GeneralCategory -- | Cn: Other, Not Assigned NotAssigned :: GeneralCategory -- | Convert a letter to the corresponding upper-case letter, if any. Any -- other character is returned unchanged. toUpper :: Char -> Char -- | Convert a letter to the corresponding title-case or upper-case letter, -- if any. (Title case differs from upper case only for a small number of -- ligature letters.) Any other character is returned unchanged. toTitle :: Char -> Char -- | Convert a letter to the corresponding lower-case letter, if any. Any -- other character is returned unchanged. toLower :: Char -> Char -- | Selects upper-case or title-case alphabetic Unicode characters -- (letters). Title case is used by a small number of letter ligatures -- like the single-character form of Lj. isUpper :: Char -> Bool -- | Selects Unicode symbol characters, including mathematical and currency -- symbols. -- -- This function returns True if its argument has one of the -- following GeneralCategorys, or False otherwise: -- -- -- -- These classes are defined in the Unicode Character Database, -- part of the Unicode standard. The same document defines what is and is -- not a "Symbol". -- --

Examples

-- -- Basic usage: -- --
--   >>> isSymbol 'a'
--   False
--   
--   >>> isSymbol '6'
--   False
--   
--   >>> isSymbol '='
--   True
--   
-- -- The definition of "math symbol" may be a little counter-intuitive -- depending on one's background: -- --
--   >>> isSymbol '+'
--   True
--   
--   >>> isSymbol '-'
--   False
--   
isSymbol :: Char -> Bool -- | Returns True for any Unicode space character, and the control -- characters \t, \n, \r, \f, -- \v. isSpace :: Char -> Bool -- | Selects Unicode punctuation characters, including various kinds of -- connectors, brackets and quotes. -- -- This function returns True if its argument has one of the -- following GeneralCategorys, or False otherwise: -- -- -- -- These classes are defined in the Unicode Character Database, -- part of the Unicode standard. The same document defines what is and is -- not a "Punctuation". -- --

Examples

-- -- Basic usage: -- --
--   >>> isPunctuation 'a'
--   False
--   
--   >>> isPunctuation '7'
--   False
--   
--   >>> isPunctuation '♥'
--   False
--   
--   >>> isPunctuation '"'
--   True
--   
--   >>> isPunctuation '?'
--   True
--   
--   >>> isPunctuation '—'
--   True
--   
isPunctuation :: Char -> Bool -- | Selects printable Unicode characters (letters, numbers, marks, -- punctuation, symbols and spaces). isPrint :: Char -> Bool -- | Selects ASCII octal digits, i.e. '0'..'7'. isOctDigit :: Char -> Bool -- | Selects lower-case alphabetic Unicode characters (letters). isLower :: Char -> Bool -- | Selects the first 256 characters of the Unicode character set, -- corresponding to the ISO 8859-1 (Latin-1) character set. isLatin1 :: Char -> Bool -- | Selects ASCII hexadecimal digits, i.e. '0'..'9', -- 'a'..'f', 'A'..'F'. isHexDigit :: Char -> Bool -- | Selects ASCII digits, i.e. '0'..'9'. isDigit :: Char -> Bool -- | Selects control characters, which are the non-printing characters of -- the Latin-1 subset of Unicode. isControl :: Char -> Bool -- | Selects ASCII upper-case letters, i.e. characters satisfying both -- isAscii and isUpper. isAsciiUpper :: Char -> Bool -- | Selects ASCII lower-case letters, i.e. characters satisfying both -- isAscii and isLower. isAsciiLower :: Char -> Bool -- | Selects the first 128 characters of the Unicode character set, -- corresponding to the ASCII character set. isAscii :: Char -> Bool -- | Selects alphabetic or numeric Unicode characters. -- -- Note that numeric digits outside the ASCII range, as well as numeric -- characters which aren't digits, are selected by this function but not -- by isDigit. Such characters may be part of identifiers but are -- not used by the printer and reader to represent numbers. isAlphaNum :: Char -> Bool -- | Selects alphabetic Unicode characters (lower-case, upper-case and -- title-case letters, plus letters of caseless scripts and modifiers -- letters). This function is equivalent to isLetter. isAlpha :: Char -> Bool -- | The Unicode general category of the character. This relies on the -- Enum instance of GeneralCategory, which must remain in -- the same order as the categories are presented in the Unicode -- standard. -- --

Examples

-- -- Basic usage: -- --
--   >>> generalCategory 'a'
--   LowercaseLetter
--   
--   >>> generalCategory 'A'
--   UppercaseLetter
--   
--   >>> generalCategory '0'
--   DecimalNumber
--   
--   >>> generalCategory '%'
--   OtherPunctuation
--   
--   >>> generalCategory '♥'
--   OtherSymbol
--   
--   >>> generalCategory '\31'
--   Control
--   
--   >>> generalCategory ' '
--   Space
--   
generalCategory :: Char -> GeneralCategory -- | The FiniteBits class denotes types with a finite, fixed number -- of bits. class Bits b => FiniteBits b -- | Return the number of bits in the type of the argument. The actual -- value of the argument is ignored. Moreover, finiteBitSize is -- total, in contrast to the deprecated bitSize function it -- replaces. -- --
--   finiteBitSize = bitSize
--   bitSizeMaybe = Just . finiteBitSize
--   
finiteBitSize :: FiniteBits b => b -> Int -- | Count number of zero bits preceding the most significant set bit. -- --
--   countLeadingZeros (zeroBits :: a) = finiteBitSize (zeroBits :: a)
--   
-- -- countLeadingZeros can be used to compute log base 2 via -- --
--   logBase2 x = finiteBitSize x - 1 - countLeadingZeros x
--   
-- -- Note: The default implementation for this method is intentionally -- naive. However, the instances provided for the primitive integral -- types are implemented using CPU specific machine instructions. countLeadingZeros :: FiniteBits b => b -> Int -- | Count number of zero bits following the least significant set bit. -- --
--   countTrailingZeros (zeroBits :: a) = finiteBitSize (zeroBits :: a)
--   countTrailingZeros . negate = countTrailingZeros
--   
-- -- The related find-first-set operation can be expressed in terms -- of countTrailingZeros as follows -- --
--   findFirstSet x = 1 + countTrailingZeros x
--   
-- -- Note: The default implementation for this method is intentionally -- naive. However, the instances provided for the primitive integral -- types are implemented using CPU specific machine instructions. countTrailingZeros :: FiniteBits b => b -> Int -- | The Bits class defines bitwise operations over integral types. -- -- class Eq a => Bits a -- | Bitwise "and" (.&.) :: Bits a => a -> a -> a -- | Bitwise "or" (.|.) :: Bits a => a -> a -> a -- | Bitwise "xor" xor :: Bits a => a -> a -> a -- | Reverse all the bits in the argument complement :: Bits a => a -> a -- | shift x i shifts x left by i bits if -- i is positive, or right by -i bits otherwise. Right -- shifts perform sign extension on signed number types; i.e. they fill -- the top bits with 1 if the x is negative and with 0 -- otherwise. -- -- An instance can define either this unified shift or -- shiftL and shiftR, depending on which is more convenient -- for the type in question. shift :: Bits a => a -> Int -> a -- | rotate x i rotates x left by i bits -- if i is positive, or right by -i bits otherwise. -- -- For unbounded types like Integer, rotate is equivalent -- to shift. -- -- An instance can define either this unified rotate or -- rotateL and rotateR, depending on which is more -- convenient for the type in question. rotate :: Bits a => a -> Int -> a -- | zeroBits is the value with all bits unset. -- -- The following laws ought to hold (for all valid bit indices -- n): -- -- -- -- This method uses clearBit (bit 0) 0 as its -- default implementation (which ought to be equivalent to -- zeroBits for types which possess a 0th bit). zeroBits :: Bits a => a -- | bit i is a value with the ith bit set -- and all other bits clear. -- -- Can be implemented using bitDefault if a is also an -- instance of Num. -- -- See also zeroBits. bit :: Bits a => Int -> a -- | x `setBit` i is the same as x .|. bit i setBit :: Bits a => a -> Int -> a -- | x `clearBit` i is the same as x .&. complement (bit -- i) clearBit :: Bits a => a -> Int -> a -- | x `complementBit` i is the same as x `xor` bit i complementBit :: Bits a => a -> Int -> a -- | x `testBit` i is the same as x .&. bit n /= 0 -- -- In other words it returns True if the bit at offset @n is set. -- -- Can be implemented using testBitDefault if a is also -- an instance of Num. testBit :: Bits a => a -> Int -> Bool -- | Return the number of bits in the type of the argument. The actual -- value of the argument is ignored. Returns Nothing for types that do -- not have a fixed bitsize, like Integer. bitSizeMaybe :: Bits a => a -> Maybe Int -- | Return the number of bits in the type of the argument. The actual -- value of the argument is ignored. The function bitSize is -- undefined for types that do not have a fixed bitsize, like -- Integer. -- -- Default implementation based upon bitSizeMaybe provided since -- 4.12.0.0. bitSize :: Bits a => a -> Int -- | Return True if the argument is a signed type. The actual value -- of the argument is ignored isSigned :: Bits a => a -> Bool -- | Shift the argument left by the specified number of bits (which must be -- non-negative). Some instances may throw an Overflow exception -- if given a negative input. -- -- An instance can define either this and shiftR or the unified -- shift, depending on which is more convenient for the type in -- question. shiftL :: Bits a => a -> Int -> a -- | Shift the argument left by the specified number of bits. The result is -- undefined for negative shift amounts and shift amounts greater or -- equal to the bitSize. -- -- Defaults to shiftL unless defined explicitly by an instance. unsafeShiftL :: Bits a => a -> Int -> a -- | Shift the first argument right by the specified number of bits. The -- result is undefined for negative shift amounts and shift amounts -- greater or equal to the bitSize. Some instances may throw an -- Overflow exception if given a negative input. -- -- Right shifts perform sign extension on signed number types; i.e. they -- fill the top bits with 1 if the x is negative and with 0 -- otherwise. -- -- An instance can define either this and shiftL or the unified -- shift, depending on which is more convenient for the type in -- question. shiftR :: Bits a => a -> Int -> a -- | Shift the first argument right by the specified number of bits, which -- must be non-negative and smaller than the number of bits in the type. -- -- Right shifts perform sign extension on signed number types; i.e. they -- fill the top bits with 1 if the x is negative and with 0 -- otherwise. -- -- Defaults to shiftR unless defined explicitly by an instance. unsafeShiftR :: Bits a => a -> Int -> a -- | Rotate the argument left by the specified number of bits (which must -- be non-negative). -- -- An instance can define either this and rotateR or the unified -- rotate, depending on which is more convenient for the type in -- question. rotateL :: Bits a => a -> Int -> a -- | Rotate the argument right by the specified number of bits (which must -- be non-negative). -- -- An instance can define either this and rotateL or the unified -- rotate, depending on which is more convenient for the type in -- question. rotateR :: Bits a => a -> Int -> a -- | Return the number of set bits in the argument. This number is known as -- the population count or the Hamming weight. -- -- Can be implemented using popCountDefault if a is also -- an instance of Num. popCount :: Bits a => a -> Int infixl 6 `xor` infixl 8 `shiftR` infixl 8 `shiftL` infixl 8 `shift` infixl 8 `rotateR` infixl 8 `rotateL` infixl 8 `rotate` infixl 7 .&. infixl 5 .|. -- | 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 -- | 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 -- | Default implementation for bit. -- -- Note that: bitDefault i = 1 shiftL i bitDefault :: (Bits a, Num a) => Int -> a -- | Converts a possibly-negative Real value to a string. showSigned :: Real a => (a -> ShowS) -> Int -> a -> ShowS odd :: Integral a => a -> Bool -- | Extract the numerator of the ratio in reduced form: the numerator and -- denominator have no common factor and the denominator is positive. numerator :: Ratio a -> a -- | lcm x y is the smallest positive integer that both -- x and y divide. lcm :: Integral a => a -> a -> a -- | gcd x y is the non-negative factor of both x -- and y of which every common factor of x and -- y is also a factor; for example gcd 4 2 = 2, -- gcd (-4) 6 = 2, gcd 0 4 = 4. -- gcd 0 0 = 0. (That is, the common divisor -- that is "greatest" in the divisibility preordering.) -- -- Note: Since for signed fixed-width integer types, abs -- minBound < 0, the result may be negative if one of the -- arguments is minBound (and necessarily is if the other -- is 0 or minBound) for such types. gcd :: Integral a => a -> a -> a even :: Integral a => a -> Bool -- | Extract the denominator of the ratio in reduced form: the numerator -- and denominator have no common factor and the denominator is positive. denominator :: Ratio a -> a -- | raise a number to an integral power (^^) :: (Fractional a, Integral b) => a -> b -> a infixr 8 ^^ -- | raise a number to a non-negative integral power (^) :: (Num a, Integral b) => a -> b -> a infixr 8 ^ -- | Forms the ratio of two integral numbers. (%) :: Integral a => a -> a -> Ratio a infixl 7 % -- | The toEnum method restricted to the type Char. chr :: Int -> Char -- | a value of type STRef s a is a mutable variable in state -- thread s, containing a value of type a -- --
--   >>> :{
--   runST (do
--       ref <- newSTRef "hello"
--       x <- readSTRef ref
--       writeSTRef ref (x ++ "world")
--       readSTRef ref )
--   :}
--   "helloworld"
--   
data STRef s a -- | Write a new value into an STRef writeSTRef :: STRef s a -> a -> ST s () -- | Read the value of an STRef readSTRef :: STRef s a -> ST s a -- | Build a new STRef in the current state thread newSTRef :: a -> ST s (STRef s a) -- | Return the value computed by a state thread. The forall -- ensures that the internal state used by the ST computation is -- inaccessible to the rest of the program. runST :: (forall s. () => ST s a) -> a -- | 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 -- | equivalent to showsPrec with a precedence of 0. shows :: Show a => a -> ShowS -- | utility function converting a String to a show function that -- simply prepends the string unchanged. showString :: String -> ShowS -- | utility function that surrounds the inner show function with -- parentheses when the Bool parameter is True. showParen :: Bool -> ShowS -> ShowS -- | Convert a character to a string using only printable characters, using -- Haskell source-language escape conventions. For example: -- --
--   showLitChar '\n' s  =  "\\n" ++ s
--   
showLitChar :: Char -> ShowS -- | utility function converting a Char to a show function that -- simply prepends the character unchanged. showChar :: Char -> ShowS -- | Convert an Int in the range 0..15 to the -- corresponding single digit Char. This function fails on other -- inputs, and generates lower-case hexadecimal digits. intToDigit :: Int -> Char -- | The zipWith3 function takes a function which combines three -- elements, as well as three lists and returns a list of the function -- applied to corresponding elements, analogous to zipWith. It is -- capable of list fusion, but it is restricted to its first list -- argument and its resulting list. -- --
--   zipWith3 (,,) xs ys zs == zip3 xs ys zs
--   zipWith3 f [x1,x2,x3..] [y1,y2,y3..] [z1,z2,z3..] == [f x1 y1 z1, f x2 y2 z2, f x3 y3 z3..]
--   
zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d] -- | <math>. zipWith generalises zip by zipping with -- the function given as the first argument, instead of a tupling -- function. -- --
--   zipWith (,) xs ys == zip xs ys
--   zipWith f [x1,x2,x3..] [y1,y2,y3..] == [f x1 y1, f x2 y2, f x3 y3..]
--   
-- -- For example, zipWith (+) is applied to two lists to -- produce the list of corresponding sums: -- --
--   >>> zipWith (+) [1, 2, 3] [4, 5, 6]
--   [5,7,9]
--   
-- -- zipWith is right-lazy: -- --
--   >>> let f = undefined
--   
--   >>> zipWith f [] undefined
--   []
--   
-- -- zipWith is capable of list fusion, but it is restricted to its -- first list argument and its resulting list. zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] -- | zip3 takes three lists and returns a list of triples, analogous -- to zip. It is capable of list fusion, but it is restricted to -- its first list argument and its resulting list. zip3 :: [a] -> [b] -> [c] -> [(a, b, c)] -- | The unzip3 function takes a list of triples and returns three -- lists, analogous to unzip. -- --
--   >>> unzip3 []
--   ([],[],[])
--   
--   >>> unzip3 [(1, 'a', True), (2, 'b', False)]
--   ([1,2],"ab",[True,False])
--   
unzip3 :: [(a, b, c)] -> ([a], [b], [c]) -- | unzip transforms a list of pairs into a list of first -- components and a list of second components. -- --
--   >>> unzip []
--   ([],[])
--   
--   >>> unzip [(1, 'a'), (2, 'b')]
--   ([1,2],"ab")
--   
unzip :: [(a, b)] -> ([a], [b]) -- | <math>. Decompose a list into its head and tail. -- -- -- --
--   >>> uncons []
--   Nothing
--   
--   >>> uncons [1]
--   Just (1,[])
--   
--   >>> uncons [1, 2, 3]
--   Just (1,[2,3])
--   
uncons :: [a] -> Maybe (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] -- | 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] -- | <math>. Extract the elements after the head of a list, which -- must be non-empty. -- --
--   >>> tail [1, 2, 3]
--   [2,3]
--   
--   >>> tail [1]
--   []
--   
--   >>> tail []
--   *** Exception: Prelude.tail: empty list
--   
tail :: [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]) -- | 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]) -- | <math>. scanr1 is a variant of scanr that has no -- starting value argument. -- --
--   >>> scanr1 (+) [1..4]
--   [10,9,7,4]
--   
--   >>> scanr1 (+) []
--   []
--   
--   >>> scanr1 (-) [1..4]
--   [-2,3,-1,4]
--   
--   >>> scanr1 (&&) [True, False, True, True]
--   [False,False,True,True]
--   
--   >>> scanr1 (||) [True, True, False, False]
--   [True,True,False,False]
--   
--   >>> force $ scanr1 (+) [1..]
--   *** Exception: stack overflow
--   
scanr1 :: (a -> a -> a) -> [a] -> [a] -- | <math>. scanr is the right-to-left dual of scanl. -- Note that the order of parameters on the accumulating function are -- reversed compared to scanl. Also note that -- --
--   head (scanr f z xs) == foldr f z xs.
--   
-- --
--   >>> scanr (+) 0 [1..4]
--   [10,9,7,4,0]
--   
--   >>> scanr (+) 42 []
--   [42]
--   
--   >>> scanr (-) 100 [1..4]
--   [98,-97,99,-96,100]
--   
--   >>> scanr (\nextChar reversedString -> nextChar : reversedString) "foo" ['a', 'b', 'c', 'd']
--   ["abcdfoo","bcdfoo","cdfoo","dfoo","foo"]
--   
--   >>> force $ scanr (+) 0 [1..]
--   *** Exception: stack overflow
--   
scanr :: (a -> b -> b) -> b -> [a] -> [b] -- | <math>. scanl1 is a variant of scanl that has no -- starting value argument: -- --
--   scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
--   
-- --
--   >>> scanl1 (+) [1..4]
--   [1,3,6,10]
--   
--   >>> scanl1 (+) []
--   []
--   
--   >>> scanl1 (-) [1..4]
--   [1,-1,-4,-8]
--   
--   >>> scanl1 (&&) [True, False, True, True]
--   [True,False,False,False]
--   
--   >>> scanl1 (||) [False, False, True, True]
--   [False,False,True,True]
--   
--   >>> scanl1 (+) [1..]
--   * Hangs forever *
--   
scanl1 :: (a -> a -> a) -> [a] -> [a] -- | <math>. A strict version of scanl. scanl' :: (b -> a -> b) -> b -> [a] -> [b] -- | <math>. 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 (+) 0 [1..4]
--   [0,1,3,6,10]
--   
--   >>> scanl (+) 42 []
--   [42]
--   
--   >>> scanl (-) 100 [1..4]
--   [100,99,97,94,90]
--   
--   >>> scanl (\reversedString nextChar -> nextChar : reversedString) "foo" ['a', 'b', 'c', 'd']
--   ["foo","afoo","bafoo","cbafoo","dcbafoo"]
--   
--   >>> scanl (+) 0 [1..]
--   * Hangs forever *
--   
scanl :: (b -> a -> b) -> b -> [a] -> [b] -- | reverse xs returns the elements of xs in -- reverse order. xs must be finite. -- --
--   >>> reverse []
--   []
--   
--   >>> reverse [42]
--   [42]
--   
--   >>> reverse [2,5,7]
--   [7,5,2]
--   
--   >>> reverse [1..]
--   * Hangs forever *
--   
reverse :: [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 0 True
--   []
--   
--   >>> replicate (-1) True
--   []
--   
--   >>> replicate 4 True
--   [True,True,True,True]
--   
replicate :: Int -> a -> [a] -- | repeat x is an infinite list, with x the -- value of every element. -- --
--   >>> take 20 $ repeat 17
--   [17,17,17,17,17,17,17,17,17...
--   
repeat :: a -> [a] -- | <math>. lookup key assocs looks up a key in an -- association list. -- --
--   >>> lookup 2 []
--   Nothing
--   
--   >>> lookup 2 [(1, "first")]
--   Nothing
--   
--   >>> lookup 2 [(1, "first"), (2, "second"), (3, "third")]
--   Just "second"
--   
lookup :: Eq a => a -> [(a, b)] -> Maybe b -- | <math>. Extract the last element of a list, which must be finite -- and non-empty. -- --
--   >>> last [1, 2, 3]
--   3
--   
--   >>> last [1..]
--   * Hangs forever *
--   
--   >>> last []
--   *** Exception: Prelude.last: empty list
--   
last :: [a] -> a -- | iterate' is the strict version of iterate. -- -- It forces the result of each application of the function to weak head -- normal form (WHNF) before proceeding. iterate' :: (a -> a) -> 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. -- --
--   >>> take 10 $ iterate not True
--   [True,False,True,False...
--   
--   >>> take 10 $ iterate (+3) 42
--   [42,45,48,51,54,57,60,63...
--   
iterate :: (a -> a) -> a -> [a] -- | <math>. Return all the elements of a list except the last one. -- The list must be non-empty. -- --
--   >>> init [1, 2, 3]
--   [1,2]
--   
--   >>> init [1]
--   []
--   
--   >>> init []
--   *** Exception: Prelude.init: empty list
--   
init :: [a] -> [a] -- | <math>. Extract the first element of a list, which must be -- non-empty. -- --
--   >>> head [1, 2, 3]
--   1
--   
--   >>> head [1..]
--   1
--   
--   >>> head []
--   *** Exception: Prelude.head: empty list
--   
head :: [a] -> a -- | A strict version of foldl1. foldl1' :: (a -> a -> a) -> [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] -- | 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] -- | 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 []
--   *** Exception: Prelude.cycle: empty list
--   
--   >>> take 20 $ cycle [42]
--   [42,42,42,42,42,42,42,42,42,42...
--   
--   >>> take 20 $ cycle [2, 5, 7]
--   [2,5,7,2,5,7,2,5,7,2,5,7...
--   
cycle :: [a] -> [a] -- | 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]) -- | 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', 'b', 'c'] !! 0
--   'a'
--   
--   >>> ['a', 'b', 'c'] !! 2
--   'c'
--   
--   >>> ['a', 'b', 'c'] !! 3
--   *** Exception: Prelude.!!: index too large
--   
--   >>> ['a', 'b', 'c'] !! (-1)
--   *** Exception: Prelude.!!: negative index
--   
(!!) :: [a] -> Int -> a infixl 9 !! -- | The maybeToList function returns an empty list when given -- Nothing or a singleton list when given Just. -- --

Examples

-- -- Basic usage: -- --
--   >>> maybeToList (Just 7)
--   [7]
--   
-- --
--   >>> maybeToList Nothing
--   []
--   
-- -- One can use maybeToList to avoid pattern matching when combined -- with a function that (safely) works on lists: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> sum $ maybeToList (readMaybe "3")
--   3
--   
--   >>> sum $ maybeToList (readMaybe "")
--   0
--   
maybeToList :: Maybe a -> [a] -- | 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. -- --

Examples

-- -- Basic usage: -- --
--   >>> 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 -- | The mapMaybe function is a version of map which can -- throw out elements. In particular, the functional argument returns -- something of type Maybe b. If this is Nothing, -- no element is added on to the result list. If it is Just -- b, then b is included in the result list. -- --

Examples

-- -- Using mapMaybe f x is a shortcut for -- catMaybes $ map f x in most cases: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> let readMaybeInt = readMaybe :: String -> Maybe Int
--   
--   >>> mapMaybe readMaybeInt ["1", "Foo", "3"]
--   [1,3]
--   
--   >>> catMaybes $ map readMaybeInt ["1", "Foo", "3"]
--   [1,3]
--   
-- -- If we map the Just constructor, the entire list should be -- returned: -- --
--   >>> mapMaybe Just [1,2,3]
--   [1,2,3]
--   
mapMaybe :: (a -> Maybe b) -> [a] -> [b] -- | The listToMaybe function returns Nothing on an empty -- list or Just a where a is the first element -- of the list. -- --

Examples

-- -- Basic usage: -- --
--   >>> listToMaybe []
--   Nothing
--   
-- --
--   >>> listToMaybe [9]
--   Just 9
--   
-- --
--   >>> listToMaybe [1,2,3]
--   Just 1
--   
-- -- Composing maybeToList with listToMaybe should be the -- identity on singleton/empty lists: -- --
--   >>> maybeToList $ listToMaybe [5]
--   [5]
--   
--   >>> maybeToList $ listToMaybe []
--   []
--   
-- -- But not on lists with more than one element: -- --
--   >>> maybeToList $ listToMaybe [1,2,3]
--   [1]
--   
listToMaybe :: [a] -> Maybe a -- | The isNothing function returns True iff its argument is -- Nothing. -- --

Examples

-- -- Basic usage: -- --
--   >>> isNothing (Just 3)
--   False
--   
-- --
--   >>> isNothing (Just ())
--   False
--   
-- --
--   >>> isNothing Nothing
--   True
--   
-- -- Only the outer constructor is taken into consideration: -- --
--   >>> isNothing (Just Nothing)
--   False
--   
isNothing :: Maybe a -> Bool -- | The isJust function returns True iff its argument is of -- the form Just _. -- --

Examples

-- -- Basic usage: -- --
--   >>> isJust (Just 3)
--   True
--   
-- --
--   >>> isJust (Just ())
--   True
--   
-- --
--   >>> isJust Nothing
--   False
--   
-- -- Only the outer constructor is taken into consideration: -- --
--   >>> isJust (Just Nothing)
--   True
--   
isJust :: Maybe a -> Bool -- | The fromMaybe function takes a default value and a Maybe -- value. If the Maybe is Nothing, it returns the default -- value; otherwise, it returns the value contained in the Maybe. -- --

Examples

-- -- Basic usage: -- --
--   >>> fromMaybe "" (Just "Hello, World!")
--   "Hello, World!"
--   
-- --
--   >>> fromMaybe "" Nothing
--   ""
--   
-- -- Read an integer from a string using readMaybe. If we fail to -- parse an integer, we want to return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> fromMaybe 0 (readMaybe "5")
--   5
--   
--   >>> fromMaybe 0 (readMaybe "")
--   0
--   
fromMaybe :: a -> Maybe a -> a -- | The fromJust function extracts the element out of a Just -- and throws an error if its argument is Nothing. -- --

Examples

-- -- Basic usage: -- --
--   >>> fromJust (Just 1)
--   1
--   
-- --
--   >>> 2 * (fromJust (Just 10))
--   20
--   
-- --
--   >>> 2 * (fromJust Nothing)
--   *** Exception: Maybe.fromJust: Nothing
--   ...
--   
fromJust :: HasCallStack => Maybe a -> a -- | The catMaybes function takes a list of Maybes and -- returns a list of all the Just values. -- --

Examples

-- -- Basic usage: -- --
--   >>> catMaybes [Just 1, Nothing, Just 3]
--   [1,3]
--   
-- -- When constructing a list of Maybe values, catMaybes can -- be used to return all of the "success" results (if the list is the -- result of a map, then mapMaybe would be more -- appropriate): -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
--   [Just 1,Nothing,Just 3]
--   
--   >>> catMaybes $ [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
--   [1,3]
--   
catMaybes :: [Maybe a] -> [a] -- | 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. -- --

Examples

-- -- Basic usage: -- --
--   >>> 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 -- | on b u x y runs the binary function b -- on the results of applying unary function u to two -- arguments x and y. From the opposite perspective, it -- transforms two inputs and combines the outputs. -- --
--   ((+) `on` f) x y = f x + f y
--   
-- -- Typical usage: sortBy (compare `on` -- fst). -- -- Algebraic properties: -- -- on :: (b -> b -> c) -> (a -> b) -> a -> a -> c infixl 0 `on` -- | fix f is the least fixed point of the function -- f, i.e. the least defined x such that f x = -- x. -- -- For example, we can write the factorial function using direct -- recursion as -- --
--   >>> let fac n = if n <= 1 then 1 else n * fac (n-1) in fac 5
--   120
--   
-- -- This uses the fact that Haskell’s let introduces recursive -- bindings. We can rewrite this definition using fix, -- --
--   >>> fix (\rec n -> if n <= 1 then 1 else n * rec (n-1)) 5
--   120
--   
-- -- Instead of making a recursive call, we introduce a dummy parameter -- rec; when used within fix, this parameter then refers -- to fix’s argument, hence the recursion is reintroduced. fix :: (a -> a) -> a -- | & 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 & -- | void value discards or ignores the result of -- evaluation, such as the return value of an IO action. -- --

Examples

-- -- Replace the contents of a Maybe Int with unit: -- --
--   >>> 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
--   
-- --

Examples

-- -- Apply (+1) to a list, a Just and a Right: -- --
--   >>> 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 <&> -- | 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. -- --

Examples

-- -- Convert from a Maybe Int to a Maybe -- String using show: -- --
--   >>> 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 <$> -- | Flipped version of <$. -- --

Examples

-- -- Replace the contents of a Maybe Int with a -- constant String: -- --
--   >>> 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 $> -- | uncurry converts a curried function to a function on pairs. -- --

Examples

-- --
--   >>> 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 -- | Swap the components of a pair. swap :: (a, b) -> (b, a) -- | curry converts an uncurried function to a curried function. -- --

Examples

-- --
--   >>> curry fst 1 2
--   1
--   
curry :: ((a, b) -> c) -> a -> b -> c -- | A Version represents the version of a software entity. -- -- An instance of Eq is provided, which implements exact equality -- modulo reordering of the tags in the versionTags field. -- -- An instance of Ord is also provided, which gives lexicographic -- ordering on the versionBranch fields (i.e. 2.1 > 2.0, 1.2.3 -- > 1.2.2, etc.). This is expected to be sufficient for many uses, -- but note that you may need to use a more specific ordering for your -- versioning scheme. For example, some versioning schemes may include -- pre-releases which have tags "pre1", "pre2", and so -- on, and these would need to be taken into account when determining -- ordering. In some cases, date ordering may be more appropriate, so the -- application would have to look for date tags in the -- versionTags field and compare those. The bottom line is, don't -- always assume that compare and other Ord operations are -- the right thing for every Version. -- -- Similarly, concrete representations of versions may differ. One -- possible concrete representation is provided (see showVersion -- and parseVersion), but depending on the application a different -- concrete representation may be more appropriate. data Version Version :: [Int] -> [String] -> Version -- | The numeric branch for this version. This reflects the fact that most -- software versions are tree-structured; there is a main trunk which is -- tagged with versions at various points (1,2,3...), and the first -- branch off the trunk after version 3 is 3.1, the second branch off the -- trunk after version 3 is 3.2, and so on. The tree can be branched -- arbitrarily, just by adding more digits. -- -- We represent the branch as a list of Int, so version 3.2.1 -- becomes [3,2,1]. Lexicographic ordering (i.e. the default instance of -- Ord for [Int]) gives the natural ordering of branches. [versionBranch] :: Version -> [Int] -- | A version can be tagged with an arbitrary list of strings. The -- interpretation of the list of tags is entirely dependent on the entity -- that this version applies to. [versionTags] :: Version -> [String] -- | Construct tag-less Version makeVersion :: [Int] -> Version -- | This is the "back door" into the IO monad, allowing IO -- computation to be performed at any time. For this to be safe, the -- IO computation should be free of side effects and independent -- of its environment. -- -- If the I/O computation wrapped in unsafePerformIO performs side -- effects, then the relative order in which those side effects take -- place (relative to the main I/O trunk, or other calls to -- unsafePerformIO) is indeterminate. Furthermore, when using -- unsafePerformIO to cause side-effects, you should take the -- following precautions to ensure the side effects are performed as many -- times as you expect them to be. Note that these precautions are -- necessary for GHC, but may not be sufficient, and other compilers may -- require different precautions: -- -- -- -- It is less well known that unsafePerformIO is not type safe. -- For example: -- --
--   test :: IORef [a]
--   test = unsafePerformIO $ newIORef []
--   
--   main = do
--           writeIORef test [42]
--           bang <- readIORef test
--           print (bang :: [Char])
--   
-- -- This program will core dump. This problem with polymorphic references -- is well known in the ML community, and does not arise with normal -- monadic use of references. There is no easy way to make it impossible -- once you use unsafePerformIO. Indeed, it is possible to write -- coerce :: a -> b with the help of unsafePerformIO. -- So be careful! unsafePerformIO :: IO a -> a -- | unsafeInterleaveIO allows an IO computation to be -- deferred lazily. When passed a value of type IO a, the -- IO will only be performed when the value of the a is -- demanded. This is used to implement lazy file reading, see -- hGetContents. unsafeInterleaveIO :: 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 -- | An MVar (pronounced "em-var") is a synchronising variable, used -- for communication between concurrent threads. It can be thought of as -- a box, which may be empty or full. data MVar a -- | A non-blocking version of takeMVar. The tryTakeMVar -- function returns immediately, with Nothing if the MVar -- was empty, or Just a if the MVar was full with -- contents a. After tryTakeMVar, the MVar is left -- empty. tryTakeMVar :: MVar a -> IO (Maybe a) -- | A non-blocking version of readMVar. The tryReadMVar -- function returns immediately, with Nothing if the MVar -- was empty, or Just a if the MVar was full with -- contents a. tryReadMVar :: MVar a -> IO (Maybe a) -- | A non-blocking version of putMVar. The tryPutMVar -- function attempts to put the value a into the MVar, -- returning True if it was successful, or False otherwise. tryPutMVar :: MVar a -> a -> IO Bool -- | Return the contents of the MVar. If the MVar is -- currently empty, takeMVar will wait until it is full. After a -- takeMVar, the MVar is left empty. -- -- There are two further important properties of takeMVar: -- -- takeMVar :: MVar a -> IO a -- | Atomically read the contents of an MVar. If the MVar is -- currently empty, readMVar will wait until it is full. -- readMVar is guaranteed to receive the next putMVar. -- -- readMVar is multiple-wakeup, so when multiple readers are -- blocked on an MVar, all of them are woken up at the same time. -- -- Compatibility note: Prior to base 4.7, readMVar was a -- combination of takeMVar and putMVar. This mean that in -- the presence of other threads attempting to putMVar, -- readMVar could block. Furthermore, readMVar would not -- receive the next putMVar if there was already a pending thread -- blocked on takeMVar. The old behavior can be recovered by -- implementing 'readMVar as follows: -- --
--   readMVar :: MVar a -> IO a
--   readMVar m =
--     mask_ $ do
--       a <- takeMVar m
--       putMVar m a
--       return a
--   
readMVar :: MVar a -> IO a -- | Put a value into an MVar. If the MVar is currently full, -- putMVar will wait until it becomes empty. -- -- There are two further important properties of putMVar: -- -- putMVar :: MVar a -> a -> IO () -- | Create an MVar which contains the supplied value. newMVar :: a -> IO (MVar a) -- | Create an MVar which is initially empty. newEmptyMVar :: IO (MVar a) -- | Check whether a given MVar is empty. -- -- Notice that the boolean value returned is just a snapshot of the state -- of the MVar. By the time you get to react on its result, the MVar may -- have been filled (or emptied) - so be extremely careful when using -- this operation. Use tryTakeMVar instead if possible. isEmptyMVar :: MVar a -> IO Bool -- | 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 -- | Monads that also support choice and failure. class (Alternative m, Monad m) => MonadPlus (m :: Type -> Type) -- | 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 -- | A monoid on applicative functors. -- -- If defined, some and many should be the least solutions -- of the equations: -- -- class Applicative f => Alternative (f :: Type -> Type) -- | The identity of <|> empty :: Alternative f => f a -- | An associative binary operation (<|>) :: Alternative f => f a -> f a -> f a -- | One or more. some :: Alternative f => f a -> f [a] -- | Zero or more. many :: Alternative f => f a -> f [a] infixl 3 <|> -- | Conditional execution of Applicative expressions. For example, -- --
--   when debug (putStrLn "Debugging")
--   
-- -- will output the string Debugging if the Boolean value -- debug is True, and otherwise do nothing. when :: Applicative f => Bool -> f () -> f () -- | until p f yields the result of applying f -- until p holds. until :: (a -> Bool) -> (a -> a) -> a -> a -- | The fromEnum method restricted to the type Char. ord :: Char -> Int -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM5 :: Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM4 :: Monad m => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM3 :: Monad m => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right. For example, -- --
--   liftM2 (+) [0,1] [0,2] = [0,2,1,3]
--   liftM2 (+) (Just 1) Nothing = Nothing
--   
liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r -- | Lift a ternary function to actions. liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d -- | Lift a function to actions. Equivalent to Functor's fmap but -- implemented using only Applicative's methods: `liftA f a = pure -- f * a` -- -- As such this function may be used to implement a Functor -- instance from an Applicative one. liftA :: Applicative f => (a -> b) -> f a -> f b -- | flip f takes its (first) two arguments in the reverse -- order of f. -- --
--   >>> flip (++) "hello" "world"
--   "worldhello"
--   
flip :: (a -> b -> c) -> b -> a -> c -- | 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 -- | 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 -- | In many situations, the liftM operations can be replaced by -- uses of ap, which promotes function application. -- --
--   return f `ap` x1 `ap` ... `ap` xn
--   
-- -- is equivalent to -- --
--   liftMn f x1 x2 ... xn
--   
ap :: Monad m => m (a -> b) -> m a -> m b -- | Same as >>=, but with the arguments interchanged. (=<<) :: Monad m => (a -> m b) -> m a -> m b infixr 1 =<< -- | A variant of <*> with the arguments reversed. (<**>) :: Applicative f => f a -> f (a -> b) -> f b infixl 4 <**> -- | 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 :: RuntimeRep) a (b :: TYPE r). (a -> b) -> a -> b infixr 0 $! -- | 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 :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => a -- | A variant of error that does not produce a stack trace. errorWithoutStackTrace :: forall (r :: RuntimeRep) (a :: TYPE r). [Char] -> a -- | error stops execution and displays an error message. error :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => [Char] -> 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 <math> rather than <math> stimesIdempotentMonoid :: (Integral b, Monoid a) => b -> a -> a -- | 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 :: e -> SomeException -- | Boolean "and", lazy in the second argument (&&) :: Bool -> Bool -> Bool infixr 3 && -- | Boolean "not" not :: Bool -> Bool -- | Boolean "or", lazy in the second argument (||) :: Bool -> Bool -> Bool infixr 2 || -- | Make a Functor over the second argument of a Bifunctor. newtype WrappedBifunctor (p :: k -> k1 -> Type) (a :: k) (b :: k1) WrapBifunctor :: p a b -> WrappedBifunctor (p :: k -> k1 -> Type) (a :: k) (b :: k1) [unwrapBifunctor] :: WrappedBifunctor (p :: k -> k1 -> Type) (a :: k) (b :: k1) -> p a b (<<$>>) :: (a -> b) -> a -> b infixl 4 <<$>> -- | A compact representation of a Word8 vector. -- -- It has a lower memory overhead than a ByteString and does not -- contribute to heap fragmentation. It can be converted to or from a -- ByteString (at the cost of copying the string data). It -- supports very few other operations. -- -- It is suitable for use as an internal representation for code that -- needs to keep many short strings in memory, but it should not -- be used as an interchange type. That is, it should not generally be -- used in public APIs. The ByteString type is usually more -- suitable for use in interfaces; it is more flexible and it supports a -- wide range of operations. data ShortByteString -- | A space-efficient representation of a Word8 vector, supporting -- many efficient operations. -- -- A ByteString contains 8-bit bytes, or by using the operations -- from Data.ByteString.Char8 it can be interpreted as containing -- 8-bit characters. data ByteString -- | Lift a ternary function into a Comonad with zipping liftW3 :: ComonadApply w => (a -> b -> c -> d) -> w a -> w b -> w c -> w d -- | Lift a binary function into a Comonad with zipping liftW2 :: ComonadApply w => (a -> b -> c) -> w a -> w b -> w c -- | A variant of <@> with the arguments reversed. (<@@>) :: ComonadApply w => w a -> w (a -> b) -> w b infixl 4 <@@> -- | Left-to-right Cokleisli composition (=>=) :: Comonad w => (w a -> b) -> (w b -> c) -> w a -> c infixr 1 =>= -- | Right-to-left Cokleisli composition (=<=) :: Comonad w => (w b -> c) -> (w a -> b) -> w a -> c infixr 1 =<= -- | extend in operator form (<<=) :: Comonad w => (w a -> b) -> w a -> w b infixr 1 <<= -- | extend with the arguments swapped. Dual to >>= for -- a Monad. (=>>) :: Comonad w => w a -> (w a -> b) -> w b infixl 1 =>> -- | Comonadic fixed point à la Kenneth Foner: -- -- This is the evaluate function from his "Getting a Quick -- Fix on Comonads" talk. kfix :: ComonadApply w => w (w a -> a) -> w a -- | Comonadic fixed point à la Dominic Orchard cfix :: Comonad w => (w a -> a) -> w a -- | Comonadic fixed point à la David Menendez wfix :: Comonad w => w (w a -> a) -> a -- | A suitable default definition for fmap for a Comonad. -- Promotes a function to a comonad. -- -- You can only safely use liftW to define fmap if your -- Comonad defines extend, not just duplicate, since -- defining extend in terms of duplicate uses fmap! -- --
--   fmap f = liftW f = extend (f . extract)
--   
liftW :: Comonad w => (a -> b) -> w a -> w b -- | There are two ways to define a comonad: -- -- I. Provide definitions for extract and extend satisfying -- these laws: -- --
--   extend extract      = id
--   extract . extend f  = f
--   extend f . extend g = extend (f . extend g)
--   
-- -- In this case, you may simply set fmap = liftW. -- -- These laws are directly analogous to the laws for monads and perhaps -- can be made clearer by viewing them as laws stating that Cokleisli -- composition must be associative, and has extract for a unit: -- --
--   f =>= extract   = f
--   extract =>= f   = f
--   (f =>= g) =>= h = f =>= (g =>= h)
--   
-- -- II. Alternately, you may choose to provide definitions for -- fmap, extract, and duplicate satisfying these -- laws: -- --
--   extract . duplicate      = id
--   fmap extract . duplicate = id
--   duplicate . duplicate    = fmap duplicate . duplicate
--   
-- -- In this case you may not rely on the ability to define fmap in -- terms of liftW. -- -- You may of course, choose to define both duplicate and -- extend. In that case you must also satisfy these laws: -- --
--   extend f  = fmap f . duplicate
--   duplicate = extend id
--   fmap f    = extend (f . extract)
--   
-- -- These are the default definitions of extend and -- duplicate and the definition of liftW respectively. class Functor w => Comonad (w :: Type -> Type) -- |
--   extract . fmap f = f . extract
--   
extract :: Comonad w => w a -> a -- |
--   duplicate = extend id
--   fmap (fmap f) . duplicate = duplicate . fmap f
--   
duplicate :: Comonad w => w a -> w (w a) -- |
--   extend f = fmap f . duplicate
--   
extend :: Comonad w => (w a -> b) -> w a -> w b -- | ComonadApply is to Comonad like Applicative -- is to Monad. -- -- Mathematically, it is a strong lax symmetric semi-monoidal comonad on -- the category Hask of Haskell types. That it to say that -- w is a strong lax symmetric semi-monoidal functor on Hask, -- where both extract and duplicate are symmetric monoidal -- natural transformations. -- -- Laws: -- --
--   (.) <$> u <@> v <@> w = u <@> (v <@> w)
--   extract (p <@> q) = extract p (extract q)
--   duplicate (p <@> q) = (<@>) <$> duplicate p <@> duplicate q
--   
-- -- If our type is both a ComonadApply and Applicative we -- further require -- --
--   (<*>) = (<@>)
--   
-- -- Finally, if you choose to define (<@) and (@>), -- the results of your definitions should match the following laws: -- --
--   a @> b = const id <$> a <@> b
--   a <@ b = const <$> a <@> b
--   
class Comonad w => ComonadApply (w :: Type -> Type) (<@>) :: ComonadApply w => w (a -> b) -> w a -> w b (@>) :: ComonadApply w => w a -> w b -> w b (<@) :: ComonadApply w => w a -> w b -> w a infixl 4 <@ infixl 4 <@> infixl 4 @> -- | The Cokleisli Arrows of a given Comonad newtype Cokleisli (w :: k -> Type) (a :: k) b Cokleisli :: (w a -> b) -> Cokleisli (w :: k -> Type) (a :: k) b [runCokleisli] :: Cokleisli (w :: k -> Type) (a :: k) b -> w a -> b -- | A map of integers to values a. data IntMap a -- | A set of integers. data IntSet -- | A Map from keys k to values a. -- -- The Semigroup operation for Map is union, which -- prefers values from the left operand. If m1 maps a key -- k to a value a1, and m2 maps the same key -- to a different value a2, then their union m1 <> -- m2 maps k to a1. data Map k a -- | General-purpose finite sequences. data Seq a -- | A set of values a. data Set a -- |
--   chosen = choose id
--   
chosen :: Decidable f => f b -> f c -> f (Either b c) -- |
--   lost = lose id
--   
lost :: Decidable f => f Void -- | This is the divisible analogue of liftA. It gives a viable -- default definition for contramap in terms of the members of -- Divisible. -- --
--   liftD f = divide ((,) () . f) conquer
--   
liftD :: Divisible f => (a -> b) -> f b -> f a -- | Redundant, but provided for symmetry. -- --
--   conquered = conquer
--   
conquered :: Divisible f => f () -- |
--   divided = divide id
--   
divided :: Divisible f => f a -> f b -> f (a, b) -- | A Divisible contravariant functor is the contravariant analogue -- of Applicative. -- -- Continuing the intuition that Contravariant functors consume -- input, a Divisible contravariant functor also has the ability -- to be composed "beside" another contravariant functor. -- -- Serializers provide a good example of Divisible contravariant -- functors. To begin let's start with the type of serializers for -- specific types: -- --
--   newtype Serializer a = Serializer { runSerializer :: a -> ByteString }
--   
-- -- This is a contravariant functor: -- --
--   instance Contravariant Serializer where
--     contramap f s = Serializer (runSerializer s . f)
--   
-- -- That is, given a serializer for a (s :: Serializer -- a), and a way to turn bs into as (a mapping -- f :: b -> a), we have a serializer for b: -- contramap f s :: Serializer b. -- -- Divisible gives us a way to combine two serializers that focus on -- different parts of a structure. If we postulate the existance of two -- primitive serializers - string :: Serializer String and -- int :: Serializer Int, we would like to be able to combine -- these into a serializer for pairs of Strings and -- Ints. How can we do this? Simply run both serializers and -- combine their output! -- --
--   data StringAndInt = StringAndInt String Int
--   
--   stringAndInt :: Serializer StringAndInt
--   stringAndInt = Serializer $ \(StringAndInt s i) ->
--     let sBytes = runSerializer string s
--         iBytes = runSerializer int i
--     in sBytes <> iBytes
--   
-- -- divide is a generalization by also taking a contramap -- like function to split any a into a pair. This conveniently -- allows you to target fields of a record, for instance, by extracting -- the values under two fields and combining them into a tuple. -- -- To complete the example, here is how to write stringAndInt -- using a Divisible instance: -- --
--   instance Divisible Serializer where
--     conquer = Serializer (const mempty)
--   
--     divide toBC bSerializer cSerializer = Serializer $ \a ->
--       case toBC a of
--         (b, c) ->
--           let bBytes = runSerializer bSerializer b
--               cBytes = runSerializer cSerializer c
--           in bBytes <> cBytes
--   
--   stringAndInt :: Serializer StringAndInt
--   stringAndInt =
--     divide (\(StringAndInt s i) -> (s, i)) string int
--   
class Contravariant f => Divisible (f :: Type -> Type) divide :: Divisible f => (a -> (b, c)) -> f b -> f c -> f a -- | Conquer acts as an identity for combining Divisible functors. conquer :: Divisible f => f a -- | A Decidable contravariant functor is the contravariant analogue -- of Alternative. -- -- Noting the superclass constraint that f must also be -- Divisible, a Decidable functor has the ability to "fan -- out" input, under the intuition that contravariant functors consume -- input. -- -- In the discussion for Divisible, an example was demonstrated -- with Serializers, that turn as into -- ByteStrings. Divisible allowed us to serialize the -- product of multiple values by concatenation. By making our -- Serializer also Decidable- we now have the ability -- to serialize the sum of multiple values - for example different -- constructors in an ADT. -- -- Consider serializing arbitrary identifiers that can be either -- Strings or Ints: -- --
--   data Identifier = StringId String | IntId Int
--   
-- -- We know we have serializers for Strings and Ints, -- but how do we combine them into a Serializer for -- Identifier? Essentially, our Serializer needs to -- scrutinise the incoming value and choose how to serialize it: -- --
--   identifier :: Serializer Identifier
--   identifier = Serializer $ \identifier ->
--     case identifier of
--       StringId s -> runSerializer string s
--       IntId i -> runSerializer int i
--   
-- -- It is exactly this notion of choice that Decidable encodes. -- Hence if we add an instance of Decidable for -- Serializer... -- --
--   instance Decidable Serializer where
--     lose f = Serializer $ \a -> absurd (f a)
--     choose split l r = Serializer $ \a ->
--       either (runSerializer l) (runSerializer r) (split a)
--   
-- -- Then our identifier Serializer is -- --
--   identifier :: Serializer Identifier
--   identifier = choose toEither string int where
--     toEither (StringId s) = Left s
--     toEither (IntId i) = Right i
--   
class Divisible f => Decidable (f :: Type -> Type) -- | Acts as identity to choose. lose :: Decidable f => (a -> Void) -> f a choose :: Decidable f => (a -> Either b c) -> f b -> f c -> f a -- | A class of bifunctors that can be fully evaluated. class NFData2 (p :: Type -> Type -> Type) -- | liftRnf2 should reduce its argument to normal form (that is, -- fully evaluate all sub-components), given functions to reduce -- a and b arguments respectively, and then return -- (). -- -- Note: Unlike for the unary liftRnf, there is currently -- no support for generically deriving liftRnf2. liftRnf2 :: NFData2 p => (a -> ()) -> (b -> ()) -> p a b -> () -- | A class of functors that can be fully evaluated. class NFData1 (f :: TYPE LiftedRep -> TYPE LiftedRep) -- | liftRnf should reduce its argument to normal form (that is, -- fully evaluate all sub-components), given an argument to reduce -- a arguments, and then return (). -- -- See rnf for the generic deriving. liftRnf :: NFData1 f => (a -> ()) -> f a -> () -- | A class of types that can be fully evaluated. class NFData a -- | rnf should reduce its argument to normal form (that is, fully -- evaluate all sub-components), and then return (). -- --

Generic NFData deriving

-- -- Starting with GHC 7.2, you can automatically derive instances for -- types possessing a Generic instance. -- -- Note: Generic1 can be auto-derived starting with GHC 7.4 -- --
--   {-# LANGUAGE DeriveGeneric #-}
--   
--   import GHC.Generics (Generic, Generic1)
--   import Control.DeepSeq
--   
--   data Foo a = Foo a String
--                deriving (Eq, Generic, Generic1)
--   
--   instance NFData a => NFData (Foo a)
--   instance NFData1 Foo
--   
--   data Colour = Red | Green | Blue
--                 deriving Generic
--   
--   instance NFData Colour
--   
-- -- Starting with GHC 7.10, the example above can be written more -- concisely by enabling the new DeriveAnyClass extension: -- --
--   {-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
--   
--   import GHC.Generics (Generic)
--   import Control.DeepSeq
--   
--   data Foo a = Foo a String
--                deriving (Eq, Generic, Generic1, NFData, NFData1)
--   
--   data Colour = Red | Green | Blue
--                 deriving (Generic, NFData)
--   
-- --

Compatibility with previous deepseq versions

-- -- Prior to version 1.4.0.0, the default implementation of the rnf -- method was defined as -- --
--   rnf a = seq a ()
--   
-- -- However, starting with deepseq-1.4.0.0, the default -- implementation is based on DefaultSignatures allowing for -- more accurate auto-derived NFData instances. If you need the -- previously used exact default rnf method implementation -- semantics, use -- --
--   instance NFData Colour where rnf x = seq x ()
--   
-- -- or alternatively -- --
--   instance NFData Colour where rnf = rwhnf
--   
-- -- or -- --
--   {-# LANGUAGE BangPatterns #-}
--   instance NFData Colour where rnf !_ = ()
--   
rnf :: NFData a => a -> () -- | Reduce to weak head normal form -- -- Equivalent to \x -> seq x (). -- -- Useful for defining NFData for types for which NF=WHNF holds. -- --
--   data T = C1 | C2 | C3
--   instance NFData T where rnf = rwhnf
--   
rwhnf :: a -> () -- | Lift the standard rnf function through the type constructor. rnf2 :: (NFData2 p, NFData a, NFData b) => p a b -> () -- | Lift the standard rnf function through the type constructor. rnf1 :: (NFData1 f, NFData a) => f a -> () -- | a variant of deepseq that is useful in some circumstances: -- --
--   force x = x `deepseq` x
--   
-- -- force x fully evaluates x, and then returns it. Note -- that force x only performs evaluation when the value of -- force x itself is demanded, so essentially it turns shallow -- evaluation into deep evaluation. -- -- force can be conveniently used in combination with -- ViewPatterns: -- --
--   {-# LANGUAGE BangPatterns, ViewPatterns #-}
--   import Control.DeepSeq
--   
--   someFun :: ComplexData -> SomeResult
--   someFun (force -> !arg) = {- 'arg' will be fully evaluated -}
--   
-- -- Another useful application is to combine force with -- evaluate in order to force deep evaluation relative to other -- IO operations: -- --
--   import Control.Exception (evaluate)
--   import Control.DeepSeq
--   
--   main = do
--     result <- evaluate $ force $ pureComputation
--     {- 'result' will be fully evaluated at this point -}
--     return ()
--   
-- -- Finally, here's an exception safe variant of the readFile' -- example: -- --
--   readFile' :: FilePath -> IO String
--   readFile' fn = bracket (openFile fn ReadMode) hClose $ \h ->
--                          evaluate . force =<< hGetContents h
--   
force :: NFData a => a -> a -- | deepseq: fully evaluates the first argument, before returning -- the second. -- -- The name deepseq is used to illustrate the relationship to -- seq: where seq is shallow in the sense that it only -- evaluates the top level of its argument, deepseq traverses the -- entire data structure evaluating it completely. -- -- deepseq can be useful for forcing pending exceptions, -- eradicating space leaks, or forcing lazy I/O to happen. It is also -- useful in conjunction with parallel Strategies (see the -- parallel package). -- -- There is no guarantee about the ordering of evaluation. The -- implementation may evaluate the components of the structure in any -- order or in parallel. To impose an actual order on evaluation, use -- pseq from Control.Parallel in the parallel -- package. deepseq :: NFData a => a -> b -> b -- | Deeply strict version of <$>. (<$!!>) :: (Monad m, NFData b) => (a -> b) -> m a -> m b infixl 4 <$!!> -- | the deep analogue of $!. In the expression f $!! x, -- x is fully evaluated before the function f is -- applied to it. ($!!) :: NFData a => (a -> b) -> a -> b infixr 0 $!! -- | A difference list is an abstraction representing a list that supports -- <math>(1) append and snoc operations, -- making it useful for replacing frequent applications of ++ such -- as logging and pretty printing (esp. if those uses of ++ are -- left-nested). data DList a -- | Swap the Left and Right sides of an Either. -- --
--   >>> swapEither (Right 3)
--   Left 3
--   
-- --
--   >>> swapEither (Left "error")
--   Right "error"
--   
swapEither :: Either e a -> Either a e -- | Generalize Either e as MonadError e m. -- -- If the argument has form Left e, an error is produced in the -- monad via throwError. Otherwise, the Right a part is -- forwarded. eitherToError :: MonadError e m => Either e a -> m a -- | Maybe produce a Right, otherwise produce a Left. -- --
--   >>> maybeToRight "default" (Just 12)
--   Right 12
--   
-- --
--   >>> maybeToRight "default" Nothing
--   Left "default"
--   
maybeToRight :: b -> Maybe a -> Either b a -- | Maybe produce a Left, otherwise produce a Right. -- --
--   >>> maybeToLeft "default" (Just 12)
--   Left 12
--   
-- --
--   >>> maybeToLeft "default" Nothing
--   Right "default"
--   
maybeToLeft :: b -> Maybe a -> Either a b -- | Maybe get the Right side of an Either. -- --
--   rightToMaybeeither (const Nothing) Just
--   
-- -- Using Control.Lens: -- --
--   rightToMaybe ≡ preview _Right
--   rightToMaybe x ≡ x^?_Right
--   
-- --
--   >>> rightToMaybe (Left 12)
--   Nothing
--   
-- --
--   >>> rightToMaybe (Right 12)
--   Just 12
--   
rightToMaybe :: Either a b -> Maybe b -- | Maybe get the Left side of an Either. -- --
--   leftToMaybeeither Just (const Nothing)
--   
-- -- Using Control.Lens: -- --
--   leftToMaybe ≡ preview _Left
--   leftToMaybe x ≡ x^?_Left
--   
-- --
--   >>> leftToMaybe (Left 12)
--   Just 12
--   
-- --
--   >>> leftToMaybe (Right 12)
--   Nothing
--   
leftToMaybe :: Either a b -> Maybe a -- | A synonym of whenLeft. unlessRight :: Applicative m => Either a b -> (a -> m ()) -> m () -- | A synonym of whenRight. unlessLeft :: Applicative m => Either a b -> (b -> m ()) -> m () -- | The whenRight function takes an Either value and a -- function which returns a monad. The monad is only executed when the -- given argument takes the form Right _, otherwise it -- does nothing. -- -- Using Data.Foldable: -- --
--   whenRightforM_
--   
-- -- Using Control.Lens: -- --
--   whenRight ≡ forOf_ _Right
--   
-- --
--   >>> whenRight (Right 12) print
--   12
--   
whenRight :: Applicative m => Either a b -> (b -> m ()) -> m () -- | The whenLeft function takes an Either value and a -- function which returns a monad. The monad is only executed when the -- given argument takes the form Left _, otherwise it -- does nothing. -- -- Using Control.Lens: -- --
--   whenLeft ≡ forOf_ _Left
--   
-- --
--   >>> whenLeft (Left 12) print
--   12
--   
whenLeft :: Applicative m => Either a b -> (a -> m ()) -> m () -- | The mapBoth function takes two functions and applies the first -- if iff the value takes the form Left _ and the second -- if the value takes the form Right _. -- -- Using Data.Bifunctor: -- --
--   mapBoth = bimap
--   
-- -- Using Control.Arrow: -- --
--   mapBoth = (+++)
--   
-- --
--   >>> mapBoth (*2) (*3) (Left 4)
--   Left 8
--   
-- --
--   >>> mapBoth (*2) (*3) (Right 4)
--   Right 12
--   
mapBoth :: (a -> c) -> (b -> d) -> Either a b -> Either c d -- | Extracts the element out of a Right and throws an error if its -- argument take the form Left _. -- -- Using Control.Lens: -- --
--   fromRight' x ≡ x^?!_Right
--   
-- --
--   >>> fromRight' (Right 12)
--   12
--   
fromRight' :: Either a b -> b -- | Extracts the element out of a Left and throws an error if its -- argument take the form Right _. -- -- Using Control.Lens: -- --
--   fromLeft' x ≡ x^?!_Left
--   
-- --
--   >>> fromLeft' (Left 12)
--   12
--   
fromLeft' :: Either a b -> a -- | The parameterizable maybe monad, obtained by composing an arbitrary -- monad with the Maybe monad. -- -- Computations are actions that may produce a value or exit. -- -- The return function yields a computation that produces that -- value, while >>= sequences two subcomputations, exiting -- if either computation does. newtype MaybeT (m :: Type -> Type) a MaybeT :: m (Maybe a) -> MaybeT (m :: Type -> Type) a -- | A monad transformer that adds exceptions to other monads. -- -- ExceptT constructs a monad parameterized over two things: -- -- -- -- The return function yields a computation that produces the -- given value, while >>= sequences two subcomputations, -- exiting on the first exception. newtype ExceptT e (m :: Type -> Type) a ExceptT :: m (Either e a) -> ExceptT e (m :: Type -> Type) a -- | Lazily generate all elements of a Cyclic group using its -- generator. -- -- Note: Fuses, terminates if the underlying group is finite. generated' :: (Eq a, Cyclic a) => [a] -- | Generate all elements of a Cyclic group using its -- generator. -- -- Note: Fuses, does not terminate even for finite groups. generated :: Cyclic a => [a] -- | A Group is a Monoid plus a function, invert, such -- that: -- --
--   a <> invert a == mempty
--   
-- --
--   invert a <> a == mempty
--   
class Monoid m => Group m invert :: Group m => m -> m -- | Group subtraction: x ~~ y == x <> invert y (~~) :: Group m => m -> m -> m -- |
--   pow a n == a <> a <> ... <> a
--   
-- --
--   (n lots of a)
--   
-- -- If n is negative, the result is inverted. pow :: (Group m, Integral x) => m -> x -> m infixl 7 ~~ -- | An Abelian group is a Group that follows the rule: -- --
--   a <> b == b <> a
--   
class Group g => Abelian g -- | A Group G is Cyclic if there exists an element x of G -- such that for all y in G, there exists an n, such that -- --
--   y = pow x n
--   
class Group a => Cyclic a -- | The generator of the Cyclic group. generator :: Cyclic a => a -- | Hashed cannot be Traversable traverseHashed :: (Hashable b, Functor f) => (a -> f b) -> Hashed a -> f (Hashed b) -- | Hashed cannot be Functor mapHashed :: Hashable b => (a -> b) -> Hashed a -> Hashed b -- | hash has Eq requirement. hashedHash :: Hashed a -> Int -- | Unwrap hashed value. unhashed :: Hashed a -> a -- | Wrap a hashable value, caching the hash function result. hashed :: Hashable a => a -> Hashed a -- | Compute a hash value for the content of this ByteArray#, -- beginning at the specified offset, using specified number of bytes. hashByteArray :: ByteArray# -> Int -> Int -> Int -- | Compute a hash value for the content of this pointer. hashPtr :: Ptr a -> Int -> IO Int -- | Transform a value into a Hashable value, then hash the -- transformed value using the given salt. -- -- This is a useful shorthand in cases where a type can easily be mapped -- to another type that is already an instance of Hashable. -- Example: -- --
--   data Foo = Foo | Bar
--            deriving (Enum)
--   
--   instance Hashable Foo where
--       hashWithSalt = hashUsing fromEnum
--   
hashUsing :: Hashable b => (a -> b) -> Int -> a -> Int -- | The class of types that can be converted to a hash value. -- -- Minimal implementation: hashWithSalt. -- -- Note: the hash is not guaranteed to be stable across library -- versions, operating systems or architectures. For stable hashing use -- named hashes: SHA256, CRC32 etc. -- -- If you are looking for Hashable instance in time -- package, check time-compat class Eq a => Hashable a -- | Return a hash value for the argument, using the given salt. -- -- The general contract of hashWithSalt is: -- -- hashWithSalt :: Hashable a => Int -> a -> Int -- | Like hashWithSalt, but no salt is used. The default -- implementation uses hashWithSalt with some default salt. -- Instances might want to implement this method to provide a more -- efficient implementation than the default implementation. hash :: Hashable a => a -> Int infixl 0 `hashWithSalt` -- | A hashable value along with the result of the hash function. data Hashed a -- | Compute a hash value for the content of this ByteArray#, using -- an initial salt. -- -- This function can for example be used to hash non-contiguous segments -- of memory as if they were one contiguous segment, by using the output -- of one hash as the salt for the next. hashByteArrayWithSalt :: ByteArray# -> Int -> Int -> Salt -> Salt -- | Compute a hash value for the content of this pointer, using an initial -- salt. -- -- This function can for example be used to hash non-contiguous segments -- of memory as if they were one contiguous segment, by using the output -- of one hash as the salt for the next. hashPtrWithSalt :: Ptr a -> Int -> Salt -> IO Salt -- | Formally, the class Profunctor represents a profunctor from -- Hask -> Hask. -- -- Intuitively it is a bifunctor where the first argument is -- contravariant and the second argument is covariant. -- -- You can define a Profunctor by either defining dimap or -- by defining both lmap and rmap. -- -- If you supply dimap, you should ensure that: -- --
--   dimap id idid
--   
-- -- If you supply lmap and rmap, ensure: -- --
--   lmap idid
--   rmap idid
--   
-- -- If you supply both, you should also ensure: -- --
--   dimap f g ≡ lmap f . rmap g
--   
-- -- These ensure by parametricity: -- --
--   dimap (f . g) (h . i) ≡ dimap g h . dimap f i
--   lmap (f . g) ≡ lmap g . lmap f
--   rmap (f . g) ≡ rmap f . rmap g
--   
class Profunctor (p :: Type -> Type -> Type) -- | Map over both arguments at the same time. -- --
--   dimap f g ≡ lmap f . rmap g
--   
dimap :: Profunctor p => (a -> b) -> (c -> d) -> p b c -> p a d -- | Map the first argument contravariantly. -- --
--   lmap f ≡ dimap f id
--   
lmap :: Profunctor p => (a -> b) -> p b c -> p a c -- | Map the second argument covariantly. -- --
--   rmapdimap id
--   
rmap :: Profunctor p => (b -> c) -> p a b -> p a c -- | Strictly map the second argument argument covariantly with a function -- that is assumed operationally to be a cast, such as a newtype -- constructor. -- -- Note: This operation is explicitly unsafe since an -- implementation may choose to use unsafeCoerce to implement -- this combinator and it has no way to validate that your function meets -- the requirements. -- -- If you implement this combinator with unsafeCoerce, then you -- are taking upon yourself the obligation that you don't use GADT-like -- tricks to distinguish values. -- -- If you import Data.Profunctor.Unsafe you are taking upon -- yourself the obligation that you will only call this with a first -- argument that is operationally identity. -- -- The semantics of this function with respect to bottoms should match -- the default definition: -- --
--   (#.) ≡ \_ -> \p -> p `seq` rmap coerce p
--   
(#.) :: forall a b c q. (Profunctor p, Coercible c b) => q b c -> p a b -> p a c -- | Strictly map the first argument argument contravariantly with a -- function that is assumed operationally to be a cast, such as a newtype -- constructor. -- -- Note: This operation is explicitly unsafe since an -- implementation may choose to use unsafeCoerce to implement -- this combinator and it has no way to validate that your function meets -- the requirements. -- -- If you implement this combinator with unsafeCoerce, then you -- are taking upon yourself the obligation that you don't use GADT-like -- tricks to distinguish values. -- -- If you import Data.Profunctor.Unsafe you are taking upon -- yourself the obligation that you will only call this with a second -- argument that is operationally identity. -- --
--   (.#) ≡ \p -> p `seq` \f -> lmap coerce p
--   
(.#) :: forall a b c q. (Profunctor p, Coercible b a) => p b c -> q a b -> p a c infixr 9 #. infixl 8 .# -- | A generic implementation of invmap. genericInvmap :: (Generic1 f, Invariant (Rep1 f)) => (a -> b) -> (b -> a) -> f a -> f b -- | Every Profunctor is also an Invariant2 functor. invmap2Profunctor :: Profunctor f => (a -> c) -> (c -> a) -> (b -> d) -> (d -> b) -> f a b -> f c d -- | Every Bifunctor is also an Invariant2 functor. invmap2Bifunctor :: Bifunctor f => (a -> c) -> (c -> a) -> (b -> d) -> (d -> b) -> f a b -> f c d -- | An Arrow with the same input and output types can be seen as an -- Invariant functor. invmapArrow :: Arrow arr => (a -> b) -> (b -> a) -> arr a a -> arr b b -- | A Profunctor with the same input and output types can be seen -- as an Invariant functor. invmapProfunctor :: Profunctor p => (a -> b) -> (b -> a) -> p a a -> p b b -- | Every Contravariant functor is also an Invariant -- functor. invmapContravariant :: Contravariant f => (a -> b) -> (b -> a) -> f a -> f b -- | Every Functor is also an Invariant functor. invmapFunctor :: Functor f => (a -> b) -> (b -> a) -> f a -> f b -- | Any * -> * type parametric in the argument permits an -- instance of Invariant. -- -- Instances should satisfy the following laws: -- --
--   invmap id id = id
--   invmap f2 f2' . invmap f1 f1' = invmap (f2 . f1) (f1' . f2')
--   
class Invariant (f :: Type -> TYPE LiftedRep) invmap :: Invariant f => (a -> b) -> (b -> a) -> f a -> f b -- | Wrap a Functor to be used as a member of Invariant. newtype WrappedFunctor (f :: k -> Type) (a :: k) WrapFunctor :: f a -> WrappedFunctor (f :: k -> Type) (a :: k) [unwrapFunctor] :: WrappedFunctor (f :: k -> Type) (a :: k) -> f a -- | Wrap a Contravariant functor to be used as a member of -- Invariant. newtype WrappedContravariant (f :: k -> Type) (a :: k) WrapContravariant :: f a -> WrappedContravariant (f :: k -> Type) (a :: k) [unwrapContravariant] :: WrappedContravariant (f :: k -> Type) (a :: k) -> f a -- | Any * -> * -> * type parametric in both arguments -- permits an instance of Invariant2. -- -- Instances should satisfy the following laws: -- --
--   invmap2 id id id id = id
--   invmap2 f2 f2' g2 g2' . invmap2 f1 f1' g1 g1' =
--     invmap2 (f2 . f1) (f1' . f2') (g2 . g1) (g1' . g2')
--   
class Invariant2 (f :: Type -> Type -> Type) invmap2 :: Invariant2 f => (a -> c) -> (c -> a) -> (b -> d) -> (d -> b) -> f a b -> f c d -- | Wrap a Profunctor to be used as a member of Invariant2. newtype WrappedProfunctor (p :: k -> k1 -> Type) (a :: k) (b :: k1) WrapProfunctor :: p a b -> WrappedProfunctor (p :: k -> k1 -> Type) (a :: k) (b :: k1) [unwrapProfunctor] :: WrappedProfunctor (p :: k -> k1 -> Type) (a :: k) (b :: k1) -> p a b -- | A Profunctor with the same input and output types can be seen -- as an Invariant functor. newtype InvariantProfunctor (p :: k -> k -> Type) (a :: k) InvariantProfunctor :: p a a -> InvariantProfunctor (p :: k -> k -> Type) (a :: k) -- | An Arrow with the same input and output types can be seen as an -- Invariant functor. newtype InvariantArrow (c :: k -> k -> Type) (a :: k) InvariantArrow :: c a a -> InvariantArrow (c :: k -> k -> Type) (a :: k) -- | The class of monad transformers. Instances should satisfy the -- following laws, which state that lift is a monad -- transformation: -- -- class MonadTrans (t :: Type -> Type -> Type -> Type) -- | Lift a computation from the argument monad to the constructed monad. lift :: (MonadTrans t, Monad m) => m a -> t m a class (Monoid w, Monad m) => MonadWriter w (m :: Type -> Type) | m -> w -- | writer (a,w) embeds a simple writer action. writer :: MonadWriter w m => (a, w) -> m a -- | tell w is an action that produces the output -- w. tell :: MonadWriter w m => w -> m () -- | listen m is an action that executes the action -- m and adds its output to the value of the computation. listen :: MonadWriter w m => m a -> m (a, w) -- | pass m is an action that executes the action -- m, which returns a value and a function, and returns the -- value, applying the function to the output. pass :: MonadWriter w m => m (a, w -> w) -> m a -- | listens f m is an action that executes the action -- m and adds the result of applying f to the output to -- the value of the computation. -- -- listens :: MonadWriter w m => (w -> b) -> m a -> m (a, b) -- | censor f m is an action that executes the action -- m and applies the function f to its output, leaving -- the return value unchanged. -- -- censor :: MonadWriter w m => (w -> w) -> m a -> m a -- | A variant of modify in which the computation is strict in the -- new state. modify' :: MonadState s m => (s -> s) -> m () -- | Monadic state transformer. -- -- Maps an old state to a new state inside a state monad. The old state -- is thrown away. -- --
--   Main> :t modify ((+1) :: Int -> Int)
--   modify (...) :: (MonadState Int a) => a ()
--   
-- -- This says that modify (+1) acts over any Monad that is a -- member of the MonadState class, with an Int state. modify :: MonadState s m => (s -> s) -> m () -- | Gets specific component of the state, using a projection function -- supplied. gets :: MonadState s m => (s -> a) -> m a -- | Retrieves a function of the current environment. asks :: MonadReader r m => (r -> a) -> m a -- | The strategy of combining computations that can throw exceptions by -- bypassing bound functions from the point an exception is thrown to the -- point that it is handled. -- -- Is parameterized over the type of error information and the monad type -- constructor. It is common to use Either String as the -- monad type constructor for an error monad in which error descriptions -- take the form of strings. In that case and many other common cases the -- resulting monad is already defined as an instance of the -- MonadError class. You can also define your own error type -- and/or use a monad type constructor other than Either -- String or Either IOError. In -- these cases you will have to explicitly define instances of the -- MonadError class. (If you are using the deprecated -- Control.Monad.Error or Control.Monad.Trans.Error, you -- may also have to define an Error instance.) class Monad m => MonadError e (m :: Type -> Type) | m -> e -- | Is used within a monadic computation to begin exception processing. throwError :: MonadError e m => e -> m a -- | A handler function to handle previous errors and return to normal -- execution. A common idiom is: -- --
--   do { action1; action2; action3 } `catchError` handler
--   
-- -- where the action functions can call throwError. Note -- that handler and the do-block must have the same return type. catchError :: MonadError e m => m a -> (e -> m a) -> m a -- | Lifts an Either e into any MonadError -- e. -- --
--   do { val <- liftEither =<< action1; action2 }
--   
-- -- where action1 returns an Either to represent errors. liftEither :: MonadError e m => Either e a -> m a class Monad m => MonadCont (m :: Type -> Type) -- | callCC (call-with-current-continuation) calls a function with -- the current continuation as its argument. Provides an escape -- continuation mechanism for use with Continuation monads. Escape -- continuations allow to abort the current computation and return a -- value immediately. They achieve a similar effect to throwError -- and catchError within an Error monad. Advantage of this -- function over calling return is that it makes the -- continuation explicit, allowing more flexibility and better control -- (see examples in Control.Monad.Cont). -- -- The standard idiom used with callCC is to provide a -- lambda-expression to name the continuation. Then calling the named -- continuation anywhere within its scope will escape from the -- computation, even if it is many layers deep within nested -- computations. callCC :: MonadCont m => ((a -> m b) -> m a) -> m a -- | Construct a continuation-passing computation from a function. (The -- inverse of runCont) cont :: ((a -> r) -> r) -> Cont r a -- | Apply a function to transform the result of a continuation-passing -- computation. -- -- mapCont :: (r -> r) -> Cont r a -> Cont r a -- | Apply a function to transform the result of a continuation-passing -- computation. This has a more restricted type than the map -- operations for other monad transformers, because ContT does not -- define a functor in the category of monads. -- -- mapContT :: forall {k} m (r :: k) a. (m r -> m r) -> ContT r m a -> ContT r m a -- | The result of running a CPS computation with a given final -- continuation. (The inverse of cont) runCont :: Cont r a -> (a -> r) -> r -- | Apply a function to transform the continuation passed to a CPS -- computation. -- -- withCont :: ((b -> r) -> a -> r) -> Cont r a -> Cont r b -- | Apply a function to transform the continuation passed to a CPS -- computation. -- -- withContT :: forall {k} b m (r :: k) a. ((b -> m r) -> a -> m r) -> ContT r m a -> ContT r m b -- | Continuation monad. Cont r a is a CPS ("continuation-passing -- style") computation that produces an intermediate result of type -- a within a CPS computation whose final result type is -- r. -- -- The return function simply creates a continuation which -- passes the value on. -- -- The >>= operator adds the bound function into the -- continuation chain. type Cont r = ContT r Identity -- | The continuation monad transformer. Can be used to add continuation -- handling to any type constructor: the Monad instance and most -- of the operations do not require m to be a monad. -- -- ContT is not a functor on the category of monads, and many -- operations cannot be lifted through it. newtype ContT (r :: k) (m :: k -> Type) a ContT :: ((a -> m r) -> m r) -> ContT (r :: k) (m :: k -> Type) a [runContT] :: ContT (r :: k) (m :: k -> Type) a -> (a -> m r) -> m r -- | Map the unwrapped computation using the given function. -- -- mapExcept :: (Either e a -> Either e' b) -> Except e a -> Except e' b -- | Map the unwrapped computation using the given function. -- -- mapExceptT :: (m (Either e a) -> n (Either e' b)) -> ExceptT e m a -> ExceptT e' n b -- | Extractor for computations in the exception monad. (The inverse of -- except). runExcept :: Except e a -> Either e a -- | The inverse of ExceptT. runExceptT :: ExceptT e m a -> m (Either e a) -- | Transform any exceptions thrown by the computation using the given -- function (a specialization of withExceptT). withExcept :: (e -> e') -> Except e a -> Except e' a -- | Transform any exceptions thrown by the computation using the given -- function. withExceptT :: forall (m :: Type -> Type) e e' a. Functor m => (e -> e') -> ExceptT e m a -> ExceptT e' m a -- | The parameterizable exception monad. -- -- Computations are either exceptions or normal values. -- -- The return function returns a normal value, while -- >>= exits on the first exception. For a variant that -- continues after an error and collects all the errors, see -- Errors. type Except e = ExceptT e Identity -- | Transform the value returned by a Reader. -- -- mapReader :: (a -> b) -> Reader r a -> Reader r b -- | Transform the computation inside a ReaderT. -- -- mapReaderT :: (m a -> n b) -> ReaderT r m a -> ReaderT r n b -- | Runs a Reader and extracts the final value from it. (The -- inverse of reader.) runReader :: Reader r a -> r -> a -- | Execute a computation in a modified environment (a specialization of -- withReaderT). -- -- withReader :: (r' -> r) -> Reader r a -> Reader r' a -- | Execute a computation in a modified environment (a more general -- version of local). -- -- withReaderT :: forall r' r (m :: Type -> Type) a. (r' -> r) -> ReaderT r m a -> ReaderT r' m a -- | The parameterizable reader monad. -- -- Computations are functions of a shared environment. -- -- The return function ignores the environment, while -- >>= passes the inherited environment to both -- subcomputations. type Reader r = ReaderT r Identity -- | The reader monad transformer, which adds a read-only environment to -- the given monad. -- -- The return function ignores the environment, while -- >>= passes the inherited environment to both -- subcomputations. newtype ReaderT r (m :: Type -> Type) a ReaderT :: (r -> m a) -> ReaderT r (m :: Type -> Type) a [runReaderT] :: ReaderT r (m :: Type -> Type) a -> r -> m a -- | Evaluate a state computation with the given initial state and return -- the final value, discarding the final state. -- -- evalState :: State s a -> s -> a -- | Evaluate a state computation with the given initial state and return -- the final value, discarding the final state. -- -- evalStateT :: Monad m => StateT s m a -> s -> m a -- | Evaluate a state computation with the given initial state and return -- the final state, discarding the final value. -- -- execState :: State s a -> s -> s -- | Evaluate a state computation with the given initial state and return -- the final state, discarding the final value. -- -- execStateT :: Monad m => StateT s m a -> s -> m s -- | Map both the return value and final state of a computation using the -- given function. -- -- mapState :: ((a, s) -> (b, s)) -> State s a -> State s b -- | Map both the return value and final state of a computation using the -- given function. -- -- mapStateT :: (m (a, s) -> n (b, s)) -> StateT s m a -> StateT s n b -- | Unwrap a state monad computation as a function. (The inverse of -- state.) runState :: State s a -> s -> (a, s) -- | withState f m executes action m on a state -- modified by applying f. -- -- withState :: (s -> s) -> State s a -> State s a -- | withStateT f m executes action m on a state -- modified by applying f. -- -- withStateT :: forall s (m :: Type -> Type) a. (s -> s) -> StateT s m a -> StateT s m a -- | A state monad parameterized by the type s of the state to -- carry. -- -- The return function leaves the state unchanged, while -- >>= uses the final state of the first computation as -- the initial state of the second. type State s = StateT s Identity -- | A state transformer monad parameterized by: -- -- -- -- The return function leaves the state unchanged, while -- >>= uses the final state of the first computation as -- the initial state of the second. newtype StateT s (m :: Type -> Type) a StateT :: (s -> m (a, s)) -> StateT s (m :: Type -> Type) a [runStateT] :: StateT s (m :: Type -> Type) a -> s -> m (a, s) -- | Extract the output from a writer computation. -- -- execWriter :: Writer w a -> w -- | Extract the output from a writer computation. -- -- execWriterT :: Monad m => WriterT w m a -> m w -- | Map both the return value and output of a computation using the given -- function. -- -- mapWriter :: ((a, w) -> (b, w')) -> Writer w a -> Writer w' b -- | Map both the return value and output of a computation using the given -- function. -- -- mapWriterT :: (m (a, w) -> n (b, w')) -> WriterT w m a -> WriterT w' n b -- | Unwrap a writer computation as a (result, output) pair. (The inverse -- of writer.) runWriter :: Writer w a -> (a, w) -- | A writer monad parameterized by the type w of output to -- accumulate. -- -- The return function produces the output mempty, while -- >>= combines the outputs of the subcomputations using -- mappend. type Writer w = WriterT w Identity -- | A writer monad parameterized by: -- -- -- -- The return function produces the output mempty, while -- >>= combines the outputs of the subcomputations using -- mappend. newtype WriterT w (m :: Type -> Type) a WriterT :: m (a, w) -> WriterT w (m :: Type -> Type) a -- |
--   joinCoyoneda . produplicateid
--   produplicate . joinCoyonedaid
--   joinCoyonedaproextract
--   
joinCoyoneda :: forall (p :: Type -> Type -> Type) a b. Coyoneda (Coyoneda p) a b -> Coyoneda p a b -- |
--   returnCoyoneda . proextractid
--   proextract . returnCoyonedaid
--   produplicatereturnCoyoneda
--   
returnCoyoneda :: p a b -> Coyoneda p a b -- |
--   projoin . duplicateYonedaid
--   duplicateYoneda . projoinid
--   duplicateYoneda = proreturn
--   
duplicateYoneda :: forall (p :: Type -> Type -> Type) a b. Yoneda p a b -> Yoneda (Yoneda p) a b -- |
--   projoin . extractYonedaid
--   extractYoneda . projoinid
--   projoinextractYoneda
--   
extractYoneda :: Yoneda p a b -> p a b -- | This is the cofree profunctor given a data constructor of kind * -- -> * -> * newtype Yoneda (p :: Type -> Type -> Type) a b Yoneda :: (forall x y. () => (x -> a) -> (b -> y) -> p x y) -> Yoneda (p :: Type -> Type -> Type) a b [runYoneda] :: Yoneda (p :: Type -> Type -> Type) a b -> forall x y. () => (x -> a) -> (b -> y) -> p x y data Coyoneda (p :: Type -> Type -> Type) a b [Coyoneda] :: forall a x y b (p :: Type -> Type -> Type). (a -> x) -> (y -> b) -> p x y -> Coyoneda p a b mapCayley :: forall {k1} {k2} {k3} f g (p :: k2 -> k3 -> k1) (x :: k2) (y :: k3). (forall (a :: k1). () => f a -> g a) -> Cayley f p x y -> Cayley g p x y -- | Static arrows. Lifted by Applicative. -- -- Cayley has a polymorphic kind since 5.6. newtype Cayley (f :: k -> Type) (p :: k1 -> k2 -> k) (a :: k1) (b :: k2) Cayley :: f (p a b) -> Cayley (f :: k -> Type) (p :: k1 -> k2 -> k) (a :: k1) (b :: k2) [runCayley] :: Cayley (f :: k -> Type) (p :: k1 -> k2 -> k) (a :: k1) (b :: k2) -> f (p a b) decomposeCodensity :: forall {k2} {k1} p (a :: k2) (b :: k1). Procompose (Codensity p) p a b -> p a b uncurryRan :: forall {k1} {k2} {k3} (p :: k1 -> k2 -> Type) (q :: k3 -> k1 -> Type) (r :: k3 -> k2 -> Type). (p :-> Ran q r) -> Procompose p q :-> r curryRan :: forall {k1} {k2} {k3} (p :: k1 -> k2 -> Type) (q :: k3 -> k1 -> Type) (r :: k3 -> k2 -> Type). (Procompose p q :-> r) -> p :-> Ran q r precomposeRan :: forall {k} (q :: Type -> Type -> Type) (p :: TYPE LiftedRep -> k -> Type). Profunctor q => Procompose q (Ran p (->)) :-> Ran p q -- | The 2-morphism that defines a right Kan extension. -- -- Note: When q is left adjoint to Ran q (->) -- then decomposeRan is the counit of the adjunction. decomposeRan :: forall {k1} {k2} {k3} (q :: k1 -> k2 -> Type) (p :: k1 -> k3 -> Type). Procompose (Ran q p) q :-> p -- | This represents the right Kan extension of a Profunctor -- q along a Profunctor p in a limited version -- of the 2-category of Profunctors where the only object is the category -- Hask, 1-morphisms are profunctors composed and compose with Profunctor -- composition, and 2-morphisms are just natural transformations. -- -- Ran has a polymorphic kind since 5.6. newtype Ran (p :: k -> k1 -> Type) (q :: k -> k2 -> Type) (a :: k1) (b :: k2) Ran :: (forall (x :: k). () => p x a -> q x b) -> Ran (p :: k -> k1 -> Type) (q :: k -> k2 -> Type) (a :: k1) (b :: k2) [runRan] :: Ran (p :: k -> k1 -> Type) (q :: k -> k2 -> Type) (a :: k1) (b :: k2) -> forall (x :: k). () => p x a -> q x b -- | This represents the right Kan extension of a Profunctor -- p along itself. This provides a generalization of the -- "difference list" trick to profunctors. -- -- Codensity has a polymorphic kind since 5.6. newtype Codensity (p :: k -> k1 -> Type) (a :: k1) (b :: k1) Codensity :: (forall (x :: k). () => p x a -> p x b) -> Codensity (p :: k -> k1 -> Type) (a :: k1) (b :: k1) [runCodensity] :: Codensity (p :: k -> k1 -> Type) (a :: k1) (b :: k1) -> forall (x :: k). () => p x a -> p x b mu :: forall {k1} (p :: k1 -> k1 -> Type). Category p => Procompose p p :-> p -- | a Category that is also a Profunctor is a Monoid -- in Prof eta :: forall (p :: Type -> Type -> Type). (Profunctor p, Category p) => (->) :-> p -- | The 2-morphism that defines a left Kan lift. -- -- Note: When p is right adjoint to Rift p -- (->) then decomposeRift is the counit of the -- adjunction. decomposeRift :: forall {k1} {k2} {k3} (p :: k1 -> k2 -> Type) (q :: k3 -> k2 -> Type). Procompose p (Rift p q) :-> q -- | This is a variant on costars that uses Cokleisli instead -- of Costar. -- --
--   cokleislis :: Functor f => Iso' (Procompose (Cokleisli f) (Cokleisli g) d c) (Cokleisli (Compose g f) d c)
--   
cokleislis :: forall {k1} {k2} (f :: Type -> Type) (g :: k1 -> Type) (d :: k1) c (f' :: Type -> Type) (g' :: k2 -> Type) (d' :: k2) c'. Functor f => Iso (Procompose (Cokleisli f) (Cokleisli g) d c) (Procompose (Cokleisli f') (Cokleisli g') d' c') (Cokleisli (Compose f g) d c) (Cokleisli (Compose f' g') d' c') -- | This is a variant on stars that uses Kleisli instead of -- Star. -- --
--   kleislis :: Monad f => Iso' (Procompose (Kleisli f) (Kleisli g) d c) (Kleisli (Compose f g) d c)
--   
kleislis :: forall (g :: Type -> Type) (f :: Type -> Type) d c (f' :: Type -> Type) (g' :: Type -> Type) d' c'. Monad g => Iso (Procompose (Kleisli f) (Kleisli g) d c) (Procompose (Kleisli f') (Kleisli g') d' c') (Kleisli (Compose g f) d c) (Kleisli (Compose g' f') d' c') -- | Profunctor composition generalizes Functor composition -- in two ways. -- -- This is the second, which shows that exists b. (f a -> b, g b -- -> c) is isomorphic to g (f a) -> c. -- --
--   costars :: Functor f => Iso' (Procompose (Costar f) (Costar g) d c) (Costar (Compose g f) d c)
--   
costars :: forall {k1} {k2} (f :: Type -> Type) (g :: k1 -> Type) (d :: k1) c (f' :: Type -> Type) (g' :: k2 -> Type) (d' :: k2) c'. Functor f => Iso (Procompose (Costar f) (Costar g) d c) (Procompose (Costar f') (Costar g') d' c') (Costar (Compose f g) d c) (Costar (Compose f' g') d' c') -- | Profunctor composition generalizes Functor composition -- in two ways. -- -- This is the first, which shows that exists b. (a -> f b, b -- -> g c) is isomorphic to a -> f (g c). -- --
--   stars :: Functor f => Iso' (Procompose (Star f) (Star g) d c) (Star (Compose f g) d c)
--   
stars :: forall {k1} {k2} (g :: Type -> Type) (f :: k1 -> Type) d (c :: k1) (f' :: k2 -> Type) (g' :: Type -> Type) d' (c' :: k2). Functor g => Iso (Procompose (Star f) (Star g) d c) (Procompose (Star f') (Star g') d' c') (Star (Compose g f) d c) (Star (Compose g' f') d' c') -- | The associator for Profunctor composition. -- -- This provides an Iso for the lens package that -- witnesses the isomorphism between Procompose p -- (Procompose q r) a b and Procompose -- (Procompose p q) r a b, which arises because Prof -- is only a bicategory, rather than a strict 2-category. assoc :: forall {k1} {k2} {k3} {k4} {k5} {k6} (p :: k1 -> k2 -> Type) (q :: k3 -> k1 -> Type) (r :: k4 -> k3 -> Type) (a :: k4) (b :: k2) (x :: k5 -> k2 -> Type) (y :: k6 -> k5 -> Type) (z :: k4 -> k6 -> Type). Iso (Procompose p (Procompose q r) a b) (Procompose x (Procompose y z) a b) (Procompose (Procompose p q) r a b) (Procompose (Procompose x y) z a b) -- | (->) functions as a lax identity for Profunctor -- composition. -- -- This provides an Iso for the lens package that -- witnesses the isomorphism between Procompose q (->) d -- c and q d c, which is the right identity law. -- --
--   idr :: Profunctor q => Iso' (Procompose q (->) d c) (q d c)
--   
idr :: forall {k} (q :: Type -> Type -> Type) d c (r :: Type -> k -> Type) d' (c' :: k). Profunctor q => Iso (Procompose q (->) d c) (Procompose r (->) d' c') (q d c) (r d' c') -- | (->) functions as a lax identity for Profunctor -- composition. -- -- This provides an Iso for the lens package that -- witnesses the isomorphism between Procompose (->) q d -- c and q d c, which is the left identity law. -- --
--   idl :: Profunctor q => Iso' (Procompose (->) q d c) (q d c)
--   
idl :: forall {k} (q :: Type -> Type -> Type) d c (r :: k -> Type -> Type) (d' :: k) c'. Profunctor q => Iso (Procompose (->) q d c) (Procompose (->) r d' c') (q d c) (r d' c') procomposed :: forall {k} p (a :: k) (b :: k). Category p => Procompose p p a b -> p a b -- | Procompose p q is the Profunctor composition of -- the Profunctors p and q. -- -- For a good explanation of Profunctor composition in Haskell see -- Dan Piponi's article: -- -- http://blog.sigfpe.com/2011/07/profunctors-in-haskell.html -- -- Procompose has a polymorphic kind since 5.6. data Procompose (p :: k -> k1 -> Type) (q :: k2 -> k -> Type) (d :: k2) (c :: k1) [Procompose] :: forall {k} {k1} {k2} (p :: k -> k1 -> Type) (x :: k) (c :: k1) (q :: k2 -> k -> Type) (d :: k2). p x c -> q d x -> Procompose p q d c -- | This represents the right Kan lift of a Profunctor q -- along a Profunctor p in a limited version of the -- 2-category of Profunctors where the only object is the category Hask, -- 1-morphisms are profunctors composed and compose with Profunctor -- composition, and 2-morphisms are just natural transformations. -- -- Rift has a polymorphic kind since 5.6. newtype Rift (p :: k -> k1 -> Type) (q :: k2 -> k1 -> Type) (a :: k2) (b :: k) Rift :: (forall (x :: k1). () => p b x -> q a x) -> Rift (p :: k -> k1 -> Type) (q :: k2 -> k1 -> Type) (a :: k2) (b :: k) [runRift] :: Rift (p :: k -> k1 -> Type) (q :: k2 -> k1 -> Type) (a :: k2) (b :: k) -> forall (x :: k1). () => p b x -> q a x coprepCounit :: forall {k} f (a :: k). f a -> Coprep (Costar f) a coprepUnit :: forall {k} (p :: k -> Type -> Type). p :-> Costar (Coprep p) uncoprepAdj :: forall {k} (p :: k -> Type -> Type) f (a :: k). (p :-> Costar f) -> f a -> Coprep p a -- |
--   Coprep -| Costar :: [Hask, Hask]^op -> Prof
--   
-- -- Like all adjunctions this gives rise to a monad and a comonad. -- -- This gives rise to a monad on Prof -- (Costar.Coprep) and a comonad on [Hask, -- Hask]^op given by (Coprep.Costar) which is -- a monad in [Hask,Hask] coprepAdj :: forall {k} f (p :: k -> Type -> Type). (forall (a :: k). () => f a -> Coprep p a) -> p :-> Costar f prepCounit :: forall {k} f (a :: k). Prep (Star f) a -> f a prepUnit :: forall {k} (p :: Type -> k -> Type). p :-> Star (Prep p) unprepAdj :: forall {k} (p :: Type -> k -> Type) g (a :: k). (p :-> Star g) -> Prep p a -> g a prepAdj :: forall {k1} (p :: Type -> k1 -> Type) g. (forall (a :: k1). () => Prep p a -> g a) -> p :-> Star g -- | cotabulate and cosieve form two halves of an -- isomorphism. -- -- This can be used with the combinators from the lens package. -- --
--   cotabulated :: Corep f p => Iso' (f d -> c) (p d c)
--   
cotabulated :: forall (p :: Type -> Type -> Type) (q :: Type -> Type -> Type) d c d' c'. (Corepresentable p, Corepresentable q) => Iso (Corep p d -> c) (Corep q d' -> c') (p d c) (q d' c') -- | Default definition for closed given that p is -- Corepresentable closedCorep :: Corepresentable p => p a b -> p (x -> a) (x -> b) -- | Default definition for unsecond given that p is -- Corepresentable. unsecondCorep :: Corepresentable p => p (d, a) (d, b) -> p a b -- | Default definition for unfirst given that p is -- Corepresentable. unfirstCorep :: Corepresentable p => p (a, d) (b, d) -> p a b -- | tabulate and sieve form two halves of an isomorphism. -- -- This can be used with the combinators from the lens package. -- --
--   tabulated :: Representable p => Iso' (d -> Rep p c) (p d c)
--   
tabulated :: forall (p :: Type -> Type -> Type) (q :: Type -> Type -> Type) d c d' c'. (Representable p, Representable q) => Iso (d -> Rep p c) (d' -> Rep q c') (p d c) (q d' c') -- | Default definition for second' given that p is -- Representable. secondRep :: Representable p => p a b -> p (c, a) (c, b) -- | Default definition for first' given that p is -- Representable. firstRep :: Representable p => p a b -> p (a, c) (b, c) type family Rep (p :: Type -> Type -> Type) :: Type -> Type -- | A Profunctor p is Representable if there exists -- a Functor f such that p d c is isomorphic to -- d -> f c. class (Sieve p Rep p, Strong p) => Representable (p :: Type -> Type -> Type) where { type family Rep (p :: Type -> Type -> Type) :: Type -> Type; } -- | Laws: -- --
--   tabulate . sieveid
--   sieve . tabulateid
--   
tabulate :: Representable p => (d -> Rep p c) -> p d c type family Corep (p :: Type -> Type -> Type) :: Type -> Type -- | A Profunctor p is Corepresentable if there -- exists a Functor f such that p d c is -- isomorphic to f d -> c. class (Cosieve p Corep p, Costrong p) => Corepresentable (p :: Type -> Type -> Type) where { type family Corep (p :: Type -> Type -> Type) :: Type -> Type; } -- | Laws: -- --
--   cotabulate . cosieveid
--   cosieve . cotabulateid
--   
cotabulate :: Corepresentable p => (Corep p d -> c) -> p d c -- |
--   Prep -| Star :: [Hask, Hask] -> Prof
--   
-- -- This gives rise to a monad in Prof, -- (Star.Prep), and a comonad in -- [Hask,Hask] (Prep.Star) -- -- Prep has a polymorphic kind since 5.6. data Prep (p :: Type -> k -> Type) (a :: k) [Prep] :: forall {k} x (p :: Type -> k -> Type) (a :: k). x -> p x a -> Prep p a -- | Prep has a polymorphic kind since 5.6. newtype Coprep (p :: k -> Type -> Type) (a :: k) Coprep :: (forall r. () => p a r -> r) -> Coprep (p :: k -> Type -> Type) (a :: k) [runCoprep] :: Coprep (p :: k -> Type -> Type) (a :: k) -> forall r. () => p a r -> r -- | A Profunctor p is a Sieve on f -- if it is a subprofunctor of Star f. -- -- That is to say it is a subset of Hom(-,f=) closed under -- lmap and rmap. -- -- Alternately, you can view it as a sieve in the comma category -- Hask/f. class (Profunctor p, Functor f) => Sieve (p :: Type -> Type -> Type) (f :: Type -> Type) | p -> f sieve :: Sieve p f => p a b -> a -> f b -- | A Profunctor p is a Cosieve on -- f if it is a subprofunctor of Costar f. -- -- That is to say it is a subset of Hom(f-,=) closed under -- lmap and rmap. -- -- Alternately, you can view it as a cosieve in the comma category -- f/Hask. class (Profunctor p, Functor f) => Cosieve (p :: Type -> Type -> Type) (f :: Type -> Type) | p -> f cosieve :: Cosieve p f => p a b -> f a -> b closedMapping :: Mapping p => p a b -> p (x -> a) (x -> b) traverseMapping :: (Mapping p, Functor f) => p a b -> p (f a) (f b) wanderMapping :: Mapping p => (forall (f :: Type -> Type). Applicative f => (a -> f b) -> s -> f t) -> p a b -> p s t class (Traversing p, Closed p) => Mapping (p :: Type -> Type -> Type) -- | Laws: -- --
--   map' . rmap f ≡ rmap (fmap f) . map'
--   map' . map'dimap Compose getCompose . map'
--   dimap Identity runIdentity . map'id
--   
map' :: (Mapping p, Functor f) => p a b -> p (f a) (f b) roam :: Mapping p => ((a -> b) -> s -> t) -> p a b -> p s t newtype CofreeMapping (p :: Type -> Type -> Type) a b CofreeMapping :: (forall (f :: Type -> Type). Functor f => p (f a) (f b)) -> CofreeMapping (p :: Type -> Type -> Type) a b [runCofreeMapping] :: CofreeMapping (p :: Type -> Type -> Type) a b -> forall (f :: Type -> Type). Functor f => p (f a) (f b) -- |
--   FreeMapping -| CofreeMapping
--   
data FreeMapping (p :: Type -> Type -> Type) a b [FreeMapping] :: forall (f :: Type -> Type) y b (p :: Type -> Type -> Type) x a. Functor f => (f y -> b) -> p x y -> (a -> f x) -> FreeMapping p a b rightTraversing :: Traversing p => p a b -> p (Either c a) (Either c b) leftTraversing :: Traversing p => p a b -> p (Either a c) (Either b c) -- | rmapWandering is the same as the default produced from -- dimapWandering. rmapWandering :: Traversing p => (b -> c) -> p a b -> p a c -- | lmapWandering may be a more efficient implementation of -- lmap than the default produced from dimapWandering. lmapWandering :: Traversing p => (a -> b) -> p b c -> p a c -- | A definition of dimap for Traversing instances that -- define an explicit wander. dimapWandering :: Traversing p => (a' -> a) -> (b -> b') -> p a b -> p a' b' secondTraversing :: Traversing p => p a b -> p (c, a) (c, b) firstTraversing :: Traversing p => p a b -> p (a, c) (b, c) -- | Note: Definitions in terms of wander are much more efficient! class (Choice p, Strong p) => Traversing (p :: Type -> Type -> Type) -- | Laws: -- --
--   traverse'wander traverse
--   traverse' . rmap f ≡ rmap (fmap f) . traverse'
--   traverse' . traverse'dimap Compose getCompose . traverse'
--   dimap Identity runIdentity . traverse'id
--   
traverse' :: (Traversing p, Traversable f) => p a b -> p (f a) (f b) -- | This combinator is mutually defined in terms of traverse' wander :: Traversing p => (forall (f :: Type -> Type). Applicative f => (a -> f b) -> s -> f t) -> p a b -> p s t newtype CofreeTraversing (p :: Type -> Type -> Type) a b CofreeTraversing :: (forall (f :: Type -> Type). Traversable f => p (f a) (f b)) -> CofreeTraversing (p :: Type -> Type -> Type) a b [runCofreeTraversing] :: CofreeTraversing (p :: Type -> Type -> Type) a b -> forall (f :: Type -> Type). Traversable f => p (f a) (f b) -- |
--   FreeTraversing -| CofreeTraversing
--   
data FreeTraversing (p :: Type -> Type -> Type) a b [FreeTraversing] :: forall (f :: Type -> Type) y b (p :: Type -> Type -> Type) x a. Traversable f => (f y -> b) -> p x y -> (a -> f x) -> FreeTraversing p a b -- |
--   cotambaraSum . uncotambaraSumid
--   uncotambaraSum . cotambaraSumid
--   
uncotambaraSum :: forall (q :: Type -> Type -> Type) (p :: Type -> Type -> Type). Profunctor q => (p :-> CotambaraSum q) -> p :-> q -- |
--   cotambaraSum . uncotambaraSumid
--   uncotambaraSum . cotambaraSumid
--   
cotambaraSum :: forall (p :: Type -> Type -> Type) (q :: Type -> Type -> Type). Cochoice p => (p :-> q) -> p :-> CotambaraSum q -- |
--   tambaraSum . untambaraSumid
--   untambaraSum . tambaraSumid
--   
untambaraSum :: forall (q :: Type -> Type -> Type) (p :: Type -> Type -> Type). Profunctor q => (p :-> TambaraSum q) -> p :-> q -- |
--   tambaraSum . untambaraSumid
--   untambaraSum . tambaraSumid
--   
tambaraSum :: forall (p :: Type -> Type -> Type) (q :: Type -> Type -> Type). Choice p => (p :-> q) -> p :-> TambaraSum q -- | The generalization of Costar of Functor that is strong -- with respect to Either. -- -- Note: This is also a notion of strength, except with regards to -- another monoidal structure that we can choose to equip Hask with: the -- cocartesian coproduct. class Profunctor p => Choice (p :: Type -> Type -> Type) -- | Laws: -- --
--   left'dimap swapE swapE . right' where
--     swapE :: Either a b -> Either b a
--     swapE = either Right Left
--   rmap Leftlmap Left . left'
--   lmap (right f) . left'rmap (right f) . left'
--   left' . left'dimap assocE unassocE . left' where
--     assocE :: Either (Either a b) c -> Either a (Either b c)
--     assocE (Left (Left a)) = Left a
--     assocE (Left (Right b)) = Right (Left b)
--     assocE (Right c) = Right (Right c)
--     unassocE :: Either a (Either b c) -> Either (Either a b) c
--     unassocE (Left a) = Left (Left a)
--     unassocE (Right (Left b)) = Left (Right b)
--     unassocE (Right (Right c)) = Right c
--   
left' :: Choice p => p a b -> p (Either a c) (Either b c) -- | Laws: -- --
--   right'dimap swapE swapE . left' where
--     swapE :: Either a b -> Either b a
--     swapE = either Right Left
--   rmap Rightlmap Right . right'
--   lmap (left f) . right'rmap (left f) . right'
--   right' . right'dimap unassocE assocE . right' where
--     assocE :: Either (Either a b) c -> Either a (Either b c)
--     assocE (Left (Left a)) = Left a
--     assocE (Left (Right b)) = Right (Left b)
--     assocE (Right c) = Right (Right c)
--     unassocE :: Either a (Either b c) -> Either (Either a b) c
--     unassocE (Left a) = Left (Left a)
--     unassocE (Right (Left b)) = Left (Right b)
--     unassocE (Right (Right c)) = Right c
--   
right' :: Choice p => p a b -> p (Either c a) (Either c b) -- | TambaraSum is cofreely adjoins strength with respect to Either. -- -- Note: this is not dual to Tambara. It is Tambara with -- respect to a different tensor. newtype TambaraSum (p :: Type -> Type -> Type) a b TambaraSum :: (forall c. () => p (Either a c) (Either b c)) -> TambaraSum (p :: Type -> Type -> Type) a b [runTambaraSum] :: TambaraSum (p :: Type -> Type -> Type) a b -> forall c. () => p (Either a c) (Either b c) -- | PastroSum -| TambaraSum -- -- PastroSum freely constructs strength with respect to Either. data PastroSum (p :: Type -> Type -> Type) a b [PastroSum] :: forall y z b (p :: Type -> Type -> Type) x a. (Either y z -> b) -> p x y -> (a -> Either x z) -> PastroSum p a b class Profunctor p => Cochoice (p :: Type -> Type -> Type) -- | Laws: -- --
--   unleftunright . dimap swapE swapE where
--     swapE :: Either a b -> Either b a
--     swapE = either Right Left
--   rmap (either id absurd) ≡ unleft . lmap (either id absurd)
--   unfirst . rmap (second f) ≡ unfirst . lmap (second f)
--   unleft . unleftunleft . dimap assocE unassocE where
--     assocE :: Either (Either a b) c -> Either a (Either b c)
--     assocE (Left (Left a)) = Left a
--     assocE (Left (Right b)) = Right (Left b)
--     assocE (Right c) = Right (Right c)
--     unassocE :: Either a (Either b c) -> Either (Either a b) c
--     unassocE (Left a) = Left (Left a)
--     unassocE (Right (Left b)) = Left (Right b)
--     unassocE (Right (Right c)) = Right c
--   
unleft :: Cochoice p => p (Either a d) (Either b d) -> p a b -- | Laws: -- --
--   unrightunleft . dimap swapE swapE where
--     swapE :: Either a b -> Either b a
--     swapE = either Right Left
--   rmap (either absurd id) ≡ unright . lmap (either absurd id)
--   unsecond . rmap (first f) ≡ unsecond . lmap (first f)
--   unright . unrightunright . dimap unassocE assocE where
--     assocE :: Either (Either a b) c -> Either a (Either b c)
--     assocE (Left (Left a)) = Left a
--     assocE (Left (Right b)) = Right (Left b)
--     assocE (Right c) = Right (Right c)
--     unassocE :: Either a (Either b c) -> Either (Either a b) c
--     unassocE (Left a) = Left (Left a)
--     unassocE (Right (Left b)) = Left (Right b)
--     unassocE (Right (Right c)) = Right c
--   
unright :: Cochoice p => p (Either d a) (Either d b) -> p a b -- | CotambaraSum cofreely constructs costrength with respect to -- Either (aka Choice) data CotambaraSum (q :: Type -> Type -> Type) a b [CotambaraSum] :: forall (r :: Type -> Type -> Type) (q :: Type -> Type -> Type) a b. Cochoice r => (r :-> q) -> r a b -> CotambaraSum q a b -- | CopastroSum -| CotambaraSum -- -- CopastroSum freely constructs costrength with respect to -- Either (aka Choice) newtype CopastroSum (p :: Type -> Type -> Type) a b CopastroSum :: (forall (r :: Type -> Type -> Type). Cochoice r => (forall x y. () => p x y -> r x y) -> r a b) -> CopastroSum (p :: Type -> Type -> Type) a b [runCopastroSum] :: CopastroSum (p :: Type -> Type -> Type) a b -> forall (r :: Type -> Type -> Type). Cochoice r => (forall x y. () => p x y -> r x y) -> r a b -- |
--   close . uncloseid
--   unclose . closeid
--   
unclose :: forall (q :: Type -> Type -> Type) (p :: Type -> Type -> Type). Profunctor q => (p :-> Closure q) -> p :-> q -- |
--   close . uncloseid
--   unclose . closeid
--   
close :: forall (p :: Type -> Type -> Type) (q :: Type -> Type -> Type). Closed p => (p :-> q) -> p :-> Closure q curry' :: Closed p => p (a, b) c -> p a (b -> c) -- | A strong profunctor allows the monoidal structure to pass through. -- -- A closed profunctor allows the closed structure to pass through. class Profunctor p => Closed (p :: Type -> Type -> Type) -- | Laws: -- --
--   lmap (. f) . closedrmap (. f) . closed
--   closed . closeddimap uncurry curry . closed
--   dimap const ($()) . closedid
--   
closed :: Closed p => p a b -> p (x -> a) (x -> b) -- | Closure adjoins a Closed structure to any -- Profunctor. -- -- Analogous to Tambara for Strong. newtype Closure (p :: Type -> Type -> Type) a b Closure :: (forall x. () => p (x -> a) (x -> b)) -> Closure (p :: Type -> Type -> Type) a b [runClosure] :: Closure (p :: Type -> Type -> Type) a b -> forall x. () => p (x -> a) (x -> b) data Environment (p :: Type -> Type -> Type) a b [Environment] :: forall z y b (p :: Type -> Type -> Type) x a. ((z -> y) -> b) -> p x y -> (a -> z -> x) -> Environment p a b -- |
--   cotambara . uncotambaraid
--   uncotambara . cotambaraid
--   
uncotambara :: forall (q :: Type -> Type -> Type) (p :: Type -> Type -> Type). Profunctor q => (p :-> Cotambara q) -> p :-> q -- |
--   cotambara . uncotambaraid
--   uncotambara . cotambaraid
--   
cotambara :: forall (p :: Type -> Type -> Type) (q :: Type -> Type -> Type). Costrong p => (p :-> q) -> p :-> Cotambara q -- |
--   pastro (unpastro f) ≡ f
--   unpastro (pastro f) ≡ f
--   
unpastro :: forall (p :: Type -> Type -> Type) (q :: Type -> Type -> Type). (Pastro p :-> q) -> p :-> q -- |
--   pastro (unpastro f) ≡ f
--   unpastro (pastro f) ≡ f
--   
pastro :: forall (q :: Type -> Type -> Type) (p :: Type -> Type -> Type). Strong q => (p :-> q) -> Pastro p :-> q -- |
--   tambara (untambara f) ≡ f
--   untambara (tambara f) ≡ f
--   
untambara :: forall (q :: Type -> Type -> Type) (p :: Type -> Type -> Type). Profunctor q => (p :-> Tambara q) -> p :-> q -- |
--   tambara (untambara f) ≡ f
--   untambara (tambara f) ≡ f
--   
tambara :: forall (p :: Type -> Type -> Type) (q :: Type -> Type -> Type). Strong p => (p :-> q) -> p :-> Tambara q strong :: Strong p => (a -> b -> c) -> p a b -> p a c uncurry' :: Strong p => p a (b -> c) -> p (a, b) c -- | Generalizing Star of a strong Functor -- -- Note: Every Functor in Haskell is strong with respect to -- (,). -- -- This describes profunctor strength with respect to the product -- structure of Hask. -- -- http://www.riec.tohoku.ac.jp/~asada/papers/arrStrMnd.pdf class Profunctor p => Strong (p :: Type -> Type -> Type) -- | Laws: -- --
--   first'dimap swap swap . second'
--   lmap fstrmap fst . first'
--   lmap (second' f) . first'rmap (second' f) . first'
--   first' . first'dimap assoc unassoc . first' where
--     assoc ((a,b),c) = (a,(b,c))
--     unassoc (a,(b,c)) = ((a,b),c)
--   
first' :: Strong p => p a b -> p (a, c) (b, c) -- | Laws: -- --
--   second'dimap swap swap . first'
--   lmap sndrmap snd . second'
--   lmap (first' f) . second'rmap (first' f) . second'
--   second' . second'dimap unassoc assoc . second' where
--     assoc ((a,b),c) = (a,(b,c))
--     unassoc (a,(b,c)) = ((a,b),c)
--   
second' :: Strong p => p a b -> p (c, a) (c, b) -- | Tambara cofreely makes any Profunctor Strong. newtype Tambara (p :: Type -> Type -> Type) a b Tambara :: (forall c. () => p (a, c) (b, c)) -> Tambara (p :: Type -> Type -> Type) a b [runTambara] :: Tambara (p :: Type -> Type -> Type) a b -> forall c. () => p (a, c) (b, c) -- | Pastro -| Tambara -- --
--   Pastro p ~ exists z. Costar ((,)z) Procompose p Procompose Star ((,)z)
--   
-- -- Pastro freely makes any Profunctor Strong. data Pastro (p :: Type -> Type -> Type) a b [Pastro] :: forall y z b (p :: Type -> Type -> Type) x a. ((y, z) -> b) -> p x y -> (a -> (x, z)) -> Pastro p a b -- | Analogous to ArrowLoop, loop = unfirst class Profunctor p => Costrong (p :: Type -> Type -> Type) -- | Laws: -- --
--   unfirstunsecond . dimap swap swap
--   lmap (,()) ≡ unfirst . rmap (,())
--   unfirst . lmap (second f) ≡ unfirst . rmap (second f)
--   unfirst . unfirst = unfirst . dimap assoc unassoc where
--     assoc ((a,b),c) = (a,(b,c))
--     unassoc (a,(b,c)) = ((a,b),c)
--   
unfirst :: Costrong p => p (a, d) (b, d) -> p a b -- | Laws: -- --
--   unsecondunfirst . dimap swap swap
--   lmap ((),) ≡ unsecond . rmap ((),)
--   unsecond . lmap (first f) ≡ unsecond . rmap (first f)
--   unsecond . unsecond = unsecond . dimap unassoc assoc where
--     assoc ((a,b),c) = (a,(b,c))
--     unassoc (a,(b,c)) = ((a,b),c)
--   
unsecond :: Costrong p => p (d, a) (d, b) -> p a b -- | Cotambara cofreely constructs costrength data Cotambara (q :: Type -> Type -> Type) a b [Cotambara] :: forall (r :: Type -> Type -> Type) (q :: Type -> Type -> Type) a b. Costrong r => (r :-> q) -> r a b -> Cotambara q a b -- | Copastro -| Cotambara -- -- Copastro freely constructs costrength newtype Copastro (p :: Type -> Type -> Type) a b Copastro :: (forall (r :: Type -> Type -> Type). Costrong r => (forall x y. () => p x y -> r x y) -> r a b) -> Copastro (p :: Type -> Type -> Type) a b [runCopastro] :: Copastro (p :: Type -> Type -> Type) a b -> forall (r :: Type -> Type -> Type). Costrong r => (forall x y. () => p x y -> r x y) -> r a b -- | Laws: -- --
--   unit . counitid
--   counit . unitid
--   
class (ProfunctorFunctor f, ProfunctorFunctor u) => ProfunctorAdjunction (f :: Type -> Type -> Type -> Type -> Type -> Type) (u :: Type -> Type -> Type -> Type -> Type -> Type) | f -> u, u -> f unit :: forall (p :: Type -> Type -> Type). (ProfunctorAdjunction f u, Profunctor p) => p :-> u (f p) counit :: forall (p :: Type -> Type -> Type). (ProfunctorAdjunction f u, Profunctor p) => f (u p) :-> p -- | ProfunctorFunctor has a polymorphic kind since 5.6. class ProfunctorFunctor (t :: Type -> Type -> Type -> k -> k1 -> Type) -- | Laws: -- --
--   promap f . promap g ≡ promap (f . g)
--   promap idid
--   
promap :: forall (p :: Type -> Type -> Type) (q :: Type -> Type -> Type). (ProfunctorFunctor t, Profunctor p) => (p :-> q) -> t p :-> t q -- | Laws: -- --
--   promap f . proreturnproreturn . f
--   projoin . proreturnid
--   projoin . promap proreturnid
--   projoin . projoinprojoin . promap projoin
--   
class ProfunctorFunctor t => ProfunctorMonad (t :: Type -> Type -> Type -> Type -> Type -> Type) proreturn :: forall (p :: Type -> Type -> Type). (ProfunctorMonad t, Profunctor p) => p :-> t p projoin :: forall (p :: Type -> Type -> Type). (ProfunctorMonad t, Profunctor p) => t (t p) :-> t p -- | Laws: -- --
--   proextract . promap f ≡ f . proextract
--   proextract . produplicateid
--   promap proextract . produplicateid
--   produplicate . produplicatepromap produplicate . produplicate
--   
class ProfunctorFunctor t => ProfunctorComonad (t :: Type -> Type -> Type -> Type -> Type -> Type) proextract :: forall (p :: Type -> Type -> Type). (ProfunctorComonad t, Profunctor p) => t p :-> p produplicate :: forall (p :: Type -> Type -> Type). (ProfunctorComonad t, Profunctor p) => t p :-> t (t p) -- | (:->) has a polymorphic kind since 5.6. type (p :: k -> k1 -> Type) :-> (q :: k -> k1 -> Type) = forall (a :: k) (b :: k1). () => p a b -> q a b infixr 0 :-> -- | Lift a Functor into a Profunctor (forwards). -- -- Star has a polymorphic kind since 5.6. newtype Star (f :: k -> Type) d (c :: k) Star :: (d -> f c) -> Star (f :: k -> Type) d (c :: k) [runStar] :: Star (f :: k -> Type) d (c :: k) -> d -> f c -- | Lift a Functor into a Profunctor (backwards). -- -- Costar has a polymorphic kind since 5.6. newtype Costar (f :: k -> Type) (d :: k) c Costar :: (f d -> c) -> Costar (f :: k -> Type) (d :: k) c [runCostar] :: Costar (f :: k -> Type) (d :: k) c -> f d -> c -- | Forget has a polymorphic kind since 5.6. newtype Forget r a (b :: k) Forget :: (a -> r) -> Forget r a (b :: k) [runForget] :: Forget r a (b :: k) -> a -> r -- | An arbitrary-precision number represented using scientific -- notation. -- -- This type describes the set of all Reals which have a -- finite decimal expansion. -- -- A scientific number with coefficient c and -- base10Exponent e corresponds to the Fractional -- number: fromInteger c * 10 ^^ e data Scientific -- | Generalised folding with the short-circuiting behaviour. foldS :: (Selective f, Foldable t, Monoid a) => t (f (Either e a)) -> f (Either e a) -- | A lifted version of all. Retains the short-circuiting -- behaviour. allS :: Selective f => (a -> f Bool) -> [a] -> f Bool -- | A lifted version of any. Retains the short-circuiting -- behaviour. anyS :: Selective f => (a -> f Bool) -> [a] -> f Bool -- | A lifted version of lazy Boolean AND. (<&&>) :: Selective f => f Bool -> f Bool -> f Bool -- | A lifted version of lazy Boolean OR. (<||>) :: Selective f => f Bool -> f Bool -> f Bool -- | Keep running an effectful computation until it returns a -- Right value, collecting the Left's using a supplied -- Monoid instance. untilRight :: (Monoid a, Selective f) => f (Either a b) -> f (a, b) -- | Keep checking an effectful condition while it holds. whileS :: Selective f => f Bool -> f () -- | Accumulate the Right values, or return the first -- Left. andAlso :: (Selective f, Semigroup a) => f (Either e a) -> f (Either e a) -> f (Either e a) -- | Return the first Right value. If both are Left's, -- accumulate errors. orElse :: (Selective f, Semigroup e) => f (Either e a) -> f (Either e a) -> f (Either e a) -- | A lifted version of fromMaybe. fromMaybeS :: Selective f => f a -> f (Maybe a) -> f a -- | Conditionally perform an effect. whenS :: Selective f => f Bool -> f () -> f () -- | A restricted version of monadic bind. Fails with an error if the -- Bounded and Enum instances for a do not cover -- all values of a. bindS :: (Bounded a, Enum a, Eq a, Selective f) => f a -> (a -> f b) -> f b -- | Eliminate all specified values a from f (Either a b) -- by replacing each of them with a given f a. matchM :: Monad m => Cases a -> m a -> (a -> m b) -> m (Either a b) -- | Eliminate all specified values a from f (Either a b) -- by replacing each of them with a given f a. matchS :: (Eq a, Selective f) => Cases a -> f a -> (a -> f b) -> f (Either a b) -- | Embed a list of values into Cases using the trivial but slow -- membership test based on elem. cases :: Eq a => [a] -> Cases a -- | The list of all possible values of an enumerable data type. casesEnum :: (Bounded a, Enum a) => Cases a -- | Branch on a Boolean value, skipping unnecessary effects. ifS :: Selective f => f Bool -> f a -> f a -> f a -- | One can easily implement a monadic selectM that satisfies the -- laws, hence any Monad is Selective. selectM :: Monad f => f (Either a b) -> f (a -> b) -> f b -- | Recover the application operator <*> from select. -- Rigid selective functors satisfy the law <*> -- = apS and furthermore, the resulting applicative -- functor satisfies all laws of Applicative: -- -- apS :: Selective f => f (a -> b) -> f a -> f b -- | For traversable functors, we can implement select in another -- interesting way: the effects associated with the second argument can -- be skipped as long as the first argument contains only Right -- values. selectT :: Traversable f => f (Either a b) -> f (a -> b) -> f b -- | We can write a function with the type signature of select using -- the Applicative type class, but it will always execute the -- effects associated with the second argument, hence being potentially -- less efficient. selectA :: Applicative f => f (Either a b) -> f (a -> b) -> f b -- | The branch function is a natural generalisation of -- select: instead of skipping an unnecessary effect, it chooses -- which of the two given effectful functions to apply to a given -- argument; the other effect is unnecessary. It is possible to implement -- branch in terms of select, which is a good puzzle (give -- it a try!). -- -- We can also implement select via branch: -- --
--   selectB :: Selective f => f (Either a b) -> f (a -> b) -> f b
--   selectB x y = branch x y (pure id)
--   
branch :: Selective f => f (Either a b) -> f (a -> c) -> f (b -> c) -> f c -- | An operator alias for select, which is sometimes convenient. It -- tries to follow the notational convention for Applicative -- operators. The angle bracket pointing to the left means we always use -- the corresponding value. The value on the right, however, may be -- skipped, hence the question mark. (<*?) :: Selective f => f (Either a b) -> f (a -> b) -> f b infixl 4 <*? -- | Selective applicative functors. You can think of select as a -- selective function application: when given a value of type Left -- a, you must apply the given function, but when given a -- Right b, you may skip the function and -- associated effects, and simply return the b. -- -- Note that it is not a requirement for selective functors to skip -- unnecessary effects. It may be counterintuitive, but this makes them -- more useful. Why? Typically, when executing a selective computation, -- you would want to skip the effects (saving work); but on the other -- hand, if your goal is to statically analyse a given selective -- computation and extract the set of all possible effects (without -- actually executing them), then you do not want to skip any effects, -- because that defeats the purpose of static analysis. -- -- The type signature of select is reminiscent of both -- <*> and >>=, and indeed a selective functor -- is in some sense a composition of an applicative functor and the -- Either monad. -- -- Laws: -- -- -- --
--   x <*? pure id = either id id <$> x
--   
-- -- -- --
--   pure x <*? (y *> z) = (pure x <*? y) *> (pure x <*? z)
--   
-- -- -- --
--   x <*? (y <*? z) = (f <$> x) <*? (g <$> y) <*? (h <$> z)
--     where
--       f x = Right <$> x
--       g y = a -> bimap (,a) ($a) y
--       h z = uncurry z
--   
-- -- -- --
--   select = selectM
--   
-- -- There are also a few useful theorems: -- -- -- --
--   f <$> select x y = select (fmap f <$> x) (fmap f <$> y)
--   
-- -- -- --
--   select (first f <$> x) y = select x ((. f) <$> y)
--   
-- -- -- --
--   select x (f <$> y) = select (first (flip f) <$> x) ((&) <$> y)
--   
-- -- -- --
--   x <*? pure y = either y id <$> x
--   
-- -- -- --
--   x *> (y <*? z) = (x *> y) <*? z
--   
-- -- If f is also a Monad, we require that select = -- selectM, from which one can prove <*> = -- apS. class Applicative f => Selective (f :: Type -> Type) select :: Selective f => f (Either a b) -> f (a -> b) -> f b -- | A list of values, equipped with a fast membership test. data Cases a -- | Any applicative functor can be given a Selective instance by -- defining select = selectA. This data type -- captures this pattern, so you can use it in combination with the -- DerivingVia extension as follows: -- --
--   newtype Over m a = Over m
--       deriving (Functor, Applicative, Selective) via SelectA (Const m)
--   
newtype SelectA (f :: Type -> Type) a SelectA :: f a -> SelectA (f :: Type -> Type) a [getSelectA] :: SelectA (f :: Type -> Type) a -> f a -- | Any monad can be given a Selective instance by defining -- select = selectM. This data type captures this -- pattern, so you can use it in combination with the -- DerivingVia extension as follows: -- --
--   newtype V1 a = V1 a
--       deriving (Functor, Applicative, Selective, Monad) via SelectM Identity
--   
newtype SelectM (f :: Type -> Type) a SelectM :: f a -> SelectM (f :: Type -> Type) a [getSelectM] :: SelectM (f :: Type -> Type) a -> f a -- | Static analysis of selective functors with over-approximation. newtype Over m a Over :: m -> Over m a [getOver] :: Over m a -> m -- | Static analysis of selective functors with under-approximation. newtype Under m a Under :: m -> Under m a [getUnder] :: Under m a -> m -- | Selective instance for the standard applicative functor Validation. -- This is a good example of a non-trivial selective functor which is not -- a monad. data Validation e a Failure :: e -> Validation e a Success :: a -> Validation e a -- | Composition of a selective functor f and an applicative -- traversable functor g. newtype ComposeTraversable (f :: Type -> Type) (g :: Type -> Type) a ComposeTraversable :: f (g a) -> ComposeTraversable (f :: Type -> Type) (g :: Type -> Type) a -- | Composition of a selective functor f with the Either -- monad. newtype ComposeEither (f :: Type -> Type) e a ComposeEither :: f (Either e a) -> ComposeEither (f :: Type -> Type) e a -- | The sum of a collection of actions, generalizing concat. -- --
--   >>> psum [Just "Hello", Nothing, Just "World"]
--   Just "Hello"
--   
psum :: (Foldable t, Plus f) => t (f a) -> f a -- | Laws: -- --
--   zero <!> m = m
--   m <!> zero = m
--   
-- -- If extended to an Alternative then zero should equal -- empty. class Alt f => Plus (f :: Type -> Type) zero :: Plus f => f a bifoldMap1Default :: (Bitraversable1 t, Semigroup m) => (a -> m) -> (b -> m) -> t a b -> m -- | Default implementation of foldMap1 given an implementation of -- Traversable1. foldMap1Default :: (Traversable1 f, Semigroup m) => (a -> m) -> f a -> m class (Bifoldable1 t, Bitraversable t) => Bitraversable1 (t :: TYPE LiftedRep -> TYPE LiftedRep -> Type) bitraverse1 :: (Bitraversable1 t, Apply f) => (a -> f b) -> (c -> f d) -> t a c -> f (t b d) bisequence1 :: (Bitraversable1 t, Apply f) => t (f a) (f b) -> f (t a b) class (Foldable1 t, Traversable t) => Traversable1 (t :: TYPE LiftedRep -> Type) traverse1 :: (Traversable1 t, Apply f) => (a -> f b) -> t a -> f (t b) sequence1 :: (Traversable1 t, Apply f) => t (f b) -> f (t b) -- | Monadic fold over the elements of a non-empty structure, associating -- to the left, i.e. from left to right. -- --
--   let g = flip $ (=<<) . f
--   in foldlM1 f (x1 :| [x2, ..., xn]) == (...((x1 `f` x2) `g` x2) `g`...) `g` xn
--   
foldlM1 :: (Foldable1 t, Monad m) => (a -> a -> m a) -> t a -> m a -- | Monadic fold over the elements of a non-empty structure, associating -- to the right, i.e. from right to left. -- --
--   let g = (=<<) . f
--   in foldrM1 f (x1 :| [x2, ..., xn]) == x1 `g` (x2 `g` ... (xn-1 `f` xn)...)
--   
foldrM1 :: (Foldable1 t, Monad m) => (a -> a -> m a) -> t a -> m a asum1 :: (Foldable1 t, Alt m) => t (m a) -> m a -- | Usable default for foldMap, but only if you define foldMap1 yourself foldMapDefault1 :: (Foldable1 t, Monoid m) => (a -> m) -> t a -> m sequenceA1_ :: (Foldable1 t, Apply f) => t (f a) -> f () for1_ :: (Foldable1 t, Apply f) => t a -> (a -> f b) -> f () traverse1_ :: (Foldable1 t, Apply f) => (a -> f b) -> t a -> f () -- | Insert m between each pair of m derived from -- a. -- --
--   >>> intercalateMap1 " " show $ True :| [False, True]
--   "True False True"
--   
-- --
--   >>> intercalateMap1 " " show $ True :| []
--   "True"
--   
intercalateMap1 :: (Foldable1 t, Semigroup m) => m -> (a -> m) -> t a -> m -- | Insert an m between each pair of t m. Equivalent to -- intercalateMap1 with id as the second argument. -- --
--   >>> intercalate1 ", " $ "hello" :| ["how", "are", "you"]
--   "hello, how, are, you"
--   
-- --
--   >>> intercalate1 ", " $ "hello" :| []
--   "hello"
--   
-- --
--   >>> intercalate1 mempty $ "I" :| ["Am", "Fine", "You?"]
--   "IAmFineYou?"
--   
intercalate1 :: (Foldable1 t, Semigroup m) => m -> t m -> m -- | Laws: -- --
--   <!> is associative:             (a <!> b) <!> c = a <!> (b <!> c)
--   <$> left-distributes over <!>:  f <$> (a <!> b) = (f <$> a) <!> (f <$> b)
--   
-- -- If extended to an Alternative then <!> should -- equal <|>. -- -- Ideally, an instance of Alt also satisfies the "left -- distribution" law of MonadPlus with respect to <.>: -- --
--   <.> right-distributes over <!>: (a <!> b) <.> c = (a <.> c) <!> (b <.> c)
--   
-- -- IO, Either a, ExceptT e m and -- STM instead satisfy the "left catch" law: -- --
--   pure a <!> b = pure a
--   
-- -- Maybe and Identity satisfy both "left distribution" and -- "left catch". -- -- These variations cannot be stated purely in terms of the dependencies -- of Alt. -- -- When and if MonadPlus is successfully refactored, this class should -- also be refactored to remove these instances. -- -- The right distributive law should extend in the cases where the a -- Bind or Monad is provided to yield variations of the -- right distributive law: -- --
--   (m <!> n) >>- f = (m >>- f) <!> (m >>- f)
--   (m <!> n) >>= f = (m >>= f) <!> (m >>= f)
--   
class Functor f => Alt (f :: Type -> Type) -- | <|> without a required empty () :: Alt f => f a -> f a -> f a infixl 3 -- | Lift ternary functions bilift3 :: Biapply w => (a -> b -> c -> d) -> (e -> f -> g -> h) -> w a e -> w b f -> w c g -> w d h -- | Lift binary functions bilift2 :: Biapply w => (a -> b -> c) -> (d -> e -> f) -> w a d -> w b e -> w c f (<<..>>) :: Biapply p => p a c -> p (a -> b) (c -> d) -> p b d infixl 4 <<..>> -- | semigroupoid with inverses. This technically should be a category with -- inverses, except we need to use Ob to define the valid objects for the -- category class Semigroupoid k1 => Groupoid (k1 :: k -> k -> Type) inv :: forall (a :: k) (b :: k). Groupoid k1 => k1 a b -> k1 b a -- | Category sans id class Semigroupoid (c :: k -> k -> Type) o :: forall (j :: k) (k1 :: k) (i :: k). Semigroupoid c => c j k1 -> c i j -> c i k1 newtype WrappedCategory (k2 :: k -> k1 -> Type) (a :: k) (b :: k1) WrapCategory :: k2 a b -> WrappedCategory (k2 :: k -> k1 -> Type) (a :: k) (b :: k1) [unwrapCategory] :: WrappedCategory (k2 :: k -> k1 -> Type) (a :: k) (b :: k1) -> k2 a b newtype Semi m (a :: k) (b :: k1) Semi :: m -> Semi m (a :: k) (b :: k1) [getSemi] :: Semi m (a :: k) (b :: k1) -> m (-<-) :: Bind m => (b -> m c) -> (a -> m b) -> a -> m c infixr 1 -<- (->-) :: Bind m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 ->- (-<<) :: Bind m => (a -> m b) -> m a -> m b infixr 1 -<< -- | Usable default for foldMap, but only if you define bifoldMap1 yourself bifoldMapDefault1 :: (Bifoldable1 t, Monoid m) => (a -> m) -> (b -> m) -> t a b -> m bisequenceA1_ :: (Bifoldable1 t, Apply f) => t (f a) (f b) -> f () bifor1_ :: (Bifoldable1 t, Apply f) => t a c -> (a -> f b) -> (c -> f d) -> f () bitraverse1_ :: (Bifoldable1 t, Apply f) => (a -> f b) -> (c -> f d) -> t a c -> f () -- | Lift a ternary function into a comonad with zipping liftF3 :: Apply w => (a -> b -> c -> d) -> w a -> w b -> w c -> w d -- | A variant of <.> with the arguments reversed. (<..>) :: Apply w => w a -> w (a -> b) -> w b infixl 4 <..> apDefault :: Bind f => f (a -> b) -> f a -> f b returning :: Functor f => f a -> (a -> b) -> f b -- | Traverse a Traversable using Apply, getting the results -- back in a MaybeApply. traverse1Maybe :: (Traversable t, Apply f) => (a -> f b) -> t a -> MaybeApply f (t b) -- | Apply a possibly-empty-with-unit container of functions to a non-empty -- container of values. (<*.>) :: Apply f => MaybeApply f (a -> b) -> f a -> f b infixl 4 <*.> -- | Apply a non-empty container of functions to a possibly-empty-with-unit -- container of values. (<.*>) :: Apply f => f (a -> b) -> MaybeApply f a -> f b infixl 4 <.*> -- | A strong lax semi-monoidal endofunctor. This is equivalent to an -- Applicative without pure. -- -- Laws: -- --
--   (.) <$> u <.> v <.> w = u <.> (v <.> w)
--   x <.> (f <$> y) = (. f) <$> x <.> y
--   f <$> (x <.> y) = (f .) <$> x <.> y
--   
-- -- The laws imply that .> and <. really ignore their -- left and right results, respectively, and really return their right -- and left results, respectively. Specifically, -- --
--   (mf <$> m) .> (nf <$> n) = nf <$> (m .> n)
--   (mf <$> m) <. (nf <$> n) = mf <$> (m <. n)
--   
class Functor f => Apply (f :: Type -> Type) (<.>) :: Apply f => f (a -> b) -> f a -> f b -- |
--   a .> b = const id <$> a <.> b
--   
(.>) :: Apply f => f a -> f b -> f b -- |
--   a <. b = const <$> a <.> b
--   
(<.) :: Apply f => f a -> f b -> f a -- | Lift a binary function into a comonad with zipping liftF2 :: Apply f => (a -> b -> c) -> f a -> f b -> f c infixl 4 <. infixl 4 <.> infixl 4 .> -- | Wrap an Applicative to be used as a member of Apply newtype WrappedApplicative (f :: Type -> Type) a WrapApplicative :: f a -> WrappedApplicative (f :: Type -> Type) a [unwrapApplicative] :: WrappedApplicative (f :: Type -> Type) a -> f a -- | Transform an Apply into an Applicative by adding a unit. newtype MaybeApply (f :: Type -> Type) a MaybeApply :: Either (f a) a -> MaybeApply (f :: Type -> Type) a [runMaybeApply] :: MaybeApply (f :: Type -> Type) a -> Either (f a) a -- | A Monad sans return. -- -- Minimal definition: Either join or >>- -- -- If defining both, then the following laws (the default definitions) -- must hold: -- --
--   join = (>>- id)
--   m >>- f = join (fmap f m)
--   
-- -- Laws: -- --
--   induced definition of <.>: f <.> x = f >>- (<$> x)
--   
-- -- Finally, there are two associativity conditions: -- --
--   associativity of (>>-):    (m >>- f) >>- g == m >>- (\x -> f x >>- g)
--   associativity of join:     join . join = join . fmap join
--   
-- -- These can both be seen as special cases of the constraint that -- --
--   associativity of (->-): (f ->- g) ->- h = f ->- (g ->- h)
--   
class Apply m => Bind (m :: Type -> Type) (>>-) :: Bind m => m a -> (a -> m b) -> m b infixl 1 >>- class Bifunctor p => Biapply (p :: Type -> Type -> Type) (<<.>>) :: Biapply p => p (a -> b) (c -> d) -> p a c -> p b d -- |
--   a .> b ≡ const id <$> a <.> b
--   
(.>>) :: Biapply p => p a b -> p c d -> p c d -- |
--   a <. b ≡ const <$> a <.> b
--   
(<<.) :: Biapply p => p a b -> p c d -> p a b infixl 4 <<. infixl 4 <<.>> infixl 4 .>> class Foldable t => Foldable1 (t :: TYPE LiftedRep -> Type) fold1 :: (Foldable1 t, Semigroup m) => t m -> m foldMap1 :: (Foldable1 t, Semigroup m) => (a -> m) -> t a -> m toNonEmpty :: Foldable1 t => t a -> NonEmpty a class Bifoldable t => Bifoldable1 (t :: TYPE LiftedRep -> TYPE LiftedRep -> Type) bifold1 :: (Bifoldable1 t, Semigroup m) => t m m -> m bifoldMap1 :: (Bifoldable1 t, Semigroup m) => (a -> m) -> (b -> m) -> t a b -> m class Functor w => Extend (w :: Type -> Type) -- |
--   duplicated = extended id
--   fmap (fmap f) . duplicated = duplicated . fmap f
--   
duplicated :: Extend w => w a -> w (w a) -- |
--   extended f  = fmap f . duplicated
--   
extended :: Extend w => (w a -> b) -> w a -> w b -- | Check that the boolean condition is true and, if not, retry. -- -- In other words, check b = unless b retry. check :: Bool -> STM () -- | TArray is a transactional array, supporting the usual MArray -- interface for mutable arrays. -- -- It is currently implemented as Array ix (TVar e), but it may -- be replaced by a more efficient implementation in the future (the -- interface will remain the same, however). data TArray i e -- | Swap the contents of a TVar for a new value. swapTVar :: TVar a -> a -> STM a -- | Like modifyTVar' but the function is a simple state transition -- that can return a side value which is passed on as the result of the -- STM. stateTVar :: TVar s -> (s -> (a, s)) -> STM a -- | Strict version of modifyTVar. modifyTVar' :: TVar a -> (a -> a) -> STM () -- | Mutate the contents of a TVar. N.B., this version is -- non-strict. modifyTVar :: TVar a -> (a -> a) -> STM () -- | Make a Weak pointer to a TVar, using the second argument -- as a finalizer to run when TVar is garbage-collected mkWeakTVar :: TVar a -> IO () -> IO (Weak (TVar a)) -- | TQueue is an abstract type representing an unbounded FIFO -- channel. data TQueue a -- | Write a value to a TQueue. writeTQueue :: TQueue a -> a -> STM () -- | Put a data item back onto a channel, where it will be the next item -- read. unGetTQueue :: TQueue a -> a -> STM () -- | A version of readTQueue which does not retry. Instead it -- returns Nothing if no value is available. tryReadTQueue :: TQueue a -> STM (Maybe a) -- | A version of peekTQueue which does not retry. Instead it -- returns Nothing if no value is available. tryPeekTQueue :: TQueue a -> STM (Maybe a) -- | Read the next value from the TQueue. readTQueue :: TQueue a -> STM a -- | Get the next value from the TQueue without removing it, -- retrying if the channel is empty. peekTQueue :: TQueue a -> STM a -- | IO version of newTQueue. This is useful for creating -- top-level TQueues using unsafePerformIO, because using -- atomically inside unsafePerformIO isn't possible. newTQueueIO :: IO (TQueue a) -- | Build and returns a new instance of TQueue newTQueue :: STM (TQueue a) -- | Returns True if the supplied TQueue is empty. isEmptyTQueue :: TQueue a -> STM Bool -- | Efficiently read the entire contents of a TQueue into a list. -- This function never retries. flushTQueue :: TQueue a -> STM [a] -- | A TMVar is a synchronising variable, used for communication -- between concurrent threads. It can be thought of as a box, which may -- be empty or full. data TMVar a -- | A version of takeTMVar that does not retry. The -- tryTakeTMVar function returns Nothing if the -- TMVar was empty, or Just a if the TMVar -- was full with contents a. After tryTakeTMVar, the -- TMVar is left empty. tryTakeTMVar :: TMVar a -> STM (Maybe a) -- | A version of readTMVar which does not retry. Instead it returns -- Nothing if no value is available. tryReadTMVar :: TMVar a -> STM (Maybe a) -- | A version of putTMVar that does not retry. The -- tryPutTMVar function attempts to put the value a into -- the TMVar, returning True if it was successful, or -- False otherwise. tryPutTMVar :: TMVar a -> a -> STM Bool -- | Return the contents of the TMVar. If the TMVar is -- currently empty, the transaction will retry. After a -- takeTMVar, the TMVar is left empty. takeTMVar :: TMVar a -> STM a -- | Swap the contents of a TMVar for a new value. swapTMVar :: TMVar a -> a -> STM a -- | This is a combination of takeTMVar and putTMVar; ie. it -- takes the value from the TMVar, puts it back, and also returns -- it. readTMVar :: TMVar a -> STM a -- | Put a value into a TMVar. If the TMVar is currently -- full, putTMVar will retry. putTMVar :: TMVar a -> a -> STM () -- | IO version of newTMVar. This is useful for creating -- top-level TMVars using unsafePerformIO, because using -- atomically inside unsafePerformIO isn't possible. newTMVarIO :: a -> IO (TMVar a) -- | Create a TMVar which contains the supplied value. newTMVar :: a -> STM (TMVar a) -- | IO version of newEmptyTMVar. This is useful for -- creating top-level TMVars using unsafePerformIO, because -- using atomically inside unsafePerformIO isn't possible. newEmptyTMVarIO :: IO (TMVar a) -- | Create a TMVar which is initially empty. newEmptyTMVar :: STM (TMVar a) -- | Make a Weak pointer to a TMVar, using the second -- argument as a finalizer to run when the TMVar is -- garbage-collected. mkWeakTMVar :: TMVar a -> IO () -> IO (Weak (TMVar a)) -- | Check whether a given TMVar is empty. isEmptyTMVar :: TMVar a -> STM Bool -- | TChan is an abstract type representing an unbounded FIFO -- channel. data TChan a -- | Write a value to a TChan. writeTChan :: TChan a -> a -> STM () -- | Put a data item back onto a channel, where it will be the next item -- read. unGetTChan :: TChan a -> a -> STM () -- | A version of readTChan which does not retry. Instead it returns -- Nothing if no value is available. tryReadTChan :: TChan a -> STM (Maybe a) -- | A version of peekTChan which does not retry. Instead it returns -- Nothing if no value is available. tryPeekTChan :: TChan a -> STM (Maybe a) -- | Read the next value from the TChan. readTChan :: TChan a -> STM a -- | Get the next value from the TChan without removing it, -- retrying if the channel is empty. peekTChan :: TChan a -> STM a -- | IO version of newTChan. This is useful for creating -- top-level TChans using unsafePerformIO, because using -- atomically inside unsafePerformIO isn't possible. newTChanIO :: IO (TChan a) -- | Build and return a new instance of TChan newTChan :: STM (TChan a) -- | IO version of newBroadcastTChan. newBroadcastTChanIO :: IO (TChan a) -- | Create a write-only TChan. More precisely, readTChan -- will retry even after items have been written to the channel. -- The only way to read a broadcast channel is to duplicate it with -- dupTChan. -- -- Consider a server that broadcasts messages to clients: -- --
--   serve :: TChan Message -> Client -> IO loop
--   serve broadcastChan client = do
--       myChan <- dupTChan broadcastChan
--       forever $ do
--           message <- readTChan myChan
--           send client message
--   
-- -- The problem with using newTChan to create the broadcast channel -- is that if it is only written to and never read, items will pile up in -- memory. By using newBroadcastTChan to create the broadcast -- channel, items can be garbage collected after clients have seen them. newBroadcastTChan :: STM (TChan a) -- | Returns True if the supplied TChan is empty. isEmptyTChan :: TChan a -> STM Bool -- | Duplicate a TChan: the duplicate channel begins empty, but data -- written to either channel from then on will be available from both. -- Hence this creates a kind of broadcast channel, where data written by -- anyone is seen by everyone else. dupTChan :: TChan a -> STM (TChan a) -- | Clone a TChan: similar to dupTChan, but the cloned channel -- starts with the same content available as the original channel. cloneTChan :: TChan a -> STM (TChan a) -- | TBQueue is an abstract type representing a bounded FIFO -- channel. data TBQueue a -- | Write a value to a TBQueue; blocks if the queue is full. writeTBQueue :: TBQueue a -> a -> STM () -- | Put a data item back onto a channel, where it will be the next item -- read. Blocks if the queue is full. unGetTBQueue :: TBQueue a -> a -> STM () -- | A version of readTBQueue which does not retry. Instead it -- returns Nothing if no value is available. tryReadTBQueue :: TBQueue a -> STM (Maybe a) -- | A version of peekTBQueue which does not retry. Instead it -- returns Nothing if no value is available. tryPeekTBQueue :: TBQueue a -> STM (Maybe a) -- | Read the next value from the TBQueue. readTBQueue :: TBQueue a -> STM a -- | Get the next value from the TBQueue without removing it, -- retrying if the channel is empty. peekTBQueue :: TBQueue a -> STM a -- | IO version of newTBQueue. This is useful for creating -- top-level TBQueues using unsafePerformIO, because using -- atomically inside unsafePerformIO isn't possible. newTBQueueIO :: Natural -> IO (TBQueue a) -- | Builds and returns a new instance of TBQueue. newTBQueue :: Natural -> STM (TBQueue a) -- | Return the length of a TBQueue. lengthTBQueue :: TBQueue a -> STM Natural -- | Returns True if the supplied TBQueue is full. isFullTBQueue :: TBQueue a -> STM Bool -- | Returns True if the supplied TBQueue is empty. isEmptyTBQueue :: TBQueue a -> STM Bool -- | Efficiently read the entire contents of a TBQueue into a list. -- This function never retries. flushTBQueue :: TBQueue a -> STM [a] -- | A space efficient, packed, unboxed Unicode text type. data Text class ISO8601 t -- | The most commonly used ISO 8601 format for this type. iso8601Format :: ISO8601 t => Format t -- | Show in the most commonly used ISO 8601 format. iso8601Show :: ISO8601 t => t -> String -- | Parse the most commonly used ISO 8601 format. iso8601ParseM :: (MonadFail m, ISO8601 t) => String -> m t -- | Parse a time value given a format string. See parseTimeM for -- details. readSTime :: ParseTime t => Bool -> TimeLocale -> String -> ReadS t -- | Parse a time value given a format string. See parseTimeM for -- details. readPTime :: ParseTime t => Bool -> TimeLocale -> String -> ReadP t -- | Parse a time value given a format string. Fails if the input could not -- be parsed using the given format. See parseTimeM for details. parseTimeOrError :: ParseTime t => Bool -> TimeLocale -> String -> String -> t -- | Parses a time value given a list of pairs of format and input. -- Resulting value is constructed from all provided specifiers. parseTimeMultipleM :: (MonadFail m, ParseTime t) => Bool -> TimeLocale -> [(String, String)] -> m t -- | Parses a time value given a format string. Missing information will be -- derived from 1970-01-01 00:00 UTC (which was a Thursday). Supports the -- same %-codes as formatTime, including %-, -- %_ and %0 modifiers, however padding widths are not -- supported. Case is not significant in the input string. Some -- variations in the input are accepted: -- -- -- -- For example, to parse a date in YYYY-MM-DD format, while allowing the -- month and date to have optional leading zeros (notice the - -- modifier used for %m and %d): -- --
--   Prelude Data.Time> parseTimeM True defaultTimeLocale "%Y-%-m-%-d" "2010-3-04" :: Maybe Day
--   Just 2010-03-04
--   
parseTimeM :: (MonadFail m, ParseTime t) => Bool -> TimeLocale -> String -> String -> m t -- | A local time together with a time zone. -- -- There is no Eq instance for ZonedTime. If you want to -- compare local times, use zonedTimeToLocalTime. If you want to -- compare absolute times, use zonedTimeToUTC. data ZonedTime ZonedTime :: LocalTime -> TimeZone -> ZonedTime [zonedTimeToLocalTime] :: ZonedTime -> LocalTime [zonedTimeZone] :: ZonedTime -> TimeZone zonedTimeToUTC :: ZonedTime -> UTCTime utcToZonedTime :: TimeZone -> UTCTime -> ZonedTime utcToLocalZonedTime :: UTCTime -> IO ZonedTime getZonedTime :: IO ZonedTime class FormatTime t -- | Substitute various time-related information for each %-code in the -- string, as per formatCharacter. -- -- The general form is -- %<modifier><width><alternate><specifier>, -- where <modifier>, <width>, and -- <alternate> are optional. -- --

<modifier>

-- -- glibc-style modifiers can be used before the specifier (here marked as -- z): -- -- -- --

<width>

-- -- Width digits can also be used after any modifiers and before the -- specifier (here marked as z), for example: -- -- -- --

<alternate>

-- -- An optional E character indicates an alternate formatting. -- Currently this only affects %Z and %z. -- -- -- --

<specifier>

-- -- For all types (note these three are done by formatTime, not by -- formatCharacter): -- -- -- --

TimeZone

-- -- For TimeZone (and ZonedTime and UTCTime): -- -- -- --

LocalTime

-- -- For LocalTime (and ZonedTime and UTCTime -- and UniversalTime): -- -- -- --

TimeOfDay

-- -- For TimeOfDay (and LocalTime and ZonedTime -- and UTCTime and UniversalTime): -- -- -- --

UTCTime and ZonedTime

-- -- For UTCTime and ZonedTime: -- -- -- --

DayOfWeek

-- -- For DayOfWeek (and Day and LocalTime and -- ZonedTime and UTCTime and UniversalTime): -- -- -- --

Month

-- -- For Month (and Day and LocalTime and -- ZonedTime and UTCTime and UniversalTime): -- -- -- --

Day

-- -- For Day (and LocalTime and ZonedTime and -- UTCTime and UniversalTime): -- -- -- --

Duration types

-- -- The specifiers for DiffTime, NominalDiffTime, -- CalendarDiffDays, and CalendarDiffTime are -- semantically separate from the other types. Specifiers on negative -- time differences will generally be negative (think rem rather -- than mod). -- --

NominalDiffTime and DiffTime

-- -- Note that a "minute" of DiffTime is simply 60 SI seconds, -- rather than a minute of civil time. Use NominalDiffTime to -- work with civil time, ignoring any leap seconds. -- -- For NominalDiffTime and DiffTime: -- -- -- --

CalendarDiffDays

-- -- For CalendarDiffDays (and CalendarDiffTime): -- -- -- --

CalendarDiffTime

-- -- For CalendarDiffTime: -- -- formatTime :: FormatTime t => TimeLocale -> String -> t -> String -- | The class of types which can be parsed given a UNIX-style time format -- string. class ParseTime t data TimeLocale TimeLocale :: [(String, String)] -> [(String, String)] -> (String, String) -> String -> String -> String -> String -> [TimeZone] -> TimeLocale -- | full and abbreviated week days, starting with Sunday [wDays] :: TimeLocale -> [(String, String)] -- | full and abbreviated months [months] :: TimeLocale -> [(String, String)] -- | AM/PM symbols [amPm] :: TimeLocale -> (String, String) -- | formatting strings [dateTimeFmt] :: TimeLocale -> String -- | formatting strings [dateFmt] :: TimeLocale -> String -- | formatting strings [timeFmt] :: TimeLocale -> String -- | formatting strings [time12Fmt] :: TimeLocale -> String -- | time zones known by name [knownTimeZones] :: TimeLocale -> [TimeZone] -- | Format string according to RFC822. rfc822DateFormat :: String -- | Construct format string according to ISO-8601. -- -- The Maybe String argument allows to supply an optional time -- specification. E.g.: -- --
--   iso8601DateFormat Nothing            == "%Y-%m-%d"           -- i.e. YYYY-MM-DD
--   iso8601DateFormat (Just "%H:%M:%S")  == "%Y-%m-%dT%H:%M:%S"  -- i.e. YYYY-MM-DDTHH:MM:SS
--   
iso8601DateFormat :: Maybe String -> String -- | Locale representing American usage. -- -- knownTimeZones contains only the ten time-zones mentioned in -- RFC 802 sec. 5: "UT", "GMT", "EST", "EDT", "CST", "CDT", "MST", "MDT", -- "PST", "PDT". Note that the parsing functions will regardless parse -- "UTC", single-letter military time-zones, and +HHMM format. defaultTimeLocale :: TimeLocale -- | A simple day and time aggregate, where the day is of the specified -- parameter, and the time is a TimeOfDay. Conversion of this (as local -- civil time) to UTC depends on the time zone. Conversion of this (as -- local mean time) to UT1 depends on the longitude. data LocalTime LocalTime :: Day -> TimeOfDay -> LocalTime [localDay] :: LocalTime -> Day [localTimeOfDay] :: LocalTime -> TimeOfDay -- | Get the local time of a UTC time in a time zone. utcToLocalTime :: TimeZone -> UTCTime -> LocalTime -- | Get the local time of a UT1 time on a particular meridian (in degrees, -- positive is East). ut1ToLocalTime :: Rational -> UniversalTime -> LocalTime -- | Get the UTC time of a local time in a time zone. localTimeToUTC :: TimeZone -> LocalTime -> UTCTime -- | Get the UT1 time of a local time on a particular meridian (in degrees, -- positive is East). localTimeToUT1 :: Rational -> LocalTime -> UniversalTime -- | diffLocalTime a b = a - b diffLocalTime :: LocalTime -> LocalTime -> NominalDiffTime -- | addLocalTime a b = a + b addLocalTime :: NominalDiffTime -> LocalTime -> LocalTime -- | Time of day as represented in hour, minute and second (with -- picoseconds), typically used to express local time of day. data TimeOfDay TimeOfDay :: Int -> Int -> Pico -> TimeOfDay -- | range 0 - 23 [todHour] :: TimeOfDay -> Int -- | range 0 - 59 [todMin] :: TimeOfDay -> Int -- | Note that 0 <= todSec < 61, accomodating leap seconds. -- Any local minute may have a leap second, since leap seconds happen in -- all zones simultaneously [todSec] :: TimeOfDay -> Pico -- | Convert a time of day in UTC to a time of day in some timezone, -- together with a day adjustment. utcToLocalTimeOfDay :: TimeZone -> TimeOfDay -> (Integer, TimeOfDay) -- | Get the time of day given a time since midnight. Time more than 24h -- will be converted to leap-seconds. timeToTimeOfDay :: DiffTime -> TimeOfDay -- | Convert a period of time into a count of days and a time of day since -- midnight. The time of day will never have a leap second. timeToDaysAndTimeOfDay :: NominalDiffTime -> (Integer, TimeOfDay) -- | Get the time since midnight for a given time of day. timeOfDayToTime :: TimeOfDay -> DiffTime -- | Get the fraction of a day since midnight given a time of day. timeOfDayToDayFraction :: TimeOfDay -> Rational -- | Same as timeOfDayToTime. sinceMidnight :: TimeOfDay -> DiffTime -- | Same as timeToTimeOfDay. pastMidnight :: DiffTime -> TimeOfDay -- | Hour zero midnight :: TimeOfDay -- | Hour twelve midday :: TimeOfDay makeTimeOfDayValid :: Int -> Int -> Pico -> Maybe TimeOfDay -- | Convert a time of day in some timezone to a time of day in UTC, -- together with a day adjustment. localToUTCTimeOfDay :: TimeZone -> TimeOfDay -> (Integer, TimeOfDay) -- | Convert a count of days and a time of day since midnight into a period -- of time. daysAndTimeOfDayToTime :: Integer -> TimeOfDay -> NominalDiffTime -- | Get the time of day given the fraction of a day since midnight. dayFractionToTimeOfDay :: Rational -> TimeOfDay -- | A TimeZone is a whole number of minutes offset from UTC, together with -- a name and a "just for summer" flag. data TimeZone TimeZone :: Int -> Bool -> String -> TimeZone -- | The number of minutes offset from UTC. Positive means local time will -- be later in the day than UTC. [timeZoneMinutes] :: TimeZone -> Int -- | Is this time zone just persisting for the summer? [timeZoneSummerOnly] :: TimeZone -> Bool -- | The name of the zone, typically a three- or four-letter acronym. [timeZoneName] :: TimeZone -> String -- | The UTC time zone. utc :: TimeZone -- | Text representing the offset of this timezone, such as "-0800" or -- "+0400" (like %z in formatTime), with arbitrary padding. timeZoneOffsetString' :: Maybe Char -> TimeZone -> String -- | Text representing the offset of this timezone, such as "-0800" or -- "+0400" (like %z in formatTime). timeZoneOffsetString :: TimeZone -> String -- | Create a nameless non-summer timezone for this number of minutes. minutesToTimeZone :: Int -> TimeZone -- | Create a nameless non-summer timezone for this number of hours. hoursToTimeZone :: Int -> TimeZone -- | Get the local time-zone for a given time (varying as per summertime -- adjustments). getTimeZone :: UTCTime -> IO TimeZone -- | Get the current time-zone. getCurrentTimeZone :: IO TimeZone data CalendarDiffTime CalendarDiffTime :: Integer -> NominalDiffTime -> CalendarDiffTime [ctMonths] :: CalendarDiffTime -> Integer [ctTime] :: CalendarDiffTime -> NominalDiffTime -- | Scale by a factor. Note that scaleCalendarDiffTime (-1) will -- not perfectly invert a duration, due to variable month lengths. scaleCalendarDiffTime :: Integer -> CalendarDiffTime -> CalendarDiffTime calendarTimeTime :: NominalDiffTime -> CalendarDiffTime calendarTimeDays :: CalendarDiffDays -> CalendarDiffTime -- | diffUTCTime a b = a - b diffUTCTime :: UTCTime -> UTCTime -> NominalDiffTime -- | addUTCTime a b = a + b addUTCTime :: NominalDiffTime -> UTCTime -> UTCTime utcTimeToPOSIXSeconds :: UTCTime -> POSIXTime systemToPOSIXTime :: SystemTime -> POSIXTime posixSecondsToUTCTime :: POSIXTime -> UTCTime -- | Get the current POSIX time from the system clock. getPOSIXTime :: IO POSIXTime -- | Get the current UTCTime from the system clock. getCurrentTime :: IO UTCTime -- | Convert UTCTime to SystemTime, matching zero -- SystemTime to midnight of systemEpochDay UTC. utcToSystemTime :: UTCTime -> SystemTime -- | Map leap-second values to the start of the following second. The -- resulting systemNanoseconds will always be in the range 0 to -- 1E9-1. truncateSystemTimeLeapSecond :: SystemTime -> SystemTime -- | Convert SystemTime to UTCTime, matching zero -- SystemTime to midnight of systemEpochDay UTC. systemToUTCTime :: SystemTime -> UTCTime -- | Convert SystemTime to AbsoluteTime, matching zero -- SystemTime to midnight of systemEpochDay TAI. systemToTAITime :: SystemTime -> AbsoluteTime -- | The day of the epoch of SystemTime, 1970-01-01 systemEpochDay :: Day -- | The Modified Julian Date is the day with the fraction of the day, -- measured from UT midnight. It's used to represent UT1, which is time -- as measured by the earth's rotation, adjusted for various wobbles. newtype UniversalTime ModJulianDate :: Rational -> UniversalTime [getModJulianDate] :: UniversalTime -> Rational -- | This is the simplest representation of UTC. It consists of the day -- number, and a time offset from midnight. Note that if a day has a leap -- second added to it, it will have 86401 seconds. data UTCTime UTCTime :: Day -> DiffTime -> UTCTime -- | the day [utctDay] :: UTCTime -> Day -- | the time from midnight, 0 <= t < 86401s (because of -- leap-seconds) [utctDayTime] :: UTCTime -> DiffTime -- | SystemTime is time returned by system clock functions. Its -- semantics depends on the clock function, but the epoch is typically -- the beginning of 1970. Note that systemNanoseconds of 1E9 to -- 2E9-1 can be used to represent leap seconds. data SystemTime MkSystemTime :: {-# UNPACK #-} !Int64 -> {-# UNPACK #-} !Word32 -> SystemTime [systemSeconds] :: SystemTime -> {-# UNPACK #-} !Int64 [systemNanoseconds] :: SystemTime -> {-# UNPACK #-} !Word32 -- | The resolution of getSystemTime, getCurrentTime, -- getPOSIXTime. On UNIX systems this uses -- clock_getres, which may be wrong on WSL2. getTime_resolution :: DiffTime -- | Get the system time, epoch start of 1970 UTC, leap-seconds ignored. -- getSystemTime is typically much faster than -- getCurrentTime. getSystemTime :: IO SystemTime -- | POSIX time is the nominal time since 1970-01-01 00:00 UTC -- -- To convert from a CTime or System.Posix.EpochTime, use -- realToFrac. type POSIXTime = NominalDiffTime -- | 86400 nominal seconds in every day posixDayLength :: NominalDiffTime -- | This is a length of time, as measured by UTC. It has a precision of -- 10^-12 s. -- -- Conversion functions such as fromInteger and realToFrac -- will treat it as seconds. For example, (0.010 :: -- NominalDiffTime) corresponds to 10 milliseconds. -- -- It has a precision of one picosecond (= 10^-12 s). Enumeration -- functions will treat it as picoseconds. -- -- It ignores leap-seconds, so it's not necessarily a fixed amount of -- clock time. For instance, 23:00 UTC + 2 hours of NominalDiffTime = -- 01:00 UTC (+ 1 day), regardless of whether a leap-second intervened. data NominalDiffTime -- | Create a NominalDiffTime from a number of seconds. secondsToNominalDiffTime :: Pico -> NominalDiffTime -- | Get the seconds in a NominalDiffTime. nominalDiffTimeToSeconds :: NominalDiffTime -> Pico -- | One day in NominalDiffTime. nominalDay :: NominalDiffTime -- | This is a length of time, as measured by a clock. Conversion functions -- such as fromInteger and realToFrac will treat it as -- seconds. For example, (0.010 :: DiffTime) corresponds to 10 -- milliseconds. -- -- It has a precision of one picosecond (= 10^-12 s). Enumeration -- functions will treat it as picoseconds. data DiffTime -- | Create a DiffTime which represents an integral number of -- seconds. secondsToDiffTime :: Integer -> DiffTime -- | Create a DiffTime from a number of picoseconds. picosecondsToDiffTime :: Integer -> DiffTime -- | Get the number of picoseconds in a DiffTime. diffTimeToPicoseconds :: DiffTime -> Integer data DayOfWeek Monday :: DayOfWeek Tuesday :: DayOfWeek Wednesday :: DayOfWeek Thursday :: DayOfWeek Friday :: DayOfWeek Saturday :: DayOfWeek Sunday :: DayOfWeek -- | The first day-of-week on or after some day firstDayOfWeekOnAfter :: DayOfWeek -> Day -> Day -- | dayOfWeekDiff a b = a - b in range 0 to 6. The number of days -- from b to the next a. dayOfWeekDiff :: DayOfWeek -> DayOfWeek -> Int dayOfWeek :: Day -> DayOfWeek -- | Convert to proleptic Gregorian calendar. toGregorian :: Day -> (Year, MonthOfYear, DayOfMonth) -- | Show in ISO 8601 format (yyyy-mm-dd) showGregorian :: Day -> String -- | The number of days in a given month according to the proleptic -- Gregorian calendar. gregorianMonthLength :: Year -> MonthOfYear -> DayOfMonth -- | Convert from proleptic Gregorian calendar. Invalid values will return -- Nothing fromGregorianValid :: Year -> MonthOfYear -> DayOfMonth -> Maybe Day -- | Convert from proleptic Gregorian calendar. Invalid values will be -- clipped to the correct range, month first, then day. fromGregorian :: Year -> MonthOfYear -> DayOfMonth -> Day -- | Calendrical difference, with as many whole months as possible. Same as -- diffGregorianDurationClip for positive durations. diffGregorianDurationRollOver :: Day -> Day -> CalendarDiffDays -- | Calendrical difference, with as many whole months as possible diffGregorianDurationClip :: Day -> Day -> CalendarDiffDays -- | Add years, matching month and day, with Feb 29th rolled over to Mar -- 1st if necessary. For instance, 2004-02-29 + 2 years = 2006-03-01. addGregorianYearsRollOver :: Integer -> Day -> Day -- | Add years, matching month and day, with Feb 29th clipped to Feb 28th -- if necessary. For instance, 2004-02-29 + 2 years = 2006-02-28. addGregorianYearsClip :: Integer -> Day -> Day -- | Add months, with days past the last day of the month rolling over to -- the next month. For instance, 2005-01-30 + 1 month = 2005-03-02. addGregorianMonthsRollOver :: Integer -> Day -> Day -- | Add months, with days past the last day of the month clipped to the -- last day. For instance, 2005-01-30 + 1 month = 2005-02-28. addGregorianMonthsClip :: Integer -> Day -> Day -- | Add months (rolling over to next month), then add days addGregorianDurationRollOver :: CalendarDiffDays -> Day -> Day -- | Add months (clipped to last day), then add days addGregorianDurationClip :: CalendarDiffDays -> Day -> Day -- | Bidirectional abstract constructor for the proleptic Gregorian -- calendar. Invalid values will be clipped to the correct range, month -- first, then day. pattern YearMonthDay :: Year -> MonthOfYear -> DayOfMonth -> Day -- | Is this year a leap year according to the proleptic Gregorian -- calendar? isLeapYear :: Year -> Bool -- | Year of Common Era. type Year = Integer -- | Month of year, in range 1 (January) to 12 (December). type MonthOfYear = Int -- | Day of month, in range 1 to 31. type DayOfMonth = Int -- | The Modified Julian Day is a standard count of days, with zero being -- the day 1858-11-17. newtype Day ModifiedJulianDay :: Integer -> Day [toModifiedJulianDay] :: Day -> Integer diffDays :: Day -> Day -> Integer addDays :: Integer -> Day -> Day data CalendarDiffDays CalendarDiffDays :: Integer -> Integer -> CalendarDiffDays [cdMonths] :: CalendarDiffDays -> Integer [cdDays] :: CalendarDiffDays -> Integer -- | Scale by a factor. Note that scaleCalendarDiffDays (-1) will -- not perfectly invert a duration, due to variable month lengths. scaleCalendarDiffDays :: Integer -> CalendarDiffDays -> CalendarDiffDays calendarYear :: CalendarDiffDays calendarWeek :: CalendarDiffDays calendarMonth :: CalendarDiffDays calendarDay :: CalendarDiffDays -- | Convert a MaybeT computation to ExceptT, with a default -- exception value. maybeToExceptT :: forall (m :: Type -> Type) e a. Functor m => e -> MaybeT m a -> ExceptT e m a -- | Transform the computation inside a MaybeT. -- -- mapMaybeT :: (m (Maybe a) -> n (Maybe b)) -> MaybeT m a -> MaybeT n b -- | Convert a ExceptT computation to MaybeT, discarding the -- value of any exception. exceptToMaybeT :: forall (m :: Type -> Type) e a. Functor m => ExceptT e m a -> MaybeT m a -- | Constructor for computations in the exception monad. (The inverse of -- runExcept). except :: forall (m :: Type -> Type) e a. Monad m => Either e a -> ExceptT e m a -- | shiftT f captures the continuation up to the nearest -- enclosing resetT and passes it to f: -- -- shiftT :: Monad m => ((a -> m r) -> ContT r m r) -> ContT r m a -- | resetT m delimits the continuation of any -- shiftT inside m. -- -- resetT :: forall (m :: Type -> Type) r r'. Monad m => ContT r m r -> ContT r' m r -- | reset m delimits the continuation of any shift -- inside m. -- -- reset :: Cont r r -> Cont r' r -- | liftLocal ask local yields a local function -- for ContT r m. liftLocal :: Monad m => m r' -> ((r' -> r') -> m r -> m r) -> (r' -> r') -> ContT r m a -> ContT r m a -- | The result of running a CPS computation with return as the -- final continuation. -- -- evalContT :: Monad m => ContT r m r -> m r -- | The result of running a CPS computation with the identity as the final -- continuation. -- -- evalCont :: Cont r r -> r -- | A set of values. A set cannot contain duplicate values. data HashSet a -- | A map from keys to values. A map cannot contain duplicate keys; each -- key can map to at most one value. data HashMap k v -- | Type representing Universally Unique Identifiers (UUID) as -- specified in RFC 4122. data UUID -- | Boxed vectors, supporting efficient slicing. data Vector a -- | If Void is uninhabited then any Monad that holds values -- of type Void is holding no values. -- -- This is only safe for valid monads that do not perform GADT-like -- analysis on the argument. unsafeVacuousM :: Monad m => m Void -> m a -- | If Void is uninhabited than any Functor that holds only -- values of the type Void is holding no values. -- -- This is only safe for valid functors that do not perform GADT-like -- analysis on the argument. unsafeVacuous :: Functor f => f Void -> f a -- | A more meaningful and conflict-free alias for first. mapLeft :: Bifunctor p => (a -> b) -> p a c -> p b c -- | A more meaningful and conflict-free alias for second. mapRight :: Bifunctor p => (b -> c) -> p a b -> p a c -- | If you're not a fan of magical or special cases, you probably have -- already been looking for this alias. type List = [] -- | A more meaningful name for the non-empty list. Follows the convention -- behind such names as foldr1. type List1 = NonEmpty sappend :: Semigroup a => a -> a -> a