-- 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: -- --
-- [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 :: () => a -> b -> b -- | filter, applied to a predicate and a list, returns the list of -- those elements that satisfy the predicate; i.e., -- --
-- filter p xs = [ x | x <- xs, p x] --filter :: () => (a -> Bool) -> [a] -> [a] -- | 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 short, excess elements of the longer list are -- discarded: -- --
-- zip [1] ['a', 'b'] = [(1, 'a')] -- zip [1, 2] ['a'] = [(1, 'a')] ---- -- zip is right-lazy: -- --
-- zip [] _|_ = [] -- zip _|_ [] = _|_ --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. -- -- Like seq, the argument of lazy can have an unboxed type. 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 but first outputs -- the message. -- --
-- >>> 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
-- | map f xs is the list obtained by applying f
-- to each element of xs, i.e.,
--
-- -- map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn] -- map f [x1, x2, ...] == [f x1, f x2, ...] --map :: () => (a -> b) -> [a] -> [b] -- | 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 ($) :: () => (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. coerce :: 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 ---- --
-- >>> 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 () -- | 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 -- | 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. -- --
-- 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 4 :: [Integer] = [4,5,6,7,...]
enumFrom 6 :: [Int] = [6,7,8,9,...,maxBound :: -- Int]
enumFromThen 4 6 :: [Integer] = [4,6,8,10...]
enumFromThen 6 2 :: [Int] = [6,2,-2,-6,...,minBound :: -- Int]
enumFromTo 6 10 :: [Int] = [6,7,8,9,10]
enumFromTo 42 1 :: [Integer] = []
enumFromThenTo 4 2 -6 :: [Integer] = -- [4,2,0,-2,-4,-6]
enumFromThenTo 6 8 2 :: [Int] = []
-- (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 `quot` infixl 7 `rem` infixl 7 `div` infixl 7 `mod` -- | The Monad class defines the basic operations over a -- monad, a concept from a branch of mathematics known as -- category theory. From the perspective of a Haskell programmer, -- however, it is best to think of a monad as an abstract datatype -- of actions. Haskell's do expressions provide a convenient -- syntax for writing monadic expressions. -- -- Instances of Monad should satisfy the following laws: -- -- -- -- Furthermore, the Monad and Applicative operations should -- relate as follows: -- -- -- -- The above laws imply: -- -- -- -- and that pure and (<*>) satisfy the applicative -- functor laws. -- -- The instances of Monad for lists, Maybe and IO -- defined in the Prelude satisfy these laws. class Applicative m => Monad (m :: Type -> Type) -- | Sequentially compose two actions, passing any value produced by the -- first as an argument to the second. (>>=) :: Monad m => m a -> (a -> m b) -> m b -- | Sequentially compose two actions, discarding any value produced by the -- first, like sequencing operators (such as the semicolon) in imperative -- languages. (>>) :: Monad m => m a -> m b -> m b -- | Inject a value into the monadic type. return :: Monad m => a -> m a 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 withing 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 :: 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 -- | The Functor class is used for types that can be mapped over. -- Instances of Functor should satisfy the following laws: -- --
-- fmap id == id -- fmap (f . g) == fmap f . fmap g ---- -- The instances of Functor for lists, Maybe and IO -- satisfy these laws. class Functor (f :: Type -> Type) 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: -- --
-- 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 6 + infixl 7 * 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. -- -- The Haskell Report defines no laws for Ord. However, -- <= is customarily expected to implement a non-strict partial -- order and have the following properties: -- --
-- 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: -- --
-- 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, -- --
-- 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: -- --
-- 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 -- --
-- (<*>) = liftA2 id ---- --
-- liftA2 f x y = f <$> x <*> y ---- -- Further, any definition must satisfy the following: -- --
pure id <*> -- v = v
pure (.) <*> u -- <*> v <*> w = u <*> (v -- <*> w)
pure f <*> -- pure x = pure (f x)
u <*> pure y = -- pure ($ y) <*> u
-- forall x y. p (q x y) = f x . g y ---- -- it follows from the above that -- --
-- liftA2 p (liftA2 q u v) = liftA2 f u . liftA2 g v ---- -- If f is also a Monad, it should satisfy -- -- -- -- (which implies that pure and <*> satisfy the -- applicative functor laws). class Functor f => Applicative (f :: 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. (<*>) :: 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 <*>. liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c -- | Sequence actions, discarding the value of the first argument. (*>) :: 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 <* -- | Data structures that can be folded. -- -- For example, given a data type -- --
-- data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a) ---- -- a suitable instance would be -- --
-- instance Foldable Tree where -- foldMap f Empty = mempty -- foldMap f (Leaf x) = f x -- foldMap f (Node l k r) = foldMap f l `mappend` f k `mappend` foldMap f r ---- -- This is suitable even for abstract types, as the monoid is assumed to -- satisfy the monoid laws. Alternatively, one could define -- foldr: -- --
-- instance Foldable Tree where -- foldr f z Empty = z -- foldr f z (Leaf x) = f x z -- foldr f z (Node l k r) = foldr f (f k (foldr f z r)) l ---- -- Foldable instances are expected to satisfy the following -- laws: -- --
-- foldr f z t = appEndo (foldMap (Endo . f) t ) z ---- --
-- foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z ---- --
-- fold = foldMap id ---- --
-- length = getSum . foldMap (Sum . const 1) ---- -- sum, product, maximum, and minimum -- should all be essentially equivalent to foldMap forms, such -- as -- --
-- sum = getSum . foldMap Sum ---- -- but may be less defined. -- -- If the type is also a Functor instance, it should satisfy -- --
-- foldMap f = fold . fmap f ---- -- which implies that -- --
-- foldMap f . fmap g = foldMap (f . g) --class Foldable (t :: Type -> Type) -- | Combine the elements of a structure using a monoid. fold :: (Foldable t, Monoid m) => t m -> m -- | Map each element of the structure to a monoid, and combine the -- results. foldMap :: (Foldable t, Monoid m) => (a -> m) -> t a -> m -- | Right-associative fold of a structure. -- -- In the case of lists, foldr, when applied to a binary operator, -- a starting value (typically the right-identity of the operator), and a -- list, reduces the list using the binary operator, from right to left: -- --
-- foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...) ---- -- Note that, since the head of the resulting expression is produced by -- an application of the operator to the first element of the list, -- foldr can produce a terminating expression from an infinite -- list. -- -- For a general Foldable structure this should be semantically -- identical to, -- --
-- foldr f z = foldr f z . toList --foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b -- | Right-associative fold of a structure, but with strict application of -- the operator. foldr' :: Foldable t => (a -> b -> b) -> b -> t a -> b -- | Left-associative fold of a structure. -- -- In the case of lists, foldl, when applied to a binary operator, -- a starting value (typically the left-identity of the operator), and a -- list, reduces the list using the binary operator, from left to right: -- --
-- foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn ---- -- Note that to produce the outermost application of the operator the -- entire input list must be traversed. This means that foldl' -- will diverge if given an infinite list. -- -- Also note that if you want an efficient left-fold, you probably want -- to use foldl' instead of foldl. The reason for this is -- that latter does not force the "inner" results (e.g. z f -- x1 in the above example) before applying them to the operator -- (e.g. to (f x2)). This results in a thunk chain -- O(n) elements long, which then must be evaluated from the -- outside-in. -- -- For a general Foldable structure this should be semantically -- identical to, -- --
-- foldl f z = foldl f z . toList --foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b -- | 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 list to a single, monolithic result (e.g. length). -- -- 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. -- --
-- foldr1 f = foldr1 f . toList --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. -- --
-- foldl1 f = foldl1 f . toList --foldl1 :: Foldable t => (a -> a -> a) -> t a -> a -- | List of elements of a structure, from left to right. toList :: Foldable t => t a -> [a] -- | Test whether the structure is empty. The default implementation is -- optimized for structures that are similar to cons-lists, because there -- is no general way to do better. null :: Foldable t => t a -> Bool -- | Returns the size/length of a finite structure as an Int. The -- default implementation is optimized for structures that are similar to -- cons-lists, because there is no general way to do better. length :: Foldable t => t a -> Int -- | Does the element occur in the structure? elem :: (Foldable t, Eq a) => a -> t a -> Bool -- | The largest element of a non-empty structure. maximum :: (Foldable t, Ord a) => t a -> a -- | The least element of a non-empty structure. minimum :: (Foldable t, Ord a) => t a -> a -- | The sum function computes the sum of the numbers of a -- structure. sum :: (Foldable t, Num a) => t a -> a -- | The product function computes the product of the numbers of a -- structure. product :: (Foldable t, Num a) => t a -> a infix 4 `elem` -- | Functors representing data structures that can be traversed from left -- to right. -- -- A definition of traverse must satisfy the following laws: -- --
-- t :: (Applicative f, Applicative g) => f a -> g a ---- -- preserving the Applicative operations, i.e. -- -- -- -- and the identity functor Identity and composition of functors -- Compose are defined as -- --
-- newtype Identity a = Identity a -- -- instance Functor Identity where -- fmap f (Identity x) = Identity (f x) -- -- instance Applicative Identity where -- pure x = Identity x -- Identity f <*> Identity x = Identity (f x) -- -- newtype Compose f g a = Compose (f (g a)) -- -- instance (Functor f, Functor g) => Functor (Compose f g) where -- fmap f (Compose x) = Compose (fmap (fmap f) x) -- -- instance (Applicative f, Applicative g) => Applicative (Compose f g) where -- pure x = Compose (pure (pure x)) -- Compose f <*> Compose x = Compose ((<*>) <$> f <*> x) ---- -- (The naturality law is implied by parametricity.) -- -- Instances are similar to Functor, e.g. given a data type -- --
-- data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a) ---- -- a suitable instance would be -- --
-- instance Traversable Tree where -- traverse f Empty = pure Empty -- traverse f (Leaf x) = Leaf <$> f x -- traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r ---- -- This is suitable even for abstract types, as the laws for -- <*> imply a form of associativity. -- -- The superclass instances should satisfy the following: -- --
-- from . to ≡ id -- to . from ≡ id --class Generic a -- | The class of semigroups (types with an associative binary operation). -- -- Instances should satisfy the associativity law: -- -- class Semigroup a -- | An associative operation. (<>) :: Semigroup a => a -> a -> a -- | Reduce a non-empty list with <> -- -- The default definition should be sufficient, but this can be -- overridden for efficiency. sconcat :: Semigroup a => NonEmpty a -> a -- | Repeat a value n times. -- -- Given that this works on a Semigroup it is allowed to fail if -- you request 0 or fewer repetitions, and the default definition will do -- so. -- -- By making this a member of the class, idempotent semigroups and -- monoids can upgrade this to execute in O(1) by picking -- stimes = stimesIdempotent or stimes = -- stimesIdempotentMonoid respectively. stimes :: (Semigroup a, Integral b) => b -> a -> a infixr 6 <> -- | The class of monoids (types with an associative binary operation that -- has an identity). Instances should satisfy the following laws: -- --
x <> mempty = x
mempty <> x = x
mconcat = foldr '(<>)' -- mempty
-- >>> 2^100 :: Natural -- 1267650600228229401496703205376 ---- -- Operations whose result would be negative throw -- (Underflow :: ArithException), -- --
-- >>> -1 :: Natural -- *** Exception: arithmetic underflow --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 :: Type -- | 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 -- --
-- 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"). -- --
-- >>> 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 -- | 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 :: k0) (b :: k0) data TyCon -- | 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: -- --
-- runST (writeSTRef _|_ v >>= f) = _|_ --data ST s a untangle :: Addr# -> String -> String ioException :: () => IOException -> IO a heapOverflow :: SomeException stackOverflow :: SomeException cannotCompactMutable :: SomeException cannotCompactPinned :: SomeException cannotCompactFunction :: SomeException allocationLimitExceeded :: SomeException blockedIndefinitelyOnSTM :: SomeException blockedIndefinitelyOnMVar :: SomeException unsupportedOperation :: IOError -- | 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 -- | The nonnegative magnitude of a complex number. magnitude :: RealFloat a => 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) -- | cis t is a complex value with magnitude 1 and -- phase t (modulo 2*pi). cis :: Floating a => a -> Complex a -- | Form a complex number from polar components of magnitude and phase. mkPolar :: Floating a => a -> a -> Complex a -- | The conjugate of a complex number. conjugate :: Num a => Complex a -> Complex a -- | Extracts the imaginary part of a complex number. imagPart :: () => Complex a -> a -- | Extracts the real part of a complex number. realPart :: () => Complex a -> a -- | 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 :+ -- | First arg is whether to chop off trailing zeros showFixed :: 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 -- | The type parameter should be an instance of HasResolution. newtype Fixed a MkFixed :: Integer -> Fixed a class HasResolution a resolution :: HasResolution a => p a -> Integer data E0 -- | resolution of 1, this works the same as Integer type Uni = Fixed E0 data E1 -- | resolution of 10^-1 = .1 type Deci = Fixed E1 data E2 -- | resolution of 10^-2 = .01, useful for many monetary currencies type Centi = Fixed E2 data E3 -- | resolution of 10^-3 = .001 type Milli = Fixed E3 data E6 -- | resolution of 10^-6 = .000001 type Micro = Fixed E6 data E9 -- | resolution of 10^-9 = .000000001 type Nano = Fixed E9 data E12 -- | resolution of 10^-12 = .000000000001 type Pico = Fixed E12 comparisonEquivalence :: () => Comparison a -> Equivalence a -- | 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 -- | This is an infix version of contramap with the arguments -- flipped. (>$$<) :: Contravariant f => f b -> (a -> b) -> f a infixl 4 >$$< -- | This is an infix alias for contramap. (>$<) :: Contravariant f => (a -> b) -> f b -> f a infixl 4 >$< -- | This is >$ with its arguments flipped. ($<) :: Contravariant f => f b -> b -> f a infixl 4 $< -- | 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 -- | 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 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:
--
-- -- contramap id = id -- contramap f . contramap g = contramap (g . f) ---- -- 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 -> b) -> f b -> 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 >$ newtype Predicate a Predicate :: (a -> Bool) -> Predicate a [getPredicate] :: Predicate 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 -- | This data type represents an equivalence relation. -- -- Equivalence relations are expected to satisfy three laws: -- -- Reflexivity: -- --
-- getEquivalence f a a = True ---- -- Symmetry: -- --
-- getEquivalence f a b = getEquivalence f b a ---- -- Transitivity: -- -- If getEquivalence f a b and getEquivalence -- f b c are both True then so is getEquivalence f -- a c. -- -- 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 -- | Dual function arrows. newtype Op a b Op :: (b -> a) -> Op a b [getOp] :: Op a b -> b -> a -- | 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) :: forall k k1. () => k -> Type -> k1 -> k -> k1 -> Type Compose :: f (g a) -> Compose [getCompose] :: Compose -> f (g a) infixr 9 `Compose` infixr 9 `Compose` -- | If Void is uninhabited then any Functor that holds only -- values of type Void is holding no values. 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
-- | Uninhabited data type
data Void
-- | Fold an Option case-wise, just like maybe.
option :: () => b -> (a -> b) -> Option 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. 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 newtype Min a Min :: a -> Min a [getMin] :: Min a -> a newtype Max a Max :: a -> Max a [getMax] :: Max a -> a -- | Arg isn't itself a Semigroup in its own right, but it -- can be placed inside Min and Max to compute an arg min -- or arg max. data Arg a b Arg :: a -> b -> Arg a b type ArgMin a b = Min Arg a b type ArgMax a b = Max Arg a b -- | Use Option (First a) to get the behavior of -- First from Data.Monoid. newtype First a First :: a -> First a [getFirst] :: First a -> a -- | Use Option (Last a) to get the behavior of -- Last from Data.Monoid newtype Last a Last :: a -> Last a [getLast] :: Last a -> a -- | Provide a Semigroup for an arbitrary Monoid. -- -- NOTE: This is not needed anymore since Semigroup became -- a superclass of Monoid in base-4.11 and this newtype be -- deprecated at some point in the future. newtype WrappedMonoid m WrapMonoid :: m -> WrappedMonoid m [unwrapMonoid] :: WrappedMonoid m -> m -- | Option is effectively Maybe with a better instance of -- Monoid, built off of an underlying Semigroup instead of -- an underlying Monoid. -- -- Ideally, this type would not exist at all and we would just fix the -- Monoid instance of Maybe. -- -- In GHC 8.4 and higher, the Monoid instance for Maybe has -- been corrected to lift a Semigroup instance instead of a -- Monoid instance. Consequently, this type is no longer useful. -- It will be marked deprecated in GHC 8.8 and removed in GHC 8.10. newtype Option a Option :: Maybe a -> Option a [getOption] :: Option a -> Maybe a -- | 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] -- | Gets the module of a type constructor: take *.*.*... before name tyconModule :: String -> String -- | Gets the unqualified type constructor: drop *.*.*... before name tyconUQname :: String -> String -- | Test for a non-representable type isNorepType :: DataType -> Bool -- | Constructs a non-representation for a non-representable type mkNoRepType :: String -> DataType -- | Makes a constructor for Char. mkCharConstr :: DataType -> Char -> Constr mkRealConstr :: (Real a, Show a) => DataType -> a -> Constr mkIntegralConstr :: (Integral a, Show a) => DataType -> a -> Constr -- | Constructs the Char type mkCharType :: String -> DataType -- | Constructs the Float type mkFloatType :: String -> DataType -- | Constructs the Int type mkIntType :: String -> DataType -- | Gets the maximum constructor index of an algebraic datatype maxConstrIndex :: DataType -> ConIndex -- | Gets the index of a constructor (algebraic datatypes only) constrIndex :: Constr -> ConIndex -- | Gets the constructor for an index (algebraic datatypes only) indexConstr :: DataType -> ConIndex -> Constr -- | Test for an algebraic type isAlgType :: DataType -> Bool -- | Lookup a constructor via a string readConstr :: DataType -> String -> Maybe Constr -- | Gets the string for a constructor showConstr :: Constr -> String -- | 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] -- | Gets the constructors of an algebraic datatype dataTypeConstrs :: DataType -> [Constr] -- | Constructs a constructor mkConstr :: DataType -> String -> [String] -> Fixity -> Constr -- | Constructs an algebraic datatype mkDataType :: String -> [Constr] -> DataType -- | Look up a constructor by its representation repConstr :: DataType -> ConstrRep -> Constr -- | Gets the public presentation of constructors constrRep :: Constr -> ConstrRep -- | Gets the datatype of a constructor constrType :: Constr -> DataType -- | Gets the public presentation of a datatype dataTypeRep :: DataType -> DataRep -- | Gets the type constructor including the module dataTypeName :: DataType -> String -- | 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 -- | Representation of datatypes. A package of constructor representations -- with names of type and module. data DataType -- | 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 -- | 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 -- | Unique index for datatype constructors, counting from 1 in the order -- they are given in the program text. type ConIndex = Int -- | Fixity of constructors data Fixity Prefix :: Fixity Infix :: Fixity -- | 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. 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 ()) -- | 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 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 () -- | 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 -- | 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 -- | True if bound threads are supported. If -- rtsSupportsBoundThreads is False, -- isCurrentThreadBound will always return False and both -- forkOS and runInBoundThread will fail. rtsSupportsBoundThreads :: Bool -- | Write an entire list of items to a Chan. writeList2Chan :: () => Chan a -> [a] -> IO () -- | 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) -- | 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 -- | Write a value to a Chan. writeChan :: () => Chan a -> a -> IO () -- | Build and returns a new instance of Chan. newChan :: () => IO (Chan a) -- | Chan is an abstract type representing an unbounded FIFO -- channel. data Chan a -- | Signal that a unit of the QSem is available signalQSem :: QSem -> IO () -- | Wait for a unit to become available waitQSem :: QSem -> IO () -- | Build a new QSem with a supplied initial quantity. The initial -- quantity must be at least 0. newQSem :: Int -> IO QSem -- | 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 -- | Signal that a given quantity is now available from the QSemN. signalQSemN :: QSemN -> Int -> IO () -- | Wait for the specified quantity to become available waitQSemN :: QSemN -> Int -> IO () -- | Build a new QSemN with a supplied initial quantity. The initial -- quantity must be at least 0. newQSemN :: Int -> IO QSemN -- | 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 -- | 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 id ≡ id ---- -- If you supply first and second, ensure: -- --
-- first id ≡ id -- second id ≡ id ---- -- 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 ---- --
-- >>> 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 ---- --
-- >>> 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. -- --
-- second ≡ bimap id ---- --
-- >>> second (+1) ('j', 3)
-- ('j',4)
--
--
-- -- >>> second (+1) (Right 3) -- Right 4 --second :: Bifunctor p => (b -> c) -> p a b -> p a c -- | 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 -- | 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 -- | 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 -- | 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 -- | 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 -- | 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 -- | 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 -- | 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 -- | 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 -- | 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 -- | 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 -- | 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 -- | Lift the standard showsPrec function through the type -- constructor. showsPrec2 :: (Show2 f, Show a, Show b) => Int -> f a b -> ShowS -- | 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 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 readPrec function through the type -- constructor. readPrec2 :: (Read2 f, Read a, Read b) => ReadPrec (f a b) -- | Lift the standard readsPrec function through the type -- constructor. readsPrec2 :: (Read2 f, Read a, Read b) => Int -> ReadS (f a b) -- | 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 (==) function through the type -- constructor. eq2 :: (Eq2 f, Eq a, Eq b) => f a b -> f a b -> Bool -- | Lift the standard showsPrec and showList functions -- through the type constructor. showsPrec1 :: (Show1 f, Show a) => Int -> f a -> ShowS -- | 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 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] -- | Lift the standard readPrec and readListPrec functions -- through the type constructor. readPrec1 :: (Read1 f, Read a) => ReadPrec (f a) -- | Lift the standard readsPrec and readList functions -- through the type constructor. readsPrec1 :: (Read1 f, Read a) => Int -> ReadS (f a) -- | Lift the standard compare function through the type -- constructor. compare1 :: (Ord1 f, Ord a) => f a -> f a -> Ordering -- | Lift the standard (==) function through the type -- constructor. eq1 :: (Eq1 f, Eq a) => f a -> f a -> 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 -- | 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 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 Show class to unary type constructors. class Show1 (f :: Type -> Type) -- | 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 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 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 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. @since 4.9.0.0 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 Show class to binary type constructors. class Show2 (f :: Type -> Type -> Type) -- | 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 -- | 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. 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 -- --
-- >>> :{
-- 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 seldomly uses the value, thunks will pile up in memory
-- resulting in a space leak. This is a common mistake made when using an
-- STRef as a counter. For example, the following will leak memory and
-- 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 ()
-- | 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
-- | 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
-- | 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
-- | Equality on StableName that does not require that the types of
-- the arguments match.
eqStableName :: () => StableName a -> StableName b -> Bool
-- | 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
-- | Makes a StableName for an arbitrary object. The object passed
-- as the first argument is not evaluated by makeStableName.
makeStableName :: () => a -> IO (StableName a)
-- | An abstract name for an object, that supports equality and hashing.
--
-- Stable names have the following property:
--
-- -- 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 getEnv var returns the value of the -- environment variable var. For the inverse, the setEnv -- function can be used. -- -- This computation may fail with: -- --
-- >>> 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: -- --
-- 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 -- | Strict version of <$>. (<$!>) :: Monad m => (a -> b) -> m a -> m b infixl 4 <$!> -- | The reverse of when. unless :: Applicative f => Bool -> f () -> f () -- | Like replicateM, but discards the result. replicateM_ :: Applicative m => Int -> m a -> m () -- | replicateM n act performs the action n times, -- gathering the results. replicateM :: Applicative m => Int -> m a -> m [a] -- | 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 -- | 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 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-transforming monad. mapAndUnzipM :: Applicative m => (a -> m (b, c)) -> [a] -> m ([b], [c]) -- | Repeat an action indefinitely. -- --
-- 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 --forever :: Applicative f => f a -> f b -- | 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 <=< -- | Left-to-right composition of Kleisli arrows. (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 >=> -- | This generalizes the list-based filter function. filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a] -- | Construct tag-less Version makeVersion :: [Int] -> Version -- | A parser for versions in the format produced by showVersion. parseVersion :: ReadP Version -- | 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 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] -- | 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 -- | 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 -- | 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 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 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 -- | Like trace but returns the message instead of a third value. -- --
-- >>> traceId "hello" -- "hello -- hello" --traceId :: String -> String putTraceMsg :: String -> IO () -- | 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 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). -- --
-- >>> 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 -- | 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 -- | 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. mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) -- | 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. mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) -- | 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) -- | One or none. optional :: Alternative f => f a -> f (Maybe a) newtype WrappedMonad (m :: Type -> Type) a WrapMonad :: m a -> WrappedMonad a [unwrapMonad] :: WrappedMonad a -> m a newtype WrappedArrow (a :: Type -> Type -> Type) b c WrapArrow :: a b c -> WrappedArrow b c [unwrapArrow] :: WrappedArrow b c -> a b c -- | Lists, but with an Applicative functor based on zipping. newtype ZipList a ZipList :: [a] -> ZipList a [getZipList] :: ZipList a -> [a] -- | 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) -- | Postcomposition with a pure function (right-to-left variant). (^<<) :: Arrow a => (c -> d) -> a b c -> 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 <<^ -- | Postcomposition with a pure function. (>>^) :: Arrow a => a b c -> (c -> d) -> a b d infixr 1 >>^ -- | Precomposition with a pure function. (^>>) :: Arrow a => (b -> c) -> a c d -> a b d infixr 1 ^>> -- | The identity arrow, which plays the role of return in arrow -- notation. returnA :: Arrow a => a b b -- | The basic arrow class. -- -- Instances should satisfy the following laws: -- --
arr id = id
arr (f >>> g) = arr f >>> -- arr g
first (arr f) = arr (first -- f)
first (f >>> g) = first f >>> -- first g
first f >>> arr fst = -- arr fst >>> f
first f >>> arr (id *** g) = -- arr (id *** g) >>> first f
first (first f) >>> arr -- assoc = arr assoc >>> first -- f
-- 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 -> Type -> 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 &&& -- | Kleisli arrows of a monad. newtype Kleisli (m :: Type -> Type) a b Kleisli :: (a -> m b) -> Kleisli a b [runKleisli] :: Kleisli a b -> a -> m b class Arrow a => ArrowZero (a :: Type -> Type -> Type) zeroArrow :: ArrowZero a => a b c -- | A monoid on arrows. class ArrowZero a => ArrowPlus (a :: Type -> Type -> Type) -- | An associative operation with identity zeroArrow. (<+>) :: ArrowPlus a => a b c -> a b c -> a b c infixr 5 <+> -- | Choice, for arrows that support it. This class underlies the -- if and case constructs in arrow notation. -- -- Instances should satisfy the following laws: -- --
left (arr f) = arr (left -- f)
left (f >>> g) = left f >>> -- left g
f >>> arr Left = arr -- Left >>> left f
left f >>> arr (id +++ g) = -- arr (id +++ g) >>> left f
left (left f) >>> arr -- assocsum = arr assocsum >>> -- left f
-- 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 -> Type -> 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: -- --
first (arr (\x -> arr (\y -> -- (x,y)))) >>> app = id
first (arr (g >>>)) >>> -- app = second g >>> app
first (arr (>>> h)) >>> -- app = app >>> h
-- assoc ((a,b),c) = (a,(b,c)) -- unassoc (a,(b,c)) = ((a,b),c) --class Arrow a => ArrowLoop (a :: Type -> Type -> Type) loop :: ArrowLoop a => a (b, d) (c, d) -> a b c -- | Identity functor and monad. (a non-strict monad) newtype Identity a Identity :: a -> Identity a [runIdentity] :: Identity a -> 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 readLn function combines getLine and readIO. readLn :: Read a => IO a -- | 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 () -- | The computation writeFile file str function writes the -- string str, to the file file. writeFile :: FilePath -> String -> IO () -- | The readFile function reads a file and returns the contents of -- the file as a string. The file is read lazily, on demand, as with -- getContents. readFile :: FilePath -> IO String -- | The interact function takes a function of type -- String->String as its argument. The entire input from the -- standard input device is passed to this function as its argument, and -- the resulting string is output on the standard output device. interact :: (String -> String) -> IO () -- | The getContents operation returns all user input as a single -- string, which is read lazily as it is needed (same as -- hGetContents stdin). getContents :: IO String -- | Read a line from the standard input device (same as hGetLine -- stdin). getLine :: IO String -- | Read a character from the standard input device (same as -- hGetChar stdin). getChar :: IO Char -- | 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 () -- | 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 :: Handle -> 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) -- | 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 () -- | 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 () ioManagerCapabilitiesChanged :: IO () ensureIOManagerIsRunning :: IO () runHandlers :: ForeignPtr Word8 -> Signal -> IO () setHandler :: Signal -> Maybe (HandlerFun, Dynamic) -> IO (Maybe (HandlerFun, Dynamic)) type Signal = CInt type HandlerFun = ForeignPtr Word8 -> IO () -- | 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 () -- | 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 -- | Like modifyMVar_, but the IO action in the second -- argument is executed with asynchronous exceptions masked. modifyMVarMasked_ :: () => MVar a -> (a -> IO a) -> IO () -- | 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 -- | 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 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 -- | 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 -- | When invoked inside mask, this function allows a masked -- asynchronous exception to be raised, if one exists. It is equivalent -- to performing an interruptible operation (see #interruptible), but -- does not involve any actual blocking. -- -- When called outside mask, or inside uninterruptibleMask, -- this function has no effect. allowInterrupt :: IO () -- | Sometimes you want to catch two different sorts of exception. You -- could do something like -- --
-- f = expr `catch` \ (ex :: ArithException) -> handleArith ex -- `catch` \ (ex :: IOException) -> handleIO ex ---- -- However, there are a couple of problems with this approach. The first -- is that having two exception handlers is inefficient. However, the -- more serious issue is that the second exception handler will catch -- exceptions in the first, e.g. in the example above, if -- handleArith throws an IOException then the second -- exception handler will catch it. -- -- Instead, we provide a function catches, which would be used -- thus: -- --
-- f = expr `catches` [Handler (\ (ex :: ArithException) -> handleArith ex), -- Handler (\ (ex :: IOException) -> handleIO ex)] --catches :: () => IO a -> [Handler a] -> IO a -- | You need this when using catches. data Handler a [Handler] :: forall a e. Exception e => (e -> IO a) -> Handler a -- | Allow the result of a state transformer computation to be used -- (lazily) inside the computation. -- -- Note that if f is strict, fixST f = _|_. fixST :: () => (a -> ST s a) -> ST s a -- | 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 -- | Catch any IOException that occurs in the computation and throw -- a modified version. modifyIOError :: () => (IOError -> IOError) -> IO a -> IO a ioeSetFileName :: IOError -> FilePath -> IOError ioeSetHandle :: IOError -> Handle -> IOError ioeSetLocation :: IOError -> String -> IOError ioeSetErrorString :: IOError -> String -> IOError ioeSetErrorType :: IOError -> IOErrorType -> IOError ioeGetFileName :: IOError -> Maybe FilePath ioeGetHandle :: IOError -> Maybe Handle ioeGetLocation :: IOError -> String ioeGetErrorString :: IOError -> String ioeGetErrorType :: IOError -> IOErrorType -- | I/O error that is programmer-defined. isUserErrorType :: IOErrorType -> Bool -- | I/O error where the operation failed because the user does not have -- sufficient operating system privilege to perform that operation. isPermissionErrorType :: IOErrorType -> Bool -- | I/O error where the operation is not possible. isIllegalOperationErrorType :: IOErrorType -> Bool -- | I/O error where the operation failed because the end of file has been -- reached. isEOFErrorType :: IOErrorType -> Bool -- | I/O error where the operation failed because the device is full. isFullErrorType :: IOErrorType -> Bool -- | I/O error where the operation failed because one of its arguments is a -- single-use resource, which is already being used. isAlreadyInUseErrorType :: IOErrorType -> Bool -- | I/O error where the operation failed because one of its arguments does -- not exist. isDoesNotExistErrorType :: IOErrorType -> Bool -- | I/O error where the operation failed because one of its arguments -- already exists. isAlreadyExistsErrorType :: IOErrorType -> Bool -- | I/O error that is programmer-defined. userErrorType :: IOErrorType -- | I/O error where the operation failed because the user does not have -- sufficient operating system privilege to perform that operation. permissionErrorType :: IOErrorType -- | I/O error where the operation is not possible. illegalOperationErrorType :: 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 the device is full. fullErrorType :: IOErrorType -- | I/O error where the operation failed because one of its arguments is a -- single-use resource, which is already being used. alreadyInUseErrorType :: IOErrorType -- | I/O error where the operation failed because one of its arguments does -- not exist. doesNotExistErrorType :: IOErrorType -- | I/O error where the operation failed because one of its arguments -- already exists. alreadyExistsErrorType :: IOErrorType -- | A programmer-defined error value constructed using userError. isUserError :: IOError -> 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 -- | 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 -- | An error indicating that an IO operation failed because the end -- of file has been reached. isEOFError :: IOError -> Bool -- | An error indicating that an IO operation failed because the -- device is full. isFullError :: IOError -> 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 -- | An error indicating that an IO operation failed because one of -- its arguments does not exist. isDoesNotExistError :: IOError -> Bool -- | An error indicating that an IO operation failed because one of -- its arguments already exists. isAlreadyExistsError :: IOError -> Bool -- | 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 -- | 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) -- | Like bracket, but only performs the final action if there was -- an exception raised by the in-between computation. bracketOnError :: () => IO a -> (a -> IO b) -> (a -> IO c) -> IO c -- | A variant of bracket where the return value from the first -- computation is not required. bracket_ :: () => IO a -> IO b -> IO c -> IO c -- | A specialised variant of bracket with just a computation to run -- afterward. finally :: () => IO a -> IO b -> IO a -- | When you want to acquire a resource, do some work with it, and then -- release the resource, it is a good idea to use bracket, because -- bracket will install the necessary exception handler to release -- the resource in the event that an exception is raised during the -- computation. If an exception is raised, then bracket will -- re-raise the exception (after performing the release). -- -- A common example is opening a file: -- --
-- bracket
-- (openFile "filename" ReadMode)
-- (hClose)
-- (\fileHandle -> do { ... })
--
--
-- The arguments to bracket are in this order so that we can
-- partially apply it, e.g.:
--
-- -- withFile name mode = bracket (openFile name mode) hClose --bracket :: () => IO a -> (a -> IO b) -> (a -> IO c) -> IO c -- | Like finally, but only performs the final action if there was -- an exception raised by the computation. onException :: () => IO a -> IO b -> IO a -- | A variant of try that takes an exception predicate to select -- which exceptions are caught (c.f. catchJust). If the exception -- does not match the predicate, it is re-thrown. tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a) -- | Similar to catch, but returns an Either result which is -- (Right a) if no exception of type e was -- raised, or (Left ex) if an exception of type -- e was raised and its value is ex. If any other type -- of exception is raised than it will be propogated up to the next -- enclosing exception handler. -- --
-- try a = catch (Right `liftM` a) (return . Left) --try :: Exception e => IO a -> IO (Either e a) -- | This function maps one exception into another as proposed in the paper -- "A semantics for imprecise exceptions". mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a -- | A version of catchJust with the arguments swapped around (see -- handle). handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a -- | A version of catch with the arguments swapped around; useful in -- situations where the code for the handler is shorter. For example: -- --
-- do handle (\NonTermination -> exitWith (ExitFailure 1)) $ -- ... --handle :: Exception e => (e -> IO a) -> IO a -> IO a -- | The function catchJust is like catch, but it takes an -- extra argument which is an exception predicate, a function -- which selects which type of exceptions we're interested in. -- --
-- catchJust (\e -> if isDoesNotExistErrorType (ioeGetErrorType e) then Just () else Nothing)
-- (readFile f)
-- (\_ -> do hPutStrLn stderr ("No such file: " ++ show f)
-- return "")
--
--
-- Any other exceptions which are not matched by the predicate are
-- re-raised, and may be caught by an enclosing catch,
-- catchJust, etc.
catchJust :: Exception e => (e -> Maybe b) -> IO a -> (b -> IO a) -> IO a
-- | A pattern match failed. The String gives information about
-- the source location of the pattern.
newtype PatternMatchFail
PatternMatchFail :: String -> PatternMatchFail
-- | A record selector was applied to a constructor without the appropriate
-- field. This can only happen with a datatype with multiple
-- constructors, where some fields are in one constructor but not
-- another. The String gives information about the source
-- location of the record selector.
newtype RecSelError
RecSelError :: String -> RecSelError
-- | An uninitialised record field was used. The String gives
-- information about the source location where the record was
-- constructed.
newtype RecConError
RecConError :: String -> RecConError
-- | A record update was performed on a constructor without the appropriate
-- field. This can only happen with a datatype with multiple
-- constructors, where some fields are in one constructor but not
-- another. The String gives information about the source
-- location of the record update.
newtype RecUpdError
RecUpdError :: String -> RecUpdError
-- | A class method without a definition (neither a default definition, nor
-- a definition in the appropriate instance) was called. The
-- String gives information about which method it was.
newtype NoMethodError
NoMethodError :: String -> NoMethodError
-- | An expression that didn't typecheck during compile time was called.
-- This is only possible with -fdefer-type-errors. The String
-- gives details about the failed type check.
newtype TypeError
TypeError :: String -> TypeError
-- | Thrown when the runtime system detects that the computation is
-- guaranteed not to terminate. Note that there is no guarantee that the
-- runtime system will notice whether any given computation is guaranteed
-- to terminate or not.
data NonTermination
NonTermination :: NonTermination
-- | Thrown when the program attempts to call atomically, from the
-- stm package, inside another call to atomically.
data NestedAtomically
NestedAtomically :: NestedAtomically
getUncaughtExceptionHandler :: IO (SomeException -> IO ())
setUncaughtExceptionHandler :: (SomeException -> IO ()) -> IO ()
reportError :: SomeException -> IO ()
reportStackOverflow :: IO ()
-- | Write the supplied value into a TVar.
writeTVar :: () => TVar a -> a -> STM ()
-- | Return the current value stored in a TVar.
readTVar :: () => TVar a -> STM a
-- | Return the current value stored in a TVar. This is equivalent
-- to
--
-- -- 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 -- | 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) -- | Exception handling within STM actions. catchSTM :: Exception e => STM a -> (e -> STM a) -> STM a -- | 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. -- -- 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 -- | 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 -- | 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 -- | Unsafely performs IO in the STM monad. Beware: this is a highly -- dangerous thing to do. -- --
-- killThread tid = throwTo tid ThreadKilled --killThread :: ThreadId -> IO () childHandler :: SomeException -> IO () -- | Returns the number of sparks currently in the local spark pool numSparks :: IO Int -- | Returns the number of CPUs that the machine has getNumProcessors :: IO Int -- | Set the number of Haskell threads that can run truly simultaneously -- (on separate physical processors) at any given time. The number passed -- to 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 () -- | 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 -- | 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 -- | 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 -- | Disable allocation limit processing for the current thread. disableAllocationLimit :: IO () -- | 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 () -- | Return the current value of the allocation counter for the current -- thread. getAllocationCounter :: IO Int64 -- | 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: -- --
-- ref <- newIORef '1'
-- forever $ atomicModifyIORef ref (\_ -> ('2', ()))
--
--
-- Use atomicModifyIORef' or atomicWriteIORef to avoid this
-- problem.
atomicModifyIORef :: () => IORef a -> (a -> (a, b)) -> IO b
-- | 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 seldomly uses the value, thunks will pile up in memory
-- resulting in a space leak. This is a common mistake made when using an
-- IORef as a counter. For example, the following will likely produce a
-- stack overflow:
--
-- -- 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)) -- | 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) -- | 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) -- | 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 -- | 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) -- | Causes the finalizers associated with a foreign pointer to be run -- immediately. finalizeForeignPtr :: () => 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 -- | This function casts a ForeignPtr parameterised by one type into -- another type. castForeignPtr :: () => ForeignPtr a -> ForeignPtr b -- | This function ensures that the foreign object in question is alive at -- the given place in the sequence of IO actions. In particular -- withForeignPtr does a touchForeignPtr after it executes -- the user action. -- -- Note that this function should not be used to express dependencies -- between finalizers on ForeignPtrs. For example, if the -- finalizer for a ForeignPtr F1 calls -- touchForeignPtr on a second ForeignPtr F2, then -- the only guarantee is that the finalizer for F2 is never -- started before the finalizer for F1. They might be started -- together if for example both F1 and F2 are otherwise -- unreachable, and in that case the scheduler might end up running the -- finalizer for F2 first. -- -- In general, it is not recommended to use finalizers on separate -- objects with ordering constraints between them. To express the -- ordering robustly requires explicit synchronisation using -- MVars between the finalizers, but even then the runtime -- sometimes runs multiple finalizers sequentially in a single thread -- (for performance reasons), so synchronisation between finalizers could -- result in artificial deadlock. Another alternative is to use explicit -- reference counting. touchForeignPtr :: () => ForeignPtr a -> IO () -- | Turns a plain memory reference into a foreign pointer that may be -- associated with finalizers by using addForeignPtrFinalizer. newForeignPtr_ :: () => Ptr a -> IO (ForeignPtr a) -- | Like addForeignPtrFinalizerEnv but allows the finalizer to be -- passed an additional environment parameter to be passed to the -- finalizer. The environment passed to the finalizer is fixed by the -- second argument to addForeignPtrFinalizerEnv addForeignPtrFinalizerEnv :: () => FinalizerEnvPtr env a -> Ptr env -> ForeignPtr a -> IO () -- | This function adds a finalizer to the given foreign object. The -- finalizer will run before all other finalizers for the same -- object which have already been registered. addForeignPtrFinalizer :: () => FinalizerPtr a -> ForeignPtr a -> IO () -- | This 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)
-- | 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 ()
-- | 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)
-- | A mutable variable in the IO monad
data IORef a
-- | 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 -- | Like mask, but the masked computation is not interruptible (see -- Control.Exception#interruptible). THIS SHOULD BE USED WITH -- GREAT CARE, because if a thread executing in -- uninterruptibleMask blocks for any reason, then the thread (and -- possibly the program, if this is the main thread) will be unresponsive -- and unkillable. This function should only be necessary if you need to -- mask exceptions around an interruptible operation, and you can -- guarantee that the interruptible operation will only block for a short -- period of time. uninterruptibleMask :: () => ((forall a. () => IO a -> IO a) -> IO b) -> IO b -- | Like uninterruptibleMask, but does not pass a restore -- action to the argument. uninterruptibleMask_ :: () => IO a -> IO a -- | Executes an IO computation with asynchronous exceptions masked. -- That is, any thread which attempts to raise an exception in the -- current thread with throwTo will be blocked until asynchronous -- exceptions are unmasked again. -- -- The argument passed to mask is a function that takes as its -- argument another function, which can be used to restore the prevailing -- masking state within the context of the masked computation. For -- example, a common way to use mask is to protect the acquisition -- of a resource: -- --
-- mask $ \restore -> do -- x <- acquire -- restore (do_something_with x) `onException` release -- release ---- -- This code guarantees that acquire is paired with -- release, by masking asynchronous exceptions for the critical -- parts. (Rather than write this code yourself, it would be better to -- use bracket which abstracts the general pattern). -- -- Note that the restore action passed to the argument to -- mask does not necessarily unmask asynchronous exceptions, it -- just restores the masking state to that of the enclosing context. Thus -- if asynchronous exceptions are already masked, mask cannot be -- used to unmask exceptions again. This is so that if you call a library -- function with exceptions masked, you can be sure that the library call -- will not be able to unmask exceptions again. If you are writing -- library code and need to use asynchronous exceptions, the only way is -- to create a new thread; see forkIOWithUnmask. -- -- Asynchronous exceptions may still be received while in the masked -- state if the masked thread blocks in certain ways; see -- Control.Exception#interruptible. -- -- Threads created by forkIO inherit the MaskingState from -- the parent; that is, to start a thread in the -- MaskedInterruptible state, use mask_ $ forkIO .... -- This is particularly useful if you need to establish an exception -- handler in the forked thread before any asynchronous exceptions are -- received. To create a new thread in an unmasked state use -- forkIOWithUnmask. mask :: () => ((forall a. () => IO a -> IO a) -> IO b) -> IO b -- | Like mask, but does not pass a restore action to the -- argument. mask_ :: () => IO a -> IO a -- | Returns the MaskingState for the current thread. getMaskingState :: IO MaskingState -- | Allow asynchronous exceptions to be raised even inside mask, -- making the operation interruptible (see the discussion of -- "Interruptible operations" in Exception). -- -- When called outside mask, or inside uninterruptibleMask, -- this function has no effect. interruptible :: () => IO a -> IO a -- | A variant of throw that can only be used within the IO -- monad. -- -- Although throwIO has a type that is an instance of the type of -- throw, the two functions are subtly different: -- --
-- throw e `seq` x ===> throw e -- throwIO e `seq` x ===> x ---- -- The first example will cause the exception e to be raised, -- whereas the second one won't. In fact, throwIO will only cause -- an exception to be raised when it is used within the IO monad. -- The throwIO variant should be used in preference to -- throw to raise an exception within the IO monad because -- it guarantees ordering with respect to other IO operations, -- whereas throw does not. throwIO :: Exception e => e -> IO a -- | This is the simplest of the exception-catching functions. It takes a -- single argument, runs it, and if an exception is raised the "handler" -- is executed, with the value of the exception passed as an argument. -- Otherwise, the result is returned as normal. For example: -- --
-- catch (readFile f)
-- (\e -> do let err = show (e :: IOException)
-- hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err)
-- return "")
--
--
-- Note that we have to give a type signature to e, or the
-- program will not typecheck as the type is ambiguous. While it is
-- possible to catch exceptions of any type, see the section "Catching
-- all exceptions" (in Control.Exception) for an explanation of
-- the problems with doing so.
--
-- For catching exceptions in pure (non-IO) expressions, see the
-- function evaluate.
--
-- Note that due to Haskell's unspecified evaluation order, an expression
-- may throw one of several possible exceptions: consider the expression
-- (error "urk") + (1 `div` 0). Does the expression throw
-- ErrorCall "urk", or DivideByZero?
--
-- The answer is "it might throw either"; the choice is
-- non-deterministic. If you are catching any type of exception then you
-- might catch either. If you are calling catch with type IO
-- Int -> (ArithException -> IO Int) -> IO Int then the
-- handler may get run with DivideByZero as an argument, or an
-- ErrorCall "urk" exception may be propogated further up. If
-- you call it again, you might get a the opposite behaviour. This is ok,
-- because catch is an IO computation.
catch :: Exception e => IO a -> (e -> IO a) -> IO a
-- | Embed a strict state transformer 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
-- | 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
-- | 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
-- | 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 -- | 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 -- | Throw an exception. Exceptions may be thrown from purely functional -- code, but may only be caught within the IO monad. throw :: Exception e => e -> a -- | 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 -- | 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
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
-- | Force a TypeRep to normal form.
rnfTypeRep :: TypeRep -> ()
-- | Takes a value of type a and returns a concrete representation
-- of that type.
typeRepFingerprint :: TypeRep -> Fingerprint
-- | Observe the type constructor of a quantified type representation.
typeRepTyCon :: TypeRep -> TyCon
-- | Observe the argument types of a type representation
typeRepArgs :: TypeRep -> [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])
-- | Build a function type.
mkFunTy :: TypeRep -> TypeRep -> TypeRep
-- | 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
-- | Cast over k1 -> k2 -> k3
gcast2 :: (Typeable t, Typeable t') => c (t a b) -> Maybe (c (t' a b))
-- | Cast over k1 -> k2
gcast1 :: (Typeable t, Typeable t') => c (t a) -> Maybe (c (t' a))
-- | A flexible variation parameterised in a type constructor
gcast :: (Typeable a, Typeable b) => c a -> Maybe (c b)
-- | Extract a witness of equality of two types
eqT :: (Typeable a, Typeable b) => Maybe (a :~: b)
-- | The type-safe cast operation
cast :: (Typeable a, Typeable b) => a -> Maybe b
-- | Show a type representation
showsTypeRep :: TypeRep -> ShowS
-- | Takes a value of type a and returns a concrete representation
-- of that type.
typeRep :: Typeable a => proxy a -> TypeRep
-- | Observe a type representation for the type of a value.
typeOf :: Typeable a => a -> TypeRep
-- | A quantified type representation.
type TypeRep = SomeTypeRep
rnfTyCon :: TyCon -> ()
tyConFingerprint :: TyCon -> Fingerprint
tyConName :: TyCon -> String
tyConModule :: TyCon -> String
tyConPackage :: TyCon -> String
-- | The Const functor.
newtype Const a (b :: k) :: forall k. () => Type -> k -> Type
Const :: a -> Const a
[getConst] :: Const a -> a
-- | 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.
find :: Foldable t => (a -> Bool) -> t a -> Maybe a
-- | notElem is the negation of elem.
notElem :: (Foldable t, Eq a) => a -> t a -> Bool
infix 4 `notElem`
-- | The least element of a non-empty structure with respect to the given
-- comparison function.
minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
-- | The largest element of a non-empty structure with respect to the given
-- comparison function.
maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
-- | Determines whether all elements of the structure satisfy the
-- predicate.
all :: Foldable t => (a -> Bool) -> t a -> Bool
-- | Determines whether any element of the structure satisfies the
-- predicate.
any :: Foldable t => (a -> Bool) -> t a -> Bool
-- | or returns the disjunction of a container of Bools. For the
-- result to be False, the container must be finite; True,
-- however, results from a True value finitely far from the left
-- end.
or :: Foldable t => t Bool -> Bool
-- | and returns the conjunction of a container of Bools. For the
-- result to be True, the container must be finite; False,
-- however, results from a False value finitely far from the left
-- end.
and :: Foldable t => t Bool -> Bool
-- | Map a function over all the elements of a container and concatenate
-- the resulting lists.
concatMap :: Foldable t => (a -> [b]) -> t a -> [b]
-- | The concatenation of all the elements of a container of lists.
concat :: Foldable t => t [a] -> [a]
-- | The sum of a collection of actions, generalizing concat. As of
-- base 4.8.0.0, msum is just asum, specialized to
-- MonadPlus.
msum :: (Foldable t, MonadPlus m) => t (m a) -> m a
-- | The sum of a collection of actions, generalizing concat.
--
-- asum [Just Hello, Nothing, Just World] Just Hello
asum :: (Foldable t, Alternative f) => t (f a) -> f a
-- | Evaluate each monadic action in the structure from left to right, and
-- ignore the results. For a version that doesn't ignore the results see
-- sequence.
--
-- As of base 4.8.0.0, sequence_ is just sequenceA_,
-- specialized to Monad.
sequence_ :: (Foldable t, Monad m) => t (m a) -> m ()
-- | 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_ :: (Foldable t, Applicative f) => t (f a) -> f ()
-- | forM_ is mapM_ with its arguments flipped. For a version
-- that doesn't ignore the results see forM.
--
-- As of base 4.8.0.0, forM_ is just for_, specialized to
-- Monad.
forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m ()
-- | Map each element of a structure to a monadic action, evaluate these
-- actions from left to right, and ignore the results. For a version that
-- doesn't ignore the results see mapM.
--
-- As of base 4.8.0.0, mapM_ is just traverse_, specialized
-- to Monad.
mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()
-- | for_ is traverse_ with its arguments flipped. For a
-- version that doesn't ignore the results see for.
--
-- -- >>> for_ [1..4] print -- 1 -- 2 -- 3 -- 4 --for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f () -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and ignore the results. For a version that doesn't -- ignore the results see traverse. traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f () -- | Monadic fold over the elements of a structure, associating to the -- left, i.e. from left to right. foldlM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | Monadic fold over the elements of a structure, associating to the -- right, i.e. from right to left. foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b -- | This data type witnesses the lifting of a Monoid into an -- Applicative pointwise. newtype Ap (f :: k -> Type) (a :: k) :: forall k. () => k -> Type -> k -> Type Ap :: f a -> Ap [getAp] :: Ap -> f a -- | This is a valid definition of stimes for a Monoid. -- -- Unlike the default definition of stimes, it is defined for 0 -- and so it should be preferred where possible. stimesMonoid :: (Integral b, Monoid a) => b -> a -> a -- | This is a valid definition of stimes for an idempotent -- Semigroup. -- -- When x <> x = x, this definition should be preferred, -- because it works in O(1) rather than O(log n). stimesIdempotent :: Integral b => b -> a -> a -- | The dual of a Monoid, obtained by swapping the arguments of -- mappend. -- --
-- >>> getDual (mappend (Dual "Hello") (Dual "World")) -- "WorldHello" --newtype Dual a Dual :: a -> Dual a [getDual] :: Dual a -> a -- | The monoid of endomorphisms under composition. -- --
-- >>> let computation = Endo ("Hello, " ++) <> Endo (++ "!")
--
-- >>> appEndo computation "Haskell"
-- "Hello, Haskell!"
--
newtype Endo a
Endo :: (a -> a) -> Endo a
[appEndo] :: Endo a -> a -> a
-- | Boolean monoid under conjunction (&&).
--
-- -- >>> getAll (All True <> mempty <> All False) -- False ---- --
-- >>> getAll (mconcat (map (\x -> All (even x)) [2,4,6,7,8])) -- False --newtype All All :: Bool -> All [getAll] :: All -> Bool -- | Boolean monoid under disjunction (||). -- --
-- >>> getAny (Any True <> mempty <> Any False) -- True ---- --
-- >>> getAny (mconcat (map (\x -> Any (even x)) [2,4,6,7,8])) -- True --newtype Any Any :: Bool -> Any [getAny] :: Any -> Bool -- | Monoid under addition. -- --
-- >>> getSum (Sum 1 <> Sum 2 <> mempty) -- 3 --newtype Sum a Sum :: a -> Sum a [getSum] :: Sum a -> a -- | Monoid under multiplication. -- --
-- >>> getProduct (Product 3 <> Product 4 <> mempty) -- 12 --newtype Product a Product :: a -> Product a [getProduct] :: Product a -> a getAlt :: Alt f a -> f a unsafeCoerce :: () => a -> b -- | unwords is an inverse operation to words. It joins words -- with separating spaces. -- --
-- >>> unwords ["Lorem", "ipsum", "dolor"] -- "Lorem ipsum dolor" --unwords :: [String] -> String -- | words breaks a string up into a list of words, which were -- delimited by white space. -- --
-- >>> words "Lorem ipsum\ndolor" -- ["Lorem","ipsum","dolor"] --words :: String -> [String] -- | 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 -- | 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 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] -- | 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 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 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] -- | The permutations function returns the list of all permutations -- of the argument. -- --
-- >>> permutations "abc" -- ["abc","bac","cba","bca","cab","acb"] --permutations :: () => [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]] -- | 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 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 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] -- | 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]) -- | 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. 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. 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. 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. 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. 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. 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. 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. zip4 :: () => [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)] -- | 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] -- | The genericIndex function is an overloaded version of -- !!, which accepts any Integral value as the index. genericIndex :: Integral i => [a] -> i -> 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 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 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 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 :: Num i => [a] -> i -- | The non-overloaded version of insert. insertBy :: () => (a -> a -> Ordering) -> a -> [a] -> [a] -- | 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 partition function takes a predicate a list and returns the -- pair of lists of elements which do and do not satisfy the predicate, -- respectively; i.e., -- --
-- 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 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]] -- | 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] -- | 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] -- | 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 \\ 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 \\ -- | 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] -- | 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 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] -- | O(n^2). 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] -- | 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 -- | 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 -- | 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 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 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] -- | 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]
-- | Selects Unicode space and separator characters.
--
-- This function returns True if its argument has one of the
-- following GeneralCategorys, or False otherwise:
--
-- -- >>> 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 ): -- --
-- >>> 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: -- --
-- >>> 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: -- --
-- >>> 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: -- --
-- >>> 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'). -- --
-- >>> 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 -- | 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 -- | 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 -- | equivalent to readsPrec with a precedence of 0. reads :: Read a => ReadS a -- | Return the contents of a Right-value or a default value -- otherwise. -- --
-- >>> fromRight 1 (Right 3) -- 3 -- -- >>> fromRight 1 (Left "foo") -- 1 --fromRight :: () => b -> Either a b -> b -- | Return the contents of a Left-value or a default value -- otherwise. -- --
-- >>> fromLeft 1 (Left 3) -- 3 -- -- >>> fromLeft 1 (Right "foo") -- 1 --fromLeft :: () => a -> Either a b -> a -- | Return True if the given value is a Right-value, -- False otherwise. -- --
-- >>> isRight (Left "foo") -- False -- -- >>> isRight (Right 3) -- True ---- -- Assuming a Left value signifies some sort of error, we can use -- isRight to write a very simple reporting function that only -- outputs "SUCCESS" when a computation has succeeded. -- -- This example shows how isRight might be used to avoid pattern -- matching when one does not care about the value contained in the -- constructor: -- --
-- >>> import Control.Monad ( when ) -- -- >>> let report e = when (isRight e) $ putStrLn "SUCCESS" -- -- >>> report (Left "parse error") -- -- >>> report (Right 1) -- SUCCESS --isRight :: () => Either a b -> Bool -- | Return True if the given value is a Left-value, -- False otherwise. -- --
-- >>> isLeft (Left "foo") -- True -- -- >>> isLeft (Right 3) -- False ---- -- Assuming a Left value signifies some sort of error, we can use -- isLeft to write a very simple error-reporting function that -- does absolutely nothing in the case of success, and outputs "ERROR" if -- any error occurred. -- -- This example shows how isLeft might be used to avoid pattern -- matching when one does not care about the value contained in the -- constructor: -- --
-- >>> import Control.Monad ( when ) -- -- >>> let report e = when (isLeft e) $ putStrLn "ERROR" -- -- >>> report (Right 1) -- -- >>> report (Left "parse error") -- ERROR --isLeft :: () => Either a b -> Bool -- | 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. -- --
-- >>> 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 Right elements. -- All the Right elements are extracted in order. -- --
-- >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ] -- -- >>> rights list -- [3,7] --rights :: () => [Either a b] -> [b] -- | Extracts from a list of Either all the Left elements. -- All the Left elements are extracted in order. -- --
-- >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ] -- -- >>> lefts list -- ["foo","bar","baz"] --lefts :: () => [Either a 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. -- --
-- >>> 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 -- |
-- 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 -- | 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 newtype Down a Down :: a -> Down a -- | 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 -- | 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) :: forall k. () => k -> Type Proxy :: Proxy -- | 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 -- | Left-to-right composition (>>>) :: Category cat => cat a b -> cat b c -> cat a c infixr 1 >>> -- | Right-to-left composition (<<<) :: Category cat => cat b c -> cat a b -> cat a c infixr 1 <<< -- | A class for categories. Instances should satisfy the laws -- --
-- f . id = f -- (right identity) -- id . f = f -- (left identity) -- f . (g . h) = (f . g) . h -- (associativity) --class Category (cat :: k -> k -> Type) -- | the identity morphism id :: Category cat => cat a a -- | morphism composition (.) :: Category cat => cat b c -> cat a b -> cat a c infixr 9 . -- | 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) :: forall k. () => k -> k -> Type [Refl] :: forall k (a :: k) (b :: k). () => a :~: a infix 4 :~: -- | 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) :: forall k1 k2. () => k1 -> k2 -> Type [HRefl] :: forall k1 k2 (a :: k1) (b :: k2). () => a :~~: a infix 4 :~~: -- | casts an IntPtr to a Ptr intPtrToPtr :: () => IntPtr -> Ptr a -- | casts a Ptr to an IntPtr ptrToIntPtr :: () => Ptr a -> IntPtr -- | casts a WordPtr to a Ptr wordPtrToPtr :: () => WordPtr -> Ptr a -- | casts a Ptr to a WordPtr ptrToWordPtr :: () => Ptr a -> WordPtr -- | 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 () -- | 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 -- | 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 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 () -- | 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 -- | 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 () -- | Obtain the Haskell value referenced by a stable pointer, i.e., the -- same value that was passed to the corresponding call to -- makeStablePtr. If the argument to deRefStablePtr has -- already been freed using freeStablePtr, the behaviour of -- deRefStablePtr is undefined. deRefStablePtr :: () => StablePtr a -> IO a -- | Dissolve the association between the stable pointer and the Haskell -- value. Afterwards, if the stable pointer is passed to -- 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 () -- | 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 -- | 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 -- | 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 -- | 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 -- | Advances the given address by the given offset in bytes. plusPtr :: () => Ptr a -> Int -> Ptr b -- | The castPtr function casts a pointer from one type to another. castPtr :: () => Ptr a -> Ptr b -- | The constant nullPtr contains a distinguished value of -- Ptr that is not associated with a valid memory location. nullPtr :: () => Ptr a -- | Show non-negative Integral numbers in base 8. showOct :: (Integral a, Show a) => a -> ShowS -- | Show non-negative Integral numbers in base 16. showHex :: (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 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 -- (e.g. 245000, 0.0015). -- -- This behaves as showFFloat, except that a decimal point is -- always guaranteed, even if not needed. showFFloatAlt :: RealFloat a => Maybe Int -> a -> ShowS -- | Show a signed RealFloat value using standard decimal notation -- for arguments whose absolute value lies between 0.1 and -- 9,999,999, and scientific notation otherwise. -- -- 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). -- -- 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 10. showInt :: Integral a => a -> ShowS -- | Reads a signed Real value, given a reader for an -- unsigned value. readSigned :: Real a => ReadS a -> ReadS a -- | Reads an unsigned RealFrac value, expressed in decimal -- scientific notation. readFloat :: RealFrac a => 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 -- | Read an unsigned number in decimal notation. -- --
-- >>> readDec "0644" -- [(644,"")] --readDec :: (Eq a, Num 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 -- | Reads a non-empty string of decimal digits. lexDigits :: ReadS String -- | Read a string representation of a character, using Haskell -- source-language escape conventions, and convert it to the character -- that it encodes. For example: -- --
-- 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
-- | 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:
--
-- -- floatToDigits base x = ([d1,d2,...,dn], e) ---- -- then -- --
n >= 1
x = 0.d1d2...dn * (base**e)
0 <= di <= base-1
-- >>> 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 -- | 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: -- --
-- >>> isPunctuation 'a' -- False -- -- >>> isPunctuation '7' -- False -- -- >>> isPunctuation '♥' -- False -- -- >>> isPunctuation '"' -- True -- -- >>> isPunctuation '?' -- True -- -- >>> isPunctuation '—' -- True --isPunctuation :: Char -> Bool -- | Selects ASCII hexadecimal digits, i.e. '0'..'9', -- 'a'..'f', 'A'..'F'. isHexDigit :: Char -> Bool -- | Selects ASCII octal digits, i.e. '0'..'7'. isOctDigit :: Char -> Bool -- | Selects ASCII digits, i.e. '0'..'9'. isDigit :: Char -> Bool -- | Returns True for any Unicode space character, and the control -- characters \t, \n, \r, \f, -- \v. isSpace :: 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 256 characters of the Unicode character set, -- corresponding to the ISO 8859-1 (Latin-1) character set. isLatin1 :: Char -> Bool -- | Selects the first 128 characters of the Unicode character set, -- corresponding to the ASCII character set. isAscii :: 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. -- --
-- >>> generalCategory 'a' -- LowercaseLetter -- -- >>> generalCategory 'A' -- UppercaseLetter -- -- >>> generalCategory '0' -- DecimalNumber -- -- >>> generalCategory '%' -- OtherPunctuation -- -- >>> generalCategory '♥' -- OtherSymbol -- -- >>> generalCategory '\31' -- Control -- -- >>> generalCategory ' ' -- Space --generalCategory :: Char -> GeneralCategory -- | 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). -- --
-- >>> :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 -- | 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) -- | 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
-- | Return the value computed by a state transformer computation. 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
-- | 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 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 testBit. -- -- Note that: testBitDefault x i = (x .&. bit i) /= 0 testBitDefault :: (Bits a, Num a) => a -> Int -> Bool -- | Default implementation for bit. -- -- Note that: bitDefault i = 1 shiftL i bitDefault :: (Bits a, Num a) => Int -> a -- | The Bits class defines bitwise operations over integral types. -- --
clearBit zeroBits n == -- zeroBits
setBit zeroBits n == bit -- n
testBit zeroBits n == False
popCount zeroBits == 0
-- 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 -- | Case analysis for the Bool type. bool x y p -- evaluates to x when p is False, and evaluates -- to y when p is True. -- -- This is equivalent to if p then y else x; that is, one can -- think of it as an if-then-else construct with its arguments reordered. -- --
-- >>> bool "foo" "bar" True -- "bar" -- -- >>> bool "foo" "bar" False -- "foo" ---- -- Confirm that bool x y p and if p then y else -- x are equivalent: -- --
-- >>> let p = True; x = "bar"; y = "foo" -- -- >>> bool x y p == if p then y else x -- True -- -- >>> let p = False -- -- >>> bool x y p == if p then y else x -- True --bool :: () => a -> a -> Bool -> a -- | & 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 & -- | on b u x y runs the binary function b -- on the results of applying unary function u to two -- arguments x and y. From the opposite perspective, it -- transforms two inputs and combines the outputs. -- --
-- ((+) `on` f) x y = f x + f y ---- -- Typical usage: sortBy (compare `on` -- fst). -- -- Algebraic properties: -- --
(*) `on` id = (*) -- (if (*) ∉ {⊥, const -- ⊥})
((*) `on` f) `on` g = (*) `on` (f . g)
flip on f . flip on g = flip on (g . -- f)
-- >>> 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' argument, hence the recursion is reintroduced. fix :: () => (a -> a) -> a -- | void value discards or ignores the result of -- evaluation, such as the return value of an IO action. -- --
-- >>> void Nothing -- Nothing -- -- >>> void (Just 3) -- Just () ---- -- Replace the contents of an Either Int -- Int with unit, resulting in an Either -- Int '()': -- --
-- >>> void (Left 8675309) -- Left 8675309 -- -- >>> void (Right 8675309) -- Right () ---- -- Replace every element of a list with unit: -- --
-- >>> void [1,2,3] -- [(),(),()] ---- -- Replace the second element of a pair with unit: -- --
-- >>> void (1,2) -- (1,()) ---- -- Discard the result of an IO action: -- --
-- >>> mapM print [1,2] -- 1 -- 2 -- [(),()] -- -- >>> void $ mapM print [1,2] -- 1 -- 2 --void :: Functor f => f a -> f () -- | Flipped version of <$. -- --
-- >>> 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 $> -- | Flipped version of <$>. -- --
-- (<&>) = flip fmap ---- --
-- >>> Just 2 <&> (+1) -- Just 3 ---- --
-- >>> [1,2,3] <&> (+1) -- [2,3,4] ---- --
-- >>> Right 3 <&> (+1) -- Right 4 --(<&>) :: Functor f => f a -> (a -> b) -> f b infixl 1 <&> -- | An infix synonym for fmap. -- -- The name of this operator is an allusion to $. Note the -- similarities between their types: -- --
-- ($) :: (a -> b) -> a -> b -- (<$>) :: Functor f => (a -> b) -> f a -> f b ---- -- Whereas $ is function application, <$> is -- function application lifted over a Functor. -- --
-- >>> show <$> Nothing -- Nothing -- -- >>> show <$> Just 3 -- Just "3" ---- -- Convert from an Either Int Int to -- an Either Int String using -- show: -- --
-- >>> show <$> Left 17 -- Left 17 -- -- >>> show <$> Right 17 -- Right "17" ---- -- Double each element of a list: -- --
-- >>> (*2) <$> [1,2,3] -- [2,4,6] ---- -- Apply even to the second element of a pair: -- --
-- >>> even <$> (2,2) -- (2,True) --(<$>) :: Functor f => (a -> b) -> f a -> f b infixl 4 <$> -- | 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 -- | 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 ^ odd :: Integral a => a -> Bool even :: Integral a => a -> Bool -- | Converts a possibly-negative Real value to a string. showSigned :: Real a => (a -> ShowS) -> Int -> a -> ShowS -- | 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 -- | 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 -- | 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 -- | 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 -- | 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 that surrounds the inner show function with -- parentheses when the Bool parameter is True. showParen :: Bool -> ShowS -> ShowS -- | utility function converting a String to a show function that -- simply prepends the string unchanged. showString :: String -> ShowS -- | utility function converting a Char to a show function that -- simply prepends the character unchanged. showChar :: Char -> ShowS -- | equivalent to showsPrec with a precedence of 0. shows :: Show a => a -> ShowS -- | 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 -- | The unzip3 function takes a list of triples and returns three -- lists, analogous to unzip. 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 :: () => [(a, b)] -> ([a], [b]) -- | The zipWith3 function takes a function which combines three -- elements, as well as three lists and returns a list of their -- point-wise combination, analogous to zipWith. zipWith3 :: () => (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d] -- | zipWith generalises zip by zipping with the function -- given as the first argument, instead of a tupling function. For -- example, zipWith (+) is applied to two lists to -- produce the list of corresponding sums. -- -- zipWith is right-lazy: -- --
-- zipWith f [] _|_ = [] --zipWith :: () => (a -> b -> c) -> [a] -> [b] -> [c] -- | zip3 takes three lists and returns a list of triples, analogous -- to zip. zip3 :: () => [a] -> [b] -> [c] -> [(a, b, c)] -- | List index (subscript) operator, starting from 0. It is an instance of -- the more general genericIndex, which takes an index of any -- integral type. (!!) :: () => [a] -> Int -> a infixl 9 !! -- | lookup key assocs looks up a key in an association -- list. lookup :: Eq a => a -> [(a, b)] -> Maybe b -- | reverse xs returns the elements of xs in -- reverse order. xs must be finite. reverse :: () => [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]) -- | span, applied to a predicate p and a list xs, -- returns a tuple where first element is longest prefix (possibly empty) -- of xs of elements that satisfy p and second element -- is the remainder of the list: -- --
-- span (< 3) [1,2,3,4,1,2,3,4] == ([1,2],[3,4,1,2,3,4]) -- span (< 9) [1,2,3] == ([1,2,3],[]) -- span (< 0) [1,2,3] == ([],[1,2,3]) ---- -- span p xs is equivalent to (takeWhile p xs, -- dropWhile p xs) span :: () => (a -> Bool) -> [a] -> ([a], [a]) -- | splitAt n xs returns a tuple where first element is -- xs prefix of length n and second element is the -- remainder of the list: -- --
-- splitAt 6 "Hello World!" == ("Hello ","World!")
-- splitAt 3 [1,2,3,4,5] == ([1,2,3],[4,5])
-- splitAt 1 [1,2,3] == ([1],[2,3])
-- splitAt 3 [1,2,3] == ([1,2,3],[])
-- splitAt 4 [1,2,3] == ([1,2,3],[])
-- splitAt 0 [1,2,3] == ([],[1,2,3])
-- splitAt (-1) [1,2,3] == ([],[1,2,3])
--
--
-- It is equivalent to (take n xs, drop n xs) when
-- n is not _|_ (splitAt _|_ xs = _|_).
-- splitAt is an instance of the more general
-- genericSplitAt, in which n may be of any integral
-- type.
splitAt :: () => Int -> [a] -> ([a], [a])
-- | 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] -- | 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] -- | 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] -- | 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] -- | cycle ties a finite list into a circular one, or equivalently, -- the infinite repetition of the original list. It is the identity on -- infinite lists. cycle :: () => [a] -> [a] -- | replicate n x is a list of length n with -- x the value of every element. It is an instance of the more -- general genericReplicate, in which n may be of any -- integral type. replicate :: () => Int -> a -> [a] -- | repeat x is an infinite list, with x the -- value of every element. repeat :: () => a -> [a] -- | 'iterate\'' is the strict version of iterate. -- -- It ensures that the result of each application of force to weak head -- normal form 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. iterate :: () => (a -> a) -> a -> [a] -- | scanr1 is a variant of scanr that has no starting value -- argument. scanr1 :: () => (a -> a -> a) -> [a] -> [a] -- | scanr is the right-to-left dual of scanl. Note that -- --
-- head (scanr f z xs) == foldr f z xs. --scanr :: () => (a -> b -> b) -> b -> [a] -> [b] -- | A strictly accumulating version of scanl scanl' :: () => (b -> a -> b) -> b -> [a] -> [b] -- | scanl1 is a variant of scanl that has no starting value -- argument: -- --
-- scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...] --scanl1 :: () => (a -> a -> a) -> [a] -> [a] -- | scanl is similar to foldl, but returns a list of -- successive reduced values from the left: -- --
-- scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...] ---- -- Note that -- --
-- last (scanl f z xs) == foldl f z xs. --scanl :: () => (b -> a -> b) -> b -> [a] -> [b] -- | A strict version of foldl1 foldl1' :: () => (a -> a -> a) -> [a] -> a -- | Return all the elements of a list except the last one. The list must -- be non-empty. init :: () => [a] -> [a] -- | Extract the last element of a list, which must be finite and -- non-empty. last :: () => [a] -> a -- | Extract the elements after the head of a list, which must be -- non-empty. tail :: () => [a] -> [a] -- | Decompose a list into its head and tail. If the list is empty, returns -- Nothing. If the list is non-empty, returns Just (x, -- xs), where x is the head of the list and xs its -- tail. uncons :: () => [a] -> Maybe (a, [a]) -- | Extract the first element of a list, which must be non-empty. head :: () => [a] -> a -- | 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. -- --
-- >>> 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 catMaybes function takes a list of Maybes and -- returns a list of all the Just values. -- --
-- >>> 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] -- | The listToMaybe function returns Nothing on an empty -- list or Just a where a is the first element -- of the list. -- --
-- >>> 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 maybeToList function returns an empty list when given -- Nothing or a singleton list when not given Nothing. -- --
-- >>> 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 fromMaybe function takes a default value and and -- Maybe value. If the Maybe is Nothing, it returns -- the default values; otherwise, it returns the value contained in the -- Maybe. -- --
-- >>> 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. -- --
-- >>> fromJust (Just 1) -- 1 ---- --
-- >>> 2 * (fromJust (Just 10)) -- 20 ---- --
-- >>> 2 * (fromJust Nothing) -- *** Exception: Maybe.fromJust: Nothing --fromJust :: () => Maybe a -> a -- | The isNothing function returns True iff its argument is -- Nothing. -- --
-- >>> 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 _. -- --
-- >>> 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 maybe function takes a default value, a function, and a -- Maybe value. If the Maybe value is Nothing, the -- function returns the default value. Otherwise, it applies the function -- to the value inside the Just and returns the result. -- --
-- >>> maybe False odd (Just 3) -- True ---- --
-- >>> maybe False odd Nothing -- False ---- -- Read an integer from a string using readMaybe. If we succeed, -- return twice the integer; that is, apply (*2) to it. If -- instead we fail to parse an integer, return 0 by default: -- --
-- >>> import Text.Read ( readMaybe ) -- -- >>> maybe 0 (*2) (readMaybe "5") -- 10 -- -- >>> maybe 0 (*2) (readMaybe "") -- 0 ---- -- Apply show to a Maybe Int. If we have Just -- n, we want to show the underlying Int n. But if -- we have Nothing, we return the empty string instead of (for -- example) "Nothing": -- --
-- >>> maybe "" show (Just 5) -- "5" -- -- >>> maybe "" show Nothing -- "" --maybe :: () => b -> (a -> b) -> Maybe a -> b -- | Swap the components of a pair. swap :: () => (a, b) -> (b, a) -- | uncurry converts a curried function to a function on pairs. -- --
-- >>> uncurry (+) (1,2) -- 3 ---- --
-- >>> uncurry ($) (show, 1) -- "1" ---- --
-- >>> map (uncurry max) [(1,2), (3,4), (6,8)] -- [2,4,8] --uncurry :: () => (a -> b -> c) -> (a, b) -> c -- | curry converts an uncurried function to a curried function. -- --
-- >>> curry fst 1 2 -- 1 --curry :: () => ((a, b) -> c) -> a -> b -> c -- | 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 -- | 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: -- --
-- 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 -- | 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 -- | 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 -- | 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) -- | 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: -- --
-- readMVar :: MVar a -> IO a -- readMVar m = -- mask_ $ do -- a <- takeMVar m -- putMVar m a -- return a --readMVar :: () => MVar a -> IO a -- | Return the contents of the MVar. If the MVar is -- currently empty, takeMVar will wait until it is full. After a -- takeMVar, the MVar is left empty. -- -- There are two further important properties of takeMVar: -- --
-- >>> 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 -- | The fromEnum method restricted to the type Char. ord :: Char -> Int -- | 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 -- | 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 -- | Promote a function to a monad. liftM :: Monad m => (a1 -> r) -> m a1 -> m r -- | 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 () -- | Same as >>=, but with the arguments interchanged. (=<<) :: Monad m => (a -> m b) -> m a -> m b infixr 1 =<< -- | 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. This function may be used as a value for -- fmap in a Functor instance. liftA :: Applicative f => (a -> b) -> f a -> f b -- | A variant of <*> with the arguments reversed. (<**>) :: Applicative f => f a -> f (a -> b) -> f b infixl 4 <**> -- | 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 <|> -- | 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 -- | Non-empty (and non-strict) list type. data NonEmpty a (:|) :: a -> [a] -> NonEmpty a infixr 5 :| -- | A String is a list of characters. String constants in Haskell -- are values of type String. type String = [Char] -- | A special case of error. It is expected that compilers will -- recognize this and insert error messages which are more appropriate to -- the context in which undefined appears. undefined :: HasCallStack => a -- | A variant of error that does not produce a stack trace. errorWithoutStackTrace :: () => [Char] -> a -- | error stops execution and displays an error message. error :: 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 O(1) rather than O(log n) 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] :: forall e. Exception e => e -> SomeException -- | Boolean "and" (&&) :: Bool -> Bool -> Bool infixr 3 && -- | Boolean "or" (||) :: Bool -> Bool -> Bool infixr 2 || -- | Boolean "not" not :: Bool -> Bool (<<$>>) :: () => (a -> b) -> a -> b infixl 4 <<$>> -- | A compact representation of a Word8 vector. -- -- It has a lower memory overhead than a ByteString and 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 -- | A map of integers to values a. data IntMap a -- | A set of integers. data IntSet -- | A Map from keys k to values a. 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 contramany :: Decidable f => f a -> f [a] -- | An alias to divided. (>*<) :: Divisible f => f a -> f b -> f (a, b) -- | A combination of a divisible functor with some input for it. Allows to -- use the Monoid API for composition. data Supplied (divisible :: Type -> Type) [Supplied] :: forall (divisible :: Type -> Type) input. () => !divisible input -> !input -> Supplied divisible contrazip2 :: Divisible f => f a1 -> f a2 -> f (a1, a2) contrazip3 :: Divisible f => f a1 -> f a2 -> f a3 -> f (a1, a2, a3) contrazip4 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f (a1, a2, a3, a4) contrazip5 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f (a1, a2, a3, a4, a5) contrazip6 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f (a1, a2, a3, a4, a5, a6) contrazip7 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f (a1, a2, a3, a4, a5, a6, a7) contrazip8 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f (a1, a2, a3, a4, a5, a6, a7, a8) contrazip9 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9) contrazip10 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) contrazip11 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) contrazip12 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) contrazip13 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13) contrazip14 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) contrazip15 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) contrazip16 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16) contrazip17 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17) contrazip18 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18) contrazip19 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19) contrazip20 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) contrazip21 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21) contrazip22 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22) contrazip23 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23) contrazip24 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f a24 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24) contrazip25 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f a24 -> f a25 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25) contrazip26 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f a24 -> f a25 -> f a26 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26) contrazip27 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f a24 -> f a25 -> f a26 -> f a27 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27) contrazip28 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f a24 -> f a25 -> f a26 -> f a27 -> f a28 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28) contrazip29 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f a24 -> f a25 -> f a26 -> f a27 -> f a28 -> f a29 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29) contrazip30 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f a24 -> f a25 -> f a26 -> f a27 -> f a28 -> f a29 -> f a30 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30) contrazip31 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f a24 -> f a25 -> f a26 -> f a27 -> f a28 -> f a29 -> f a30 -> f a31 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31) contrazip32 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f a24 -> f a25 -> f a26 -> f a27 -> f a28 -> f a29 -> f a30 -> f a31 -> f a32 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32) contrazip33 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f a24 -> f a25 -> f a26 -> f a27 -> f a28 -> f a29 -> f a30 -> f a31 -> f a32 -> f a33 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33) contrazip34 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f a24 -> f a25 -> f a26 -> f a27 -> f a28 -> f a29 -> f a30 -> f a31 -> f a32 -> f a33 -> f a34 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34) contrazip35 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f a24 -> f a25 -> f a26 -> f a27 -> f a28 -> f a29 -> f a30 -> f a31 -> f a32 -> f a33 -> f a34 -> f a35 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35) contrazip36 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f a24 -> f a25 -> f a26 -> f a27 -> f a28 -> f a29 -> f a30 -> f a31 -> f a32 -> f a33 -> f a34 -> f a35 -> f a36 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36) contrazip37 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f a24 -> f a25 -> f a26 -> f a27 -> f a28 -> f a29 -> f a30 -> f a31 -> f a32 -> f a33 -> f a34 -> f a35 -> f a36 -> f a37 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37) contrazip38 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f a24 -> f a25 -> f a26 -> f a27 -> f a28 -> f a29 -> f a30 -> f a31 -> f a32 -> f a33 -> f a34 -> f a35 -> f a36 -> f a37 -> f a38 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38) contrazip39 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f a24 -> f a25 -> f a26 -> f a27 -> f a28 -> f a29 -> f a30 -> f a31 -> f a32 -> f a33 -> f a34 -> f a35 -> f a36 -> f a37 -> f a38 -> f a39 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39) contrazip40 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f a24 -> f a25 -> f a26 -> f a27 -> f a28 -> f a29 -> f a30 -> f a31 -> f a32 -> f a33 -> f a34 -> f a35 -> f a36 -> f a37 -> f a38 -> f a39 -> f a40 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40) contrazip41 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f a24 -> f a25 -> f a26 -> f a27 -> f a28 -> f a29 -> f a30 -> f a31 -> f a32 -> f a33 -> f a34 -> f a35 -> f a36 -> f a37 -> f a38 -> f a39 -> f a40 -> f a41 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41) contrazip42 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f a6 -> f a7 -> f a8 -> f a9 -> f a10 -> f a11 -> f a12 -> f a13 -> f a14 -> f a15 -> f a16 -> f a17 -> f a18 -> f a19 -> f a20 -> f a21 -> f a22 -> f a23 -> f a24 -> f a25 -> f a26 -> f a27 -> f a28 -> f a29 -> f a30 -> f a31 -> f a32 -> f a33 -> f a34 -> f a35 -> f a36 -> f a37 -> f a38 -> f a39 -> f a40 -> f a41 -> f a42 -> f (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42) -- | 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 -> () -- | 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 -> () -- | Deeply strict version of <$>. (<$!!>) :: (Monad m, NFData b) => (a -> b) -> m a -> m b infixl 4 <$!!> -- | 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 -- | 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 $!! -- | 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 -- | 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 '()'. -- --
-- {-# 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)
--
--
-- -- 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 -> ()
-- | A class of functors that can be fully evaluated.
class NFData1 (f :: Type -> Type)
-- | 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 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 difference list is a function that, given a list, returns the
-- original contents of the difference list prepended to the given list.
--
-- This structure supports O(1) append and snoc operations on
-- lists, making it very useful for append-heavy uses (esp. left-nested
-- uses of ++), such as logging and pretty printing.
--
-- Here is an example using DList as the state type when printing a tree
-- with the Writer monad:
--
-- -- import Control.Monad.Writer -- import Data.DList -- -- data Tree a = Leaf a | Branch (Tree a) (Tree a) -- -- flatten_writer :: Tree x -> DList x -- flatten_writer = snd . runWriter . flatten -- where -- flatten (Leaf x) = tell (singleton x) -- flatten (Branch x y) = flatten x >> flatten y --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. -- --
-- >>> maybeToRight "default" (Just 12) -- Left 12 ---- --
-- >>> maybeToRight "default" Nothing -- Right "default" --maybeToLeft :: () => b -> Maybe a -> Either a b -- | Maybe get the Right side of an Either. -- --
-- rightToMaybe ≡ either (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. -- --
-- leftToMaybe ≡ either 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: -- --
-- whenRight ≡ forM_ ---- -- 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 -- | 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 -- | 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#, 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 -> Int -> Int -- | 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, 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 -> Int -> IO 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. class Hashable a -- | Return a hash value for the argument, using the given salt. -- -- The general contract of hashWithSalt is: -- --
-- 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 () -- | 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 -- | Retrieves a function of the current environment. asks :: MonadReader r m => (r -> a) -> m a -- | 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 -- | 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
-- | 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
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
-- | 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 :: forall k. () => k -> k -> Type -> Type -> Type
ContT :: ((a -> m r) -> m r) -> ContT a
[runContT] :: ContT a -> (a -> m r) -> m r
-- | 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
-- | Construct a continuation-passing computation from a function. (The
-- inverse of runCont)
cont :: () => ((a -> r) -> r) -> Cont r 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 result of a continuation-passing
-- computation.
--
--
mapCont :: () => (r -> r) -> Cont r a -> Cont r a
-- | 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 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 :: () => (m r -> m r) -> ContT r m a -> ContT r m a
-- | Apply a function to transform the continuation passed to a CPS
-- computation.
--
--
withContT :: () => ((b -> m r) -> a -> m r) -> ContT r m a -> ContT r m b
-- | A monad transformer that adds exceptions to other monads.
--
-- ExceptT constructs a monad parameterized over two things:
--
-- runExceptT (mapExceptT f m) = f -- (runExceptT m)
runReader (withReader f m) = runReader m -- . f
runReaderT (mapReaderT f m) = f . -- runReaderT m
runReaderT (withReaderT f m) = -- runReaderT m . f
evalStateT m s = liftM fst -- (runStateT m s)
execStateT m s = liftM snd -- (runStateT m s)
withStateT f m = modify f >> m
execWriter m = snd (runWriter -- m)
execWriterT m = liftM snd -- (runWriterT m)
runWriterT (mapWriterT f m) = f -- (runWriterT m)
-- cotambaraSum . uncotambaraSum ≡ id -- uncotambaraSum . cotambaraSum ≡ id --uncotambaraSum :: Profunctor q => (p :-> CotambaraSum q) -> p :-> q -- |
-- cotambaraSum . uncotambaraSum ≡ id -- uncotambaraSum . cotambaraSum ≡ id --cotambaraSum :: Cochoice p => (p :-> q) -> p :-> CotambaraSum q -- |
-- tambaraSum . untambaraSum ≡ id -- untambaraSum . tambaraSum ≡ id --untambaraSum :: Profunctor q => (p :-> TambaraSum q) -> p :-> q -- |
-- tambaraSum . untambaraSum ≡ id -- untambaraSum . tambaraSum ≡ id --tambaraSum :: 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 Left ≡ lmap 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 Right ≡ lmap 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 a b [runTambaraSum] :: TambaraSum 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 (p :: Type -> Type -> Type) a b y z x. () => (Either y z -> b) -> p x y -> (a -> Either x z) -> PastroSum p a b class Profunctor p => Cochoice (p :: Type -> Type -> Type) -- | Laws: -- --
-- unleft ≡ unright . 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 . unleft ≡ unleft . 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: -- --
-- unright ≡ unleft . 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 . unright ≡ unright . 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 (q :: Type -> Type -> Type) a b (r :: Type -> Type -> Type). 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 a b [runCopastroSum] :: CopastroSum a b -> forall (r :: Type -> Type -> Type). Cochoice r => (forall x y. () => p x y -> r x y) -> r a b -- |
-- cotambara . uncotambara ≡ id -- uncotambara . cotambara ≡ id --uncotambara :: Profunctor q => (p :-> Cotambara q) -> p :-> q -- |
-- cotambara . uncotambara ≡ id -- uncotambara . cotambara ≡ id --cotambara :: Costrong p => (p :-> q) -> p :-> Cotambara q -- |
-- pastro (unpastro f) ≡ f -- unpastro (pastro f) ≡ f --unpastro :: () => (Pastro p :-> q) -> p :-> q -- |
-- pastro (unpastro f) ≡ f -- unpastro (pastro f) ≡ f --pastro :: Strong q => (p :-> q) -> Pastro p :-> q -- |
-- tambara (untambara f) ≡ f -- untambara (tambara f) ≡ f --untambara :: Profunctor q => (p :-> Tambara q) -> p :-> q -- |
-- tambara (untambara f) ≡ f -- untambara (tambara f) ≡ f --tambara :: 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 fst ≡ rmap 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 snd ≡ rmap 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 a b [runTambara] :: Tambara 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 (p :: Type -> Type -> Type) a b y z x. () => ((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: -- --
-- unfirst ≡ unsecond . 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: -- --
-- unsecond ≡ unfirst . 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 (q :: Type -> Type -> Type) a b (r :: Type -> Type -> Type). 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 a b [runCopastro] :: Copastro a b -> forall (r :: Type -> Type -> Type). Costrong r => (forall x y. () => p x y -> r x y) -> r a b -- | 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 id ≡ id ---- -- If you supply lmap and rmap, ensure: -- --
-- lmap id ≡ id -- rmap id ≡ id ---- -- 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. -- --
-- rmap ≡ dimap 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 --(#.) :: (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 --(.#) :: (Profunctor p, Coercible b a) => p b c -> q a b -> p a c infixr 9 #. infixl 8 .# -- | 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: -- --
pure id <*> v = v
pure f <*> pure x = pure (f x)
u <*> pure y = pure ($y) <*> -- u
(.) <$> u <*> v <*> w = u -- <*> (v <*> w)
-- 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 a [getSelectA] :: SelectA 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 a [getSelectM] :: SelectM 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 -- | 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 bifoldMap1Default :: (Bitraversable1 t, Semigroup m) => (a -> m) -> (b -> m) -> t a b -> m foldMap1Default :: (Traversable1 f, Semigroup m) => (a -> m) -> f a -> m class (Bifoldable1 t, Bitraversable t) => Bitraversable1 (t :: Type -> Type -> 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 -> 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 -- | 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 () class Foldable t => Foldable1 (t :: Type -> 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 -> Type -> Type) bifold1 :: (Bifoldable1 t, Semigroup m) => t m m -> m bifoldMap1 :: (Bifoldable1 t, Semigroup m) => (a -> m) -> (b -> m) -> t a b -> m -- | Category sans id class Semigroupoid (c :: k -> k -> Type) o :: Semigroupoid c => c j k1 -> c i j -> c i k1 newtype WrappedCategory (k2 :: k -> k1 -> Type) (a :: k) (b :: k1) :: forall k k1. () => k -> k1 -> Type -> k -> k1 -> Type WrapCategory :: k2 a b -> WrappedCategory [unwrapCategory] :: WrappedCategory -> k2 a b newtype Semi m (a :: k) (b :: k1) :: forall k k1. () => Type -> k -> k1 -> Type Semi :: m -> Semi m [getSemi] :: Semi m -> m -- | 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 -- | 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 <<..>> -- | 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 -- distributon" law of MonadPlus with respect to <.>: -- --
-- <.> right-distributes over <!>: (a <!> b) <.> c = (a <.> c) <!> (b <.> c) ---- -- But Maybe, IO, Either a, -- ErrorT e m, and STM satisfy the alternative -- "left catch" law instead: -- --
-- pure a <!> b = pure a ---- -- However, this variation 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 (-<-) :: 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 -<< -- | 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 -- | 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 a [unwrapApplicative] :: WrappedApplicative 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 a [runMaybeApply] :: MaybeApply 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 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 -- | 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)) -- | 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 () -- | Returns True if the supplied TQueue is empty. isEmptyTQueue :: () => TQueue a -> STM Bool -- | Put a data item back onto a channel, where it will be the next item -- read. unGetTQueue :: () => TQueue a -> a -> STM () -- | A version of peekTQueue which does not retry. Instead it -- returns Nothing if no value is available. tryPeekTQueue :: () => TQueue a -> STM (Maybe a) -- | Get the next value from the TQueue without removing it, -- retrying if the channel is empty. peekTQueue :: () => TQueue a -> STM a -- | Efficiently read the entire contents of a TQueue into a list. -- This function never retries. flushTQueue :: () => TQueue a -> STM [a] -- | A version of readTQueue which does not retry. Instead it -- returns Nothing if no value is available. tryReadTQueue :: () => TQueue a -> STM (Maybe a) -- | Read the next value from the TQueue. readTQueue :: () => TQueue a -> STM a -- | Write a value to a TQueue. writeTQueue :: () => TQueue a -> a -> STM () -- | 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) -- | TQueue is an abstract type representing an unbounded FIFO -- channel. data TQueue 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 -- | Swap the contents of a TMVar for a new value. swapTMVar :: () => TMVar a -> a -> STM a -- | A version of readTMVar which does not retry. Instead it returns -- Nothing if no value is available. tryReadTMVar :: () => TMVar a -> STM (Maybe 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 -- | 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 -- | Put a value into a TMVar. If the TMVar is currently -- full, putTMVar will retry. putTMVar :: () => TMVar a -> a -> STM () -- | 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) -- | 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 -- | 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) -- | 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) -- | 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 -- | 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) -- | Returns True if the supplied TChan is empty. isEmptyTChan :: () => TChan a -> STM Bool -- | Put a data item back onto a channel, where it will be the next item -- read. unGetTChan :: () => TChan a -> a -> STM () -- | 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) -- | A version of peekTChan which does not retry. Instead it returns -- Nothing if no value is available. tryPeekTChan :: () => TChan a -> STM (Maybe a) -- | Get the next value from the TChan without removing it, -- retrying if the channel is empty. peekTChan :: () => TChan a -> STM a -- | A version of readTChan which does not retry. Instead it returns -- Nothing if no value is available. tryReadTChan :: () => TChan a -> STM (Maybe a) -- | Read the next value from the TChan. readTChan :: () => TChan a -> STM a -- | Write a value to a TChan. writeTChan :: () => TChan a -> a -> STM () -- | 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) -- | 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) -- | TChan is an abstract type representing an unbounded FIFO -- channel. data TChan a -- | 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 -- | Return the length of a TBQueue. lengthTBQueue :: () => TBQueue a -> STM Natural -- | 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 peekTBQueue which does not retry. Instead it -- returns Nothing if no value is available. tryPeekTBQueue :: () => TBQueue a -> STM (Maybe a) -- | Get the next value from the TBQueue without removing it, -- retrying if the channel is empty. peekTBQueue :: () => TBQueue a -> STM a -- | Efficiently read the entire contents of a TBQueue into a list. -- This function never retries. flushTBQueue :: () => TBQueue a -> STM [a] -- | A version of readTBQueue which does not retry. Instead it -- returns Nothing if no value is available. tryReadTBQueue :: () => TBQueue a -> STM (Maybe a) -- | Read the next value from the TBQueue. readTBQueue :: () => TBQueue a -> STM a -- | Write a value to a TBQueue; blocks if the queue is full. writeTBQueue :: () => TBQueue a -> a -> STM () -- | 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) -- | TBQueue is an abstract type representing a bounded FIFO -- channel. data TBQueue a -- | A space efficient, packed, unboxed Unicode text type. data Text -- | Substitute various time-related information for each %-code in the -- string, as per formatCharacter. -- -- The general form is -- %<modifier><width><specifier>, where -- <modifier> and <width> are optional. -- --
-- 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 822 sec. 5: "UT", "GMT", "EST", "EDT", "CST", "CDT", "MST", "MDT", -- "PST", "PDT". Note that the parsing functions will regardless parse -- single-letter military time-zones and +HHMM format. defaultTimeLocale :: TimeLocale 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] -- | Get the UT1 time of a local time on a particular meridian (in degrees, -- positive is East). localTimeToUT1 :: Rational -> LocalTime -> UniversalTime -- | 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 local time of a UTC time in a time zone. utcToLocalTime :: TimeZone -> UTCTime -> LocalTime -- | 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 fraction of a day since midnight given a time of day. timeOfDayToDayFraction :: TimeOfDay -> Rational -- | Get the time of day given the fraction of a day since midnight. dayFractionToTimeOfDay :: Rational -> TimeOfDay -- | Get the time since midnight for a given time of day. timeOfDayToTime :: TimeOfDay -> DiffTime -- | 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 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 time of day in UTC to a time of day in some timezone, -- together with a day adjustment. utcToLocalTimeOfDay :: TimeZone -> TimeOfDay -> (Integer, TimeOfDay) makeTimeOfDayValid :: Int -> Int -> Pico -> Maybe TimeOfDay -- | Hour twelve midday :: TimeOfDay -- | Hour zero midnight :: TimeOfDay -- | 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 -- | Get the current time-zone. getCurrentTimeZone :: IO TimeZone -- | Get the local time-zone for a given time (varying as per summertime -- adjustments). getTimeZone :: UTCTime -> IO TimeZone -- | The UTC time zone. utc :: TimeZone -- | Text representing the offset of this timezone, such as "-0800" or -- "+0400" (like %z in formatTime). timeZoneOffsetString :: TimeZone -> String -- | Text representing the offset of this timezone, such as "-0800" or -- "+0400" (like %z in formatTime), with arbitrary padding. timeZoneOffsetString' :: Maybe Char -> TimeZone -> String -- | Create a nameless non-summer timezone for this number of hours. hoursToTimeZone :: Int -> TimeZone -- | Create a nameless non-summer timezone for this number of minutes. minutesToTimeZone :: Int -> TimeZone -- | 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 -- | diffUTCTime a b = a - b diffUTCTime :: UTCTime -> UTCTime -> NominalDiffTime -- | addUTCTime a b = a + b addUTCTime :: NominalDiffTime -> UTCTime -> UTCTime -- | Get the current UTCTime from the system clock. getCurrentTime :: IO UTCTime -- | 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 -- | The resolution of getSystemTime, getCurrentTime, -- getPOSIXTime getTime_resolution :: DiffTime -- | One day in NominalDiffTime. nominalDay :: NominalDiffTime -- | This is a length of time, as measured by UTC. Conversion functions -- will treat it as seconds. It has a precision of 10^-12 s. 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 -- | Get the number of picoseconds in a DiffTime. diffTimeToPicoseconds :: DiffTime -> Integer -- | Create a DiffTime from a number of picoseconds. picosecondsToDiffTime :: Integer -> DiffTime -- | Create a DiffTime which represents an integral number of -- seconds. secondsToDiffTime :: Integer -> DiffTime -- | This is a length of time, as measured by a clock. Conversion functions -- will treat it as seconds. It has a precision of 10^-12 s. data DiffTime -- | 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 -- | The number of days in a given month according to the proleptic -- Gregorian calendar. First argument is year, second is month. gregorianMonthLength :: Integer -> Int -> Int -- | Show in ISO 8601 format (yyyy-mm-dd) showGregorian :: Day -> String -- | Convert from proleptic Gregorian calendar. First argument is year, -- second month number (1-12), third day (1-31). Invalid values will -- return Nothing fromGregorianValid :: Integer -> Int -> Int -> Maybe Day -- | Convert from proleptic Gregorian calendar. First argument is year, -- second month number (1-12), third day (1-31). Invalid values will be -- clipped to the correct range, month first, then day. fromGregorian :: Integer -> Int -> Int -> Day -- | Convert to proleptic Gregorian calendar. First element of result is -- year, second month number (1-12), third day (1-31). toGregorian :: Day -> (Integer, Int, Int) -- | Is this year a leap year according to the proleptic Gregorian -- calendar? isLeapYear :: Integer -> Bool diffDays :: Day -> Day -> Integer addDays :: Integer -> Day -> Day -- | 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 -- | Lift a pass operation to the new monad. liftPass :: Monad m => Pass w m (Maybe a) -> Pass w (MaybeT m) a -- | Lift a listen operation to the new monad. liftListen :: Monad m => Listen w m (Maybe a) -> Listen w (MaybeT m) a -- | Lift a catchE operation to the new monad. liftCatch :: () => Catch e m (Maybe a) -> Catch e (MaybeT m) a -- | Lift a callCC operation to the new monad. liftCallCC :: () => CallCC m (Maybe a) (Maybe b) -> CallCC (MaybeT m) a b -- | Convert a ExceptT computation to MaybeT, discarding the -- value of any exception. exceptToMaybeT :: Functor m => ExceptT e m a -> MaybeT m a -- | Convert a MaybeT computation to ExceptT, with a default -- exception value. maybeToExceptT :: 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 -- | 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 a [runMaybeT] :: MaybeT a -> m (Maybe a) -- | Constructor for computations in the exception monad. (The inverse of -- runExcept). except :: () => Either e a -> Except e a -- | 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 -- | 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 :: Monad m => ContT r m r -> ContT r' m r -- | The result of running a CPS computation with return as the -- final continuation. -- -- evalContT :: Monad m => ContT r m r -> m r -- | reset m delimits the continuation of any shift -- inside m. -- -- reset :: () => Cont r r -> Cont r' 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 -- | The UUID type. A Random instance is provided which produces -- version 4 UUIDs as specified in RFC 4122. The Storable and -- Binary instances are compatible with RFC 4122, storing the -- fields in network order as 16 bytes. 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 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