-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | A super-simple web server framework -- -- A super-simple, easy to use web server framework inspired by Scotty. -- The goals of the project are: (1) Be easy to use (2) Allow graceful -- exception handling (3) Parse request parameters easily and in a typed -- manner. @package webby @version 0.3.1 module Prelude -- | Append two lists, i.e., -- --
--   [x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn]
--   [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]
--   
-- -- If the first list is not finite, the result is the first list. (++) :: () => [a] -> [a] -> [a] infixr 5 ++ -- | The value of seq a b is bottom if a is bottom, and -- otherwise equal to b. In other words, it evaluates the first -- argument a to weak head normal form (WHNF). seq is -- usually introduced to improve performance by avoiding unneeded -- laziness. -- -- A note on evaluation order: the expression seq a b does -- not guarantee that a will be evaluated before -- b. The only guarantee given by seq is that the both -- a and b will be evaluated before seq -- returns a value. In particular, this means that b may be -- evaluated before a. If you need to guarantee a specific order -- of evaluation, you must use the function pseq from the -- "parallel" package. seq :: () => 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)] -- | 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 -- | 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] -- | 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
--   
-- --

Examples

-- -- Common uses of guard include conditionally signaling an error -- in an error monad and conditionally rejecting the current choice in an -- Alternative-based parser. -- -- As an example of signaling an error in the error monad Maybe, -- consider a safe division function safeDiv x y that returns -- Nothing when the denominator y is zero and -- Just (x `div` y) otherwise. For example: -- --
--   >>> safeDiv 4 0
--   Nothing
--   >>> safeDiv 4 2
--   Just 2
--   
-- -- A definition of safeDiv using guards, but not guard: -- --
--   safeDiv :: Int -> Int -> Maybe Int
--   safeDiv x y | y /= 0    = Just (x `div` y)
--               | otherwise = Nothing
--   
-- -- A definition of safeDiv using guard and Monad -- do-notation: -- --
--   safeDiv :: Int -> Int -> Maybe Int
--   safeDiv x y = do
--     guard (y /= 0)
--     return (x `div` y)
--   
guard :: Alternative f => Bool -> f () -- | The IsList class and its methods are intended to be used in -- conjunction with the OverloadedLists extension. class IsList l -- | The fromList function constructs the structure l from -- the given list of Item l fromList :: IsList l => [Item l] -> l -- | The fromListN function takes the input list's length as a hint. -- Its behaviour should be equivalent to fromList. The hint can be -- used to construct the structure l more efficiently compared -- to fromList. If the given hint does not equal to the input -- list's length the behaviour of fromListN is not specified. fromListN :: IsList l => Int -> [Item l] -> l -- | 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. -- --

Examples

-- -- A common use of join is to run an IO computation -- returned from an STM transaction, since STM transactions -- can't perform IO directly. Recall that -- --
--   atomically :: STM a -> IO a
--   
-- -- is used to run STM transactions atomically. So, by specializing -- the types of atomically and join to -- --
--   atomically :: STM (IO b) -> IO (IO b)
--   join       :: IO (IO b)  -> IO b
--   
-- -- we can compose them as -- --
--   join . atomically :: STM (IO b) -> IO b
--   
-- -- to run an STM transaction and the IO action it returns. join :: Monad m => m (m a) -> m a -- | The Bounded class is used to name the upper and lower limits of -- a type. Ord is not a superclass of Bounded since types -- that are not totally ordered may also have upper and lower bounds. -- -- The Bounded class may be derived for any enumeration type; -- minBound is the first constructor listed in the data -- declaration and maxBound is the last. Bounded may also -- be derived for single-constructor datatypes whose constituent types -- are in Bounded. class Bounded a minBound :: Bounded a => a maxBound :: Bounded a => a -- | Class Enum defines operations on sequentially ordered types. -- -- The enumFrom... methods are used in Haskell's translation of -- arithmetic sequences. -- -- Instances of Enum may be derived for any enumeration type -- (types whose constructors have no fields). The nullary constructors -- are assumed to be numbered left-to-right by fromEnum from -- 0 through n-1. See Chapter 10 of the Haskell -- Report for more details. -- -- For any type that is an instance of class Bounded as well as -- Enum, the following should hold: -- -- -- --
--   enumFrom     x   = enumFromTo     x maxBound
--   enumFromThen x y = enumFromThenTo x y bound
--     where
--       bound | fromEnum y >= fromEnum x = maxBound
--             | otherwise                = minBound
--   
class Enum a -- | the successor of a value. For numeric types, succ adds 1. succ :: Enum a => a -> a -- | the predecessor of a value. For numeric types, pred subtracts -- 1. pred :: Enum a => a -> a -- | Convert from an Int. toEnum :: Enum a => Int -> a -- | Convert to an Int. It is implementation-dependent what -- fromEnum returns when applied to a value that is too large to -- fit in an Int. fromEnum :: Enum a => a -> Int -- | Used in Haskell's translation of [n..] with [n..] = -- enumFrom n, a possible implementation being enumFrom n = n : -- enumFrom (succ n). For example: -- -- enumFrom :: Enum a => a -> [a] -- | Used in Haskell's translation of [n,n'..] with [n,n'..] = -- enumFromThen n n', a possible implementation being -- enumFromThen n n' = n : n' : worker (f x) (f x n'), -- worker s v = v : worker s (s v), x = fromEnum n' - -- fromEnum n and f n y | n > 0 = f (n - 1) (succ y) | n < -- 0 = f (n + 1) (pred y) | otherwise = y For example: -- -- enumFromThen :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n..m] with [n..m] = -- enumFromTo n m, a possible implementation being enumFromTo n -- m | n <= m = n : enumFromTo (succ n) m | otherwise = []. For -- example: -- -- enumFromTo :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n,n'..m] with [n,n'..m] -- = enumFromThenTo n n' m, a possible implementation being -- enumFromThenTo n n' m = worker (f x) (c x) n m, x = -- fromEnum n' - fromEnum n, c x = bool (>=) ((x -- 0) f n y | n > 0 = f (n - 1) (succ y) | n < 0 = f (n + -- 1) (pred y) | otherwise = y and worker s c v m | c v m = v : -- worker s c (s v) m | otherwise = [] For example: -- -- enumFromThenTo :: Enum a => a -> a -> a -> [a] -- | The Eq class defines equality (==) and inequality -- (/=). All the basic datatypes exported by the Prelude -- are instances of Eq, and Eq may be derived for any -- datatype whose constituents are also instances of Eq. -- -- The Haskell Report defines no laws for Eq. However, == -- is customarily expected to implement an equivalence relationship where -- two values comparing equal are indistinguishable by "public" -- functions, with a "public" function being one not allowing to see -- implementation details. For example, for a type representing -- non-normalised natural numbers modulo 100, a "public" function doesn't -- make the difference between 1 and 201. It is expected to have the -- following properties: -- -- -- -- Minimal complete definition: either == or /=. class Eq a (==) :: Eq a => a -> a -> Bool (/=) :: Eq a => a -> a -> Bool infix 4 == infix 4 /= -- | Trigonometric and hyperbolic functions and related functions. -- -- The Haskell Report defines no laws for Floating. However, -- '(+)', '(*)' and exp are customarily expected to define an -- exponential field and have the following properties: -- -- class Fractional a => Floating a pi :: Floating a => a exp :: Floating a => a -> a sqrt :: Floating a => a -> a (**) :: Floating a => a -> a -> a logBase :: Floating a => a -> a -> a sin :: Floating a => a -> a cos :: Floating a => a -> a tan :: Floating a => a -> a asin :: Floating a => a -> a acos :: Floating a => a -> a atan :: Floating a => a -> a sinh :: Floating a => a -> a cosh :: Floating a => a -> a tanh :: Floating a => a -> a asinh :: Floating a => a -> a acosh :: Floating a => a -> a atanh :: Floating a => a -> a infixr 8 ** -- | Fractional numbers, supporting real division. -- -- The Haskell Report defines no laws for Fractional. However, -- '(+)' and '(*)' are customarily expected to define a division ring and -- have the following properties: -- -- -- -- Note that it isn't customarily expected that a type instance of -- Fractional implement a field. However, all instances in -- base do. class Num a => Fractional a -- | fractional division (/) :: Fractional a => a -> a -> a -- | reciprocal fraction recip :: Fractional a => a -> a -- | Conversion from a Rational (that is Ratio -- Integer). A floating literal stands for an application of -- fromRational to a value of type Rational, so such -- literals have type (Fractional a) => a. fromRational :: Fractional a => Rational -> a infixl 7 / -- | Integral numbers, supporting integer division. -- -- The Haskell Report defines no laws for Integral. However, -- Integral instances are customarily expected to define a -- Euclidean domain and have the following properties for the 'div'/'mod' -- and 'quot'/'rem' pairs, given suitable Euclidean functions f -- and g: -- -- -- -- An example of a suitable Euclidean function, for Integer's -- instance, is abs. class (Real a, Enum a) => Integral a -- | integer division truncated toward zero quot :: Integral a => a -> a -> a -- | integer remainder, satisfying -- --
--   (x `quot` y)*y + (x `rem` y) == x
--   
rem :: Integral a => a -> a -> a -- | integer division truncated toward negative infinity div :: Integral a => a -> a -> a -- | integer modulus, satisfying -- --
--   (x `div` y)*y + (x `mod` y) == x
--   
mod :: Integral a => a -> a -> a -- | simultaneous quot and rem quotRem :: Integral a => a -> a -> (a, a) -- | simultaneous div and mod divMod :: Integral a => a -> a -> (a, a) -- | conversion to Integer toInteger :: Integral a => a -> Integer infixl 7 `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 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: -- -- -- -- Note that it isn't customarily expected that a type instance of -- both Num and Ord implement an ordered ring. Indeed, in -- base only Integer and Rational do. class Num a (+) :: Num a => a -> a -> a (-) :: Num a => a -> a -> a (*) :: Num a => a -> a -> a -- | Unary negation. negate :: Num a => a -> a -- | Absolute value. abs :: Num a => a -> a -- | Sign of a number. The functions abs and signum should -- satisfy the law: -- --
--   abs x * signum x == x
--   
-- -- For real numbers, the signum is either -1 (negative), -- 0 (zero) or 1 (positive). signum :: Num a => a -> a -- | Conversion from an Integer. An integer literal represents the -- application of the function fromInteger to the appropriate -- value of type Integer, so such literals have type -- (Num a) => a. fromInteger :: Num a => Integer -> a infixl 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: -- -- -- -- Note that the following operator interactions are expected to hold: -- --
    --
  1. x >= y = y <= x
  2. --
  3. x < y = x <= y && x /= y
  4. --
  5. x > y = y < x
  6. --
  7. x < y = compare x y == LT
  8. --
  9. x > y = compare x y == GT
  10. --
  11. x == y = compare x y == EQ
  12. --
  13. min x y == if x <= y then x else y = True
  14. --
  15. max x y == if x >= y then x else y = True
  16. --
-- -- Minimal complete definition: either compare or <=. -- Using compare can be more efficient for complex types. class Eq a => Ord a compare :: Ord a => a -> a -> Ordering (<) :: Ord a => a -> a -> Bool (<=) :: Ord a => a -> a -> Bool (>) :: Ord a => a -> a -> Bool (>=) :: Ord a => a -> a -> Bool max :: Ord a => a -> a -> a min :: Ord a => a -> a -> a infix 4 >= infix 4 > infix 4 < infix 4 <= -- | Parsing of Strings, producing values. -- -- Derived instances of Read make the following assumptions, which -- derived instances of Show obey: -- -- -- -- For example, given the declarations -- --
--   infixr 5 :^:
--   data Tree a =  Leaf a  |  Tree a :^: Tree a
--   
-- -- the derived instance of Read in Haskell 2010 is equivalent to -- --
--   instance (Read a) => Read (Tree a) where
--   
--           readsPrec d r =  readParen (d > app_prec)
--                            (\r -> [(Leaf m,t) |
--                                    ("Leaf",s) <- lex r,
--                                    (m,t) <- readsPrec (app_prec+1) s]) r
--   
--                         ++ readParen (d > up_prec)
--                            (\r -> [(u:^:v,w) |
--                                    (u,s) <- readsPrec (up_prec+1) r,
--                                    (":^:",t) <- lex s,
--                                    (v,w) <- readsPrec (up_prec+1) t]) r
--   
--             where app_prec = 10
--                   up_prec = 5
--   
-- -- Note that right-associativity of :^: is unused. -- -- The derived instance in GHC is equivalent to -- --
--   instance (Read a) => Read (Tree a) where
--   
--           readPrec = parens $ (prec app_prec $ do
--                                    Ident "Leaf" <- lexP
--                                    m <- step readPrec
--                                    return (Leaf m))
--   
--                        +++ (prec up_prec $ do
--                                    u <- step readPrec
--                                    Symbol ":^:" <- lexP
--                                    v <- step readPrec
--                                    return (u :^: v))
--   
--             where app_prec = 10
--                   up_prec = 5
--   
--           readListPrec = readListPrecDefault
--   
-- -- Why do both readsPrec and readPrec exist, and why does -- GHC opt to implement readPrec in derived Read instances -- instead of readsPrec? The reason is that readsPrec is -- based on the ReadS type, and although ReadS is mentioned -- in the Haskell 2010 Report, it is not a very efficient parser data -- structure. -- -- readPrec, on the other hand, is based on a much more efficient -- ReadPrec datatype (a.k.a "new-style parsers"), but its -- definition relies on the use of the RankNTypes language -- extension. Therefore, readPrec (and its cousin, -- readListPrec) are marked as GHC-only. Nevertheless, it is -- recommended to use readPrec instead of readsPrec -- whenever possible for the efficiency improvements it brings. -- -- As mentioned above, derived Read instances in GHC will -- implement readPrec instead of readsPrec. The default -- implementations of readsPrec (and its cousin, readList) -- will simply use readPrec under the hood. If you are writing a -- Read instance by hand, it is recommended to write it like so: -- --
--   instance Read T where
--     readPrec     = ...
--     readListPrec = readListPrecDefault
--   
class Read a class (Num a, Ord a) => Real a -- | the rational equivalent of its real argument with full precision toRational :: Real a => a -> Rational -- | Extracting components of fractions. class (Real a, Fractional a) => RealFrac a -- | The function properFraction takes a real fractional number -- x and returns a pair (n,f) such that x = -- n+f, and: -- -- -- -- The default definitions of the ceiling, floor, -- truncate and round functions are in terms of -- properFraction. properFraction :: (RealFrac a, Integral b) => a -> (b, a) -- | truncate x returns the integer nearest x -- between zero and x truncate :: (RealFrac a, Integral b) => a -> b -- | round x returns the nearest integer to x; the -- even integer if x is equidistant between two integers round :: (RealFrac a, Integral b) => a -> b -- | ceiling x returns the least integer not less than -- x ceiling :: (RealFrac a, Integral b) => a -> b -- | floor x returns the greatest integer not greater than -- x floor :: (RealFrac a, Integral b) => a -> b -- | Conversion of values to readable Strings. -- -- Derived instances of Show have the following properties, which -- are compatible with derived instances of Read: -- -- -- -- For example, given the declarations -- --
--   infixr 5 :^:
--   data Tree a =  Leaf a  |  Tree a :^: Tree a
--   
-- -- the derived instance of Show is equivalent to -- --
--   instance (Show a) => Show (Tree a) where
--   
--          showsPrec d (Leaf m) = showParen (d > app_prec) $
--               showString "Leaf " . showsPrec (app_prec+1) m
--            where app_prec = 10
--   
--          showsPrec d (u :^: v) = showParen (d > up_prec) $
--               showsPrec (up_prec+1) u .
--               showString " :^: "      .
--               showsPrec (up_prec+1) v
--            where up_prec = 5
--   
-- -- Note that right-associativity of :^: is ignored. For example, -- -- class Show a -- | The class Typeable allows a concrete representation of a type -- to be calculated. class Typeable (a :: k) -- | When a value is bound in do-notation, the pattern on the left -- hand side of <- might not match. In this case, this class -- provides a function to recover. -- -- A Monad without a MonadFail instance may only be used in -- conjunction with pattern that always match, such as newtypes, tuples, -- data types with only a single data constructor, and irrefutable -- patterns (~pat). -- -- Instances of MonadFail should satisfy the following law: -- fail s should be a left zero for >>=, -- --
--   fail s >>= f  =  fail s
--   
-- -- If your Monad is also MonadPlus, a popular definition -- is -- --
--   fail _ = mzero
--   
class Monad m => MonadFail (m :: Type -> Type) fail :: MonadFail m => String -> m a -- | Class for string-like datastructures; used by the overloaded string -- extension (-XOverloadedStrings in GHC). class IsString a fromString :: IsString a => String -> a -- | A functor with application, providing operations to -- -- -- -- A minimal complete definition must include implementations of -- pure and of either <*> or liftA2. If it -- defines both, then they must behave the same as their default -- definitions: -- --
--   (<*>) = liftA2 id
--   
-- --
--   liftA2 f x y = f <$> x <*> y
--   
-- -- Further, any definition must satisfy the following: -- -- -- -- The other methods have the following default definitions, which may be -- overridden with equivalent specialized implementations: -- -- -- -- As a consequence of these laws, the Functor instance for -- f will satisfy -- -- -- -- It may be useful to note that supposing -- --
--   forall x y. p (q x y) = f x . g y
--   
-- -- it follows from the above that -- --
--   liftA2 p (liftA2 q u v) = liftA2 f u . liftA2 g v
--   
-- -- If f is also a Monad, it should satisfy -- -- -- -- (which implies that pure and <*> satisfy the -- applicative functor laws). class Functor f => Applicative (f :: Type -> Type) -- | Lift a value. pure :: Applicative f => a -> f a -- | Sequential application. -- -- A few functors support an implementation of <*> that is -- more efficient than the default one. (<*>) :: 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 -- | 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 -- | 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 -- | Functors representing data structures that can be traversed from left -- to right. -- -- A definition of traverse must satisfy the following laws: -- -- -- -- A definition of sequenceA must satisfy the following laws: -- -- -- -- where an applicative transformation is a function -- --
--   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: -- -- class (Functor t, Foldable t) => Traversable (t :: Type -> Type) -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and collect the results. For a version that -- ignores the results see traverse_. traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b) -- | Evaluate each action in the structure from left to right, and collect -- the results. For a version that ignores the results see -- sequenceA_. sequenceA :: (Traversable t, Applicative f) => t (f a) -> f (t a) -- | Map each element of a structure to a monadic action, evaluate these -- actions from left to right, and collect the results. For a version -- that ignores the results see mapM_. mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b) -- | Evaluate each monadic action in the structure from left to right, and -- collect the results. For a version that ignores the results see -- sequence_. sequence :: (Traversable t, Monad m) => t (m a) -> m (t a) -- | Representable types of kind *. This class is derivable in GHC -- with the DeriveGeneric flag on. -- -- A Generic instance must satisfy the following laws: -- --
--   from . toid
--   to . fromid
--   
class Generic a -- | This class gives the integer associated with a type-level natural. -- There are instances of the class for every concrete literal: 0, 1, 2, -- etc. class KnownNat (n :: Nat) class IsLabel (x :: Symbol) a fromLabel :: IsLabel x a => 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: -- -- -- -- The method names refer to the monoid of lists under concatenation, but -- there are many other instances. -- -- Some types can be viewed as a monoid in more than one way, e.g. both -- addition and multiplication on numbers. In such cases we often define -- newtypes and make those instances of Monoid, e.g. -- Sum and Product. -- -- NOTE: Semigroup is a superclass of Monoid since -- base-4.11.0.0. class Semigroup a => Monoid a -- | Identity of mappend mempty :: Monoid a => a -- | An associative operation -- -- NOTE: This method is redundant and has the default -- implementation mappend = '(<>)' since -- base-4.11.0.0. mappend :: Monoid a => a -> a -> a -- | Fold a list using the monoid. -- -- For most types, the default definition for mconcat will be -- used, but the function is included in the class definition so that an -- optimized version can be provided for specific types. mconcat :: Monoid a => [a] -> a data Bool False :: Bool True :: Bool -- | The character type Char is an enumeration whose values -- represent Unicode (or equivalently ISO/IEC 10646) code points (i.e. -- characters, see http://www.unicode.org/ for details). This set -- extends the ISO 8859-1 (Latin-1) character set (the first 256 -- characters), which is itself an extension of the ASCII character set -- (the first 128 characters). A character literal in Haskell has type -- Char. -- -- To convert a Char to or from the corresponding Int value -- defined by Unicode, use toEnum and fromEnum from the -- Enum class respectively (or equivalently ord and -- chr). data Char -- | Double-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- double-precision type. data Double D# :: Double# -> Double -- | Single-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- single-precision type. data Float F# :: Float# -> Float -- | A fixed-precision integer type with at least the range [-2^29 .. -- 2^29-1]. The exact range for a given implementation can be -- determined by using minBound and maxBound from the -- Bounded class. data Int -- | 8-bit signed integer type data Int8 -- | 16-bit signed integer type data Int16 -- | 32-bit signed integer type data Int32 -- | 64-bit signed integer type data Int64 -- | Invariant: Jn# and Jp# are used iff value doesn't fit in -- S# -- -- Useful properties resulting from the invariants: -- -- data Integer -- | Type representing arbitrary-precision non-negative integers. -- --
--   >>> 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 -- | 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 -- | The Either type represents values with two possibilities: a -- value of type Either a b is either Left -- a or Right b. -- -- The Either type is sometimes used to represent a value which is -- either correct or an error; by convention, the Left constructor -- is used to hold an error value and the Right constructor is -- used to hold a correct value (mnemonic: "right" also means "correct"). -- --

Examples

-- -- The type Either String Int is the type -- of values which can be either a String or an Int. The -- Left constructor can be used only on Strings, and the -- Right constructor can be used only on Ints: -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> s
--   Left "foo"
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> n
--   Right 3
--   
--   >>> :type s
--   s :: Either String Int
--   
--   >>> :type n
--   n :: Either String Int
--   
-- -- The fmap from our Functor instance will ignore -- Left values, but will apply the supplied function to values -- contained in a Right: -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> fmap (*2) s
--   Left "foo"
--   
--   >>> fmap (*2) n
--   Right 6
--   
-- -- The Monad instance for Either allows us to chain -- together multiple actions which may fail, and fail overall if any of -- the individual steps failed. First we'll write a function that can -- either parse an Int from a Char, or fail. -- --
--   >>> import Data.Char ( digitToInt, isDigit )
--   
--   >>> :{
--       let parseEither :: Char -> Either String Int
--           parseEither c
--             | isDigit c = Right (digitToInt c)
--             | otherwise = Left "parse error"
--   
--   >>> :}
--   
-- -- The following should work, since both '1' and '2' -- can be parsed as Ints. -- --
--   >>> :{
--       let parseMultiple :: Either String Int
--           parseMultiple = do
--             x <- parseEither '1'
--             y <- parseEither '2'
--             return (x + y)
--   
--   >>> :}
--   
-- --
--   >>> parseMultiple
--   Right 3
--   
-- -- But the following should fail overall, since the first operation where -- we attempt to parse 'm' as an Int will fail: -- --
--   >>> :{
--       let parseMultiple :: Either String Int
--           parseMultiple = do
--             x <- parseEither 'm'
--             y <- parseEither '2'
--             return (x + y)
--   
--   >>> :}
--   
-- --
--   >>> parseMultiple
--   Left "parse error"
--   
data Either a b Left :: a -> Either a b Right :: b -> Either a b -- | The kind of types with values. For example Int :: Type. type Type = Type -- | The kind of constraints, like Show a data Constraint -- | (Kind) This is the kind of type-level natural numbers. data Nat -- | Comparison of type-level naturals, as a function. type family CmpNat (a :: Nat) (b :: Nat) :: Ordering -- | 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) -- | CallStacks are a lightweight method of obtaining a partial -- call-stack at any point in the program. -- -- A function can request its call-site with the HasCallStack -- constraint. For example, we can define -- --
--   putStrLnWithCallStack :: HasCallStack => String -> IO ()
--   
-- -- as a variant of putStrLn that will get its call-site and -- print it, along with the string given as argument. We can access the -- call-stack inside putStrLnWithCallStack with -- callStack. -- --
--   putStrLnWithCallStack :: HasCallStack => String -> IO ()
--   putStrLnWithCallStack msg = do
--     putStrLn msg
--     putStrLn (prettyCallStack callStack)
--   
-- -- Thus, if we call putStrLnWithCallStack we will get a -- formatted call-stack alongside our string. -- --
--   >>> putStrLnWithCallStack "hello"
--   hello
--   CallStack (from HasCallStack):
--     putStrLnWithCallStack, called at <interactive>:2:1 in interactive:Ghci1
--   
-- -- GHC solves HasCallStack constraints in three steps: -- --
    --
  1. If there is a CallStack in scope -- i.e. the enclosing -- function has a HasCallStack constraint -- GHC will append the -- new call-site to the existing CallStack.
  2. --
  3. If there is no CallStack in scope -- e.g. in the GHCi -- session above -- and the enclosing definition does not have an -- explicit type signature, GHC will infer a HasCallStack -- constraint for the enclosing definition (subject to the monomorphism -- restriction).
  4. --
  5. If there is no CallStack in scope and the enclosing -- definition has an explicit type signature, GHC will solve the -- HasCallStack constraint for the singleton CallStack -- containing just the current call-site.
  6. --
-- -- CallStacks do not interact with the RTS and do not require -- compilation with -prof. On the other hand, as they are built -- up explicitly via the HasCallStack constraints, they will -- generally not contain as much information as the simulated call-stacks -- maintained by the RTS. -- -- A CallStack is a [(String, SrcLoc)]. The -- String is the name of function that was called, the -- SrcLoc is the call-site. The list is ordered with the most -- recently called function at the head. -- -- NOTE: The intrepid user may notice that HasCallStack is just an -- alias for an implicit parameter ?callStack :: CallStack. This -- is an implementation detail and should not be considered part -- of the CallStack API, we may decide to change the -- implementation in the future. data CallStack -- | 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 -- | An infix synonym for fmap. -- -- The name of this operator is an allusion to $. Note the -- similarities between their types: -- --
--    ($)  ::              (a -> b) ->   a ->   b
--   (<$>) :: Functor f => (a -> b) -> f a -> f b
--   
-- -- Whereas $ is function application, <$> is -- function application lifted over a Functor. -- --

Examples

-- -- Convert from a Maybe Int to a -- Maybe String using show: -- --
--   >>> show <$> Nothing
--   Nothing
--   
--   >>> show <$> Just 3
--   Just "3"
--   
-- -- Convert from an Either Int Int to -- an Either Int String using -- show: -- --
--   >>> show <$> Left 17
--   Left 17
--   
--   >>> show <$> Right 17
--   Right "17"
--   
-- -- Double each element of a list: -- --
--   >>> (*2) <$> [1,2,3]
--   [2,4,6]
--   
-- -- Apply even to the second element of a pair: -- --
--   >>> even <$> (2,2)
--   (2,True)
--   
(<$>) :: Functor f => (a -> b) -> f a -> f b infixl 4 <$> -- | 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: -- -- hashWithSalt :: Hashable a => Int -> a -> Int infixl 0 `hashWithSalt` -- | A space efficient, packed, unboxed Unicode text type. data Text -- | 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 -- | Function composition. (.) :: () => (b -> c) -> (a -> b) -> a -> c infixr 9 . -- | Identity function. -- --
--   id x = x
--   
id :: () => a -> 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 -- | A Map from keys k to values a. data Map k a -- | Haskell defines operations to read and write characters from and to -- files, represented by values of type Handle. Each value of -- this type is a handle: a record used by the Haskell run-time -- system to manage I/O with file system objects. A handle has at -- least the following properties: -- -- -- -- Most handles will also have a current I/O position indicating where -- the next input or output operation will occur. A handle is -- readable if it manages only input or both input and output; -- likewise, it is writable if it manages only output or both -- input and output. A handle is open when first allocated. Once -- it is closed it can no longer be used for either input or output, -- though an implementation cannot re-use its storage while references -- remain to it. Handles are in the Show and Eq classes. -- The string produced by showing a handle is system dependent; it should -- include enough information to identify the handle for debugging. A -- handle is equal according to == only to itself; no attempt is -- made to compare the internal state of different handles for equality. data Handle -- | A String is a list of characters. String constants in Haskell -- are values of type String. type String = [Char] -- | 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 boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a] boundedEnumFrom :: (Enum a, Bounded a) => a -> [a] maxInt :: Int minInt :: Int -- | 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 -- | 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 -- | A generalization of cycle to an arbitrary Semigroup. May -- fail to terminate for some values in some semigroups. cycle1 :: Semigroup m => m -> m -- | 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. data WrappedMonoid 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] -- | A bifunctor is a type constructor that takes two type arguments and is -- a functor in both arguments. That is, unlike with -- Functor, a type constructor such as Either does not need -- to be partially applied for a Bifunctor instance, and the -- methods in this class permit mapping functions over the Left -- value or the Right value, or both at the same time. -- -- Formally, the class Bifunctor represents a bifunctor from -- Hask -> Hask. -- -- Intuitively it is a bifunctor where both the first and second -- arguments are covariant. -- -- You can define a Bifunctor by either defining bimap or -- by defining both first and second. -- -- If you supply bimap, you should ensure that: -- --
--   bimap id idid
--   
-- -- If you supply first and second, ensure: -- --
--   first idid
--   second idid
--   
-- -- If you supply both, you should also ensure: -- --
--   bimap f g ≡ first f . second g
--   
-- -- These ensure by parametricity: -- --
--   bimap  (f . g) (h . i) ≡ bimap f h . bimap g i
--   first  (f . g) ≡ first  f . first  g
--   second (f . g) ≡ second f . second g
--   
class Bifunctor (p :: Type -> Type -> Type) -- | Map over both arguments at the same time. -- --
--   bimap f g ≡ first f . second g
--   
-- --

Examples

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

Examples

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

Examples

-- --
--   >>> second (+1) ('j', 3)
--   ('j',4)
--   
-- --
--   >>> second (+1) (Right 3)
--   Right 4
--   
second :: Bifunctor p => (b -> c) -> p a b -> p a c -- | Extract everything except the last element of the stream. init :: () => NonEmpty a -> [a] -- | Extract the last element of the stream. last :: () => NonEmpty a -> a -- | Extract the possibly-empty tail of the stream. tail :: () => NonEmpty a -> [a] -- | Extract the first element of the stream. head :: () => NonEmpty a -> a -- | nonEmpty efficiently turns a normal list into a NonEmpty -- stream, producing Nothing if the input is empty. nonEmpty :: () => [a] -> Maybe (NonEmpty a) -- | Get a string representation of the current execution stack state. showStackTrace :: IO (Maybe String) -- | Get a trace of the current execution stack state. -- -- Returns Nothing if stack trace support isn't available on -- host machine. getStackTrace :: IO (Maybe [Location]) -- | 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 -- | Direct MonadPlus equivalent of filter. -- --

Examples

-- -- The filter function is just mfilter specialized to the -- list monad: -- --
--   filter = ( mfilter :: (a -> Bool) -> [a] -> [a] )
--   
-- -- An example using mfilter with the Maybe monad: -- --
--   >>> mfilter odd (Just 1)
--   Just 1
--   >>> mfilter odd (Just 2)
--   Nothing
--   
mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a -- | 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] -- | 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. -- --

Examples

-- -- A common use of forever is to process input from network -- sockets, Handles, and channels (e.g. MVar and -- Chan). -- -- For example, here is how we might implement an echo server, -- using forever both to listen for client connections on a -- network socket and to echo client input on client connection handles: -- --
--   echoServer :: Socket -> IO ()
--   echoServer socket = forever $ do
--     client <- accept socket
--     forkFinally (echo client) (\_ -> hClose client)
--     where
--       echo :: Handle -> IO ()
--       echo client = forever $
--         hGetLine client >>= hPutStrLn client
--   
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] -- | 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) -- | One or none. optional :: Alternative f => f a -> f (Maybe a) -- | Lists, but with an Applicative functor based on zipping. newtype ZipList a ZipList :: [a] -> ZipList a [getZipList] :: ZipList a -> [a] -- | 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 &&& -- | Identity functor and monad. (a non-strict monad) newtype Identity a Identity :: a -> Identity a [runIdentity] :: Identity a -> a -- | withFile name mode act opens a file using -- openFile and passes the resulting handle to the computation -- act. The handle will be closed on exit from withFile, -- whether by normal termination or by raising an exception. If closing -- the handle raises an exception, then this exception will be raised by -- withFile rather than any exception raised by act. withFile :: () => FilePath -> IOMode -> (Handle -> IO r) -> IO r -- | A handle managing output to the Haskell program's standard error -- channel. stderr :: Handle -- | A handle managing input from the Haskell program's standard input -- channel. stdin :: Handle -- | Perform some computation without adding new entries to the -- CallStack. withFrozenCallStack :: HasCallStack => (HasCallStack -> a) -> a -- | Return the current CallStack. -- -- Does *not* include the call-site of callStack. callStack :: HasCallStack -> CallStack -- | 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 -- | Create a new TVar holding a value supplied newTVar :: () => a -> STM (TVar a) -- | A monad supporting atomic memory transactions. data STM a -- | Shared memory locations that support atomic memory transactions. data TVar a -- | A handle managing output to the Haskell program's standard output -- channel. stdout :: Handle -- | A mutable variable in the IO monad data IORef 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 -- | Pretty print a CallStack. prettyCallStack :: CallStack -> String -- | Pretty print a SrcLoc. prettySrcLoc :: SrcLoc -> String -- | 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 -- | 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 -- | 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. -- -- 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 -- | Maybe monoid returning the leftmost non-Nothing value. -- -- First a is isomorphic to Alt Maybe -- a, but precedes it historically. -- --
--   >>> getFirst (First (Just "hello") <> First Nothing <> First (Just "world"))
--   Just "hello"
--   
-- -- Use of this type is discouraged. Note the following equivalence: -- --
--   Data.Monoid.First x === Maybe (Data.Semigroup.First x)
--   
-- -- In addition to being equivalent in the structural sense, the two also -- have Monoid instances that behave the same. This type will be -- marked deprecated in GHC 8.8, and removed in GHC 8.10. Users are -- advised to use the variant from Data.Semigroup and wrap it in -- Maybe. newtype First a First :: Maybe a -> First a [getFirst] :: First a -> Maybe a -- | Maybe monoid returning the rightmost non-Nothing value. -- -- Last a is isomorphic to Dual (First -- a), and thus to Dual (Alt Maybe a) -- --
--   >>> getLast (Last (Just "hello") <> Last Nothing <> Last (Just "world"))
--   Just "world"
--   
-- -- Use of this type is discouraged. Note the following equivalence: -- --
--   Data.Monoid.Last x === Maybe (Data.Semigroup.Last x)
--   
-- -- In addition to being equivalent in the structural sense, the two also -- have Monoid instances that behave the same. This type will be -- marked deprecated in GHC 8.8, and removed in GHC 8.10. Users are -- advised to use the variant from Data.Semigroup and wrap it in -- Maybe. newtype Last a Last :: Maybe a -> Last a [getLast] :: Last a -> Maybe 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 -- | Monoid under <|>. newtype Alt (f :: k -> Type) (a :: k) :: forall k. () => k -> Type -> k -> Type Alt :: f a -> Alt [getAlt] :: Alt -> f a -- | Convert an integer into an unknown type-level natural. someNatVal :: Natural -> SomeNat natVal :: KnownNat n => proxy n -> Natural -- | This type represents unknown type-level natural numbers. data SomeNat [SomeNat] :: forall (n :: Nat). KnownNat n => Proxy n -> SomeNat -- | 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 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 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 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 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 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 -- | 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 -- | 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. -- --

Examples

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

Examples

-- -- Basic usage: -- --
--   >>> fromLeft 1 (Left 3)
--   3
--   
--   >>> fromLeft 1 (Right "foo")
--   1
--   
fromLeft :: () => a -> Either a b -> a -- | Return True if the given value is a Right-value, -- False otherwise. -- --

Examples

-- -- Basic usage: -- --
--   >>> isRight (Left "foo")
--   False
--   
--   >>> isRight (Right 3)
--   True
--   
-- -- Assuming a Left value signifies some sort of error, we can use -- isRight to write a very simple reporting function that only -- outputs "SUCCESS" when a computation has succeeded. -- -- This example shows how isRight might be used to avoid pattern -- matching when one does not care about the value contained in the -- constructor: -- --
--   >>> import Control.Monad ( when )
--   
--   >>> let report e = when (isRight e) $ putStrLn "SUCCESS"
--   
--   >>> report (Left "parse error")
--   
--   >>> report (Right 1)
--   SUCCESS
--   
isRight :: () => Either a b -> Bool -- | Return True if the given value is a Left-value, -- False otherwise. -- --

Examples

-- -- Basic usage: -- --
--   >>> isLeft (Left "foo")
--   True
--   
--   >>> isLeft (Right 3)
--   False
--   
-- -- Assuming a Left value signifies some sort of error, we can use -- isLeft to write a very simple error-reporting function that -- does absolutely nothing in the case of success, and outputs "ERROR" if -- any error occurred. -- -- This example shows how isLeft might be used to avoid pattern -- matching when one does not care about the value contained in the -- constructor: -- --
--   >>> import Control.Monad ( when )
--   
--   >>> let report e = when (isLeft e) $ putStrLn "ERROR"
--   
--   >>> report (Right 1)
--   
--   >>> report (Left "parse error")
--   ERROR
--   
isLeft :: () => Either a b -> Bool -- | Partitions a list of Either into two lists. All the Left -- elements are extracted, in order, to the first component of the -- output. Similarly the Right elements are extracted to the -- second component of the output. -- --

Examples

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

Examples

-- -- Basic usage: -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> rights list
--   [3,7]
--   
rights :: () => [Either a b] -> [b] -- | Extracts from a list of Either all the Left elements. -- All the Left elements are extracted in order. -- --

Examples

-- -- Basic usage: -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> lefts list
--   ["foo","bar","baz"]
--   
lefts :: () => [Either a b] -> [a] -- | Case analysis for the Either type. If the value is -- Left a, apply the first function to a; if it -- is Right b, apply the second function to b. -- --

Examples

-- -- We create two values of type Either String -- Int, one using the Left constructor and another -- using the Right constructor. Then we apply "either" the -- length function (if we have a String) or the -- "times-two" function (if we have an Int): -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> either length (*2) s
--   3
--   
--   >>> either length (*2) n
--   6
--   
either :: () => (a -> c) -> (b -> c) -> Either a b -> c -- |
--   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 -- | 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 -- | See openFile data IOMode ReadMode :: IOMode WriteMode :: IOMode AppendMode :: IOMode ReadWriteMode :: IOMode -- | Reverse order of bytes in Word64. byteSwap64 :: Word64 -> Word64 -- | Reverse order of bytes in Word32. byteSwap32 :: Word32 -> Word32 -- | Swap bytes in Word16. byteSwap16 :: Word16 -> Word16 -- | Bitwise "xor" xor :: Bits a => a -> a -> a infixl 6 `xor` -- | Case analysis for the Bool type. bool x y p -- evaluates to x when p is False, and evaluates -- to y when p is True. -- -- This is equivalent to if p then y else x; that is, one can -- think of it as an if-then-else construct with its arguments reordered. -- --

Examples

-- -- Basic usage: -- --
--   >>> bool "foo" "bar" True
--   "bar"
--   
--   >>> bool "foo" "bar" False
--   "foo"
--   
-- -- Confirm that bool x y p and if p then y else -- x are equivalent: -- --
--   >>> let p = True; x = "bar"; y = "foo"
--   
--   >>> bool x y p == if p then y else x
--   True
--   
--   >>> let p = False
--   
--   >>> bool x y p == if p then y else x
--   True
--   
bool :: () => a -> a -> Bool -> a -- | & 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 :: () => (b -> b -> c) -> (a -> b) -> a -> a -> c infixl 0 `on` -- | fix f is the least fixed point of the function -- f, i.e. the least defined x such that f x = -- x. -- -- For example, we can write the factorial function using direct -- recursion as -- --
--   >>> let fac n = if n <= 1 then 1 else n * fac (n-1) in fac 5
--   120
--   
-- -- This uses the fact that Haskell’s let introduces recursive -- bindings. We can rewrite this definition using fix, -- --
--   >>> fix (\rec n -> if n <= 1 then 1 else n * rec (n-1)) 5
--   120
--   
-- -- Instead of making a recursive call, we introduce a dummy parameter -- rec; when used within fix, this parameter then refers -- to fix' 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. -- --

Examples

-- -- Replace the contents of a Maybe Int with -- unit: -- --
--   >>> void Nothing
--   Nothing
--   
--   >>> void (Just 3)
--   Just ()
--   
-- -- Replace the contents of an Either Int -- Int with unit, resulting in an Either -- Int '()': -- --
--   >>> void (Left 8675309)
--   Left 8675309
--   
--   >>> void (Right 8675309)
--   Right ()
--   
-- -- Replace every element of a list with unit: -- --
--   >>> void [1,2,3]
--   [(),(),()]
--   
-- -- Replace the second element of a pair with unit: -- --
--   >>> void (1,2)
--   (1,())
--   
-- -- Discard the result of an IO action: -- --
--   >>> mapM print [1,2]
--   1
--   2
--   [(),()]
--   
--   >>> void $ mapM print [1,2]
--   1
--   2
--   
void :: Functor f => f a -> f () -- | Flipped version of <$. -- --

Examples

-- -- Replace the contents of a Maybe Int with a -- constant String: -- --
--   >>> Nothing $> "foo"
--   Nothing
--   
--   >>> Just 90210 $> "foo"
--   Just "foo"
--   
-- -- Replace the contents of an Either Int -- Int with a constant String, resulting in an -- Either Int String: -- --
--   >>> Left 8675309 $> "foo"
--   Left 8675309
--   
--   >>> Right 8675309 $> "foo"
--   Right "foo"
--   
-- -- Replace each element of a list with a constant String: -- --
--   >>> [1,2,3] $> "foo"
--   ["foo","foo","foo"]
--   
-- -- Replace the second element of a pair with a constant String: -- --
--   >>> (1,2) $> "foo"
--   (1,"foo")
--   
($>) :: Functor f => f a -> b -> f b infixl 4 $> -- | Flipped version of <$>. -- --
--   (<&>) = flip fmap
--   
-- --

Examples

-- -- Apply (+1) to a list, a Just and a Right: -- --
--   >>> Just 2 <&> (+1)
--   Just 3
--   
-- --
--   >>> [1,2,3] <&> (+1)
--   [2,3,4]
--   
-- --
--   >>> Right 3 <&> (+1)
--   Right 4
--   
(<&>) :: Functor f => f a -> (a -> b) -> f b infixl 1 <&> -- | 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 -- | 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 -- | The toEnum method restricted to the type Char. chr :: Int -> Char -- | 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]) -- | 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)] -- | 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]) -- | 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 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] -- | 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] -- | 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] -- | The mapMaybe function is a version of map which can -- throw out elements. In particular, the functional argument returns -- something of type Maybe b. If this is Nothing, -- no element is added on to the result list. If it is Just -- b, then b is included in the result list. -- --

Examples

-- -- Using mapMaybe f x is a shortcut for -- catMaybes $ map f x in most cases: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> let readMaybeInt = readMaybe :: String -> Maybe Int
--   
--   >>> mapMaybe readMaybeInt ["1", "Foo", "3"]
--   [1,3]
--   
--   >>> catMaybes $ map readMaybeInt ["1", "Foo", "3"]
--   [1,3]
--   
-- -- If we map the Just constructor, the entire list should be -- returned: -- --
--   >>> mapMaybe Just [1,2,3]
--   [1,2,3]
--   
mapMaybe :: () => (a -> Maybe b) -> [a] -> [b] -- | The catMaybes function takes a list of Maybes and -- returns a list of all the Just values. -- --

Examples

-- -- Basic usage: -- --
--   >>> catMaybes [Just 1, Nothing, Just 3]
--   [1,3]
--   
-- -- When constructing a list of Maybe values, catMaybes can -- be used to return all of the "success" results (if the list is the -- result of a map, then mapMaybe would be more -- appropriate): -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
--   [Just 1,Nothing,Just 3]
--   
--   >>> catMaybes $ [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
--   [1,3]
--   
catMaybes :: () => [Maybe a] -> [a] -- | The listToMaybe function returns Nothing on an empty -- list or Just a where a is the first element -- of the list. -- --

Examples

-- -- Basic usage: -- --
--   >>> listToMaybe []
--   Nothing
--   
-- --
--   >>> listToMaybe [9]
--   Just 9
--   
-- --
--   >>> listToMaybe [1,2,3]
--   Just 1
--   
-- -- Composing maybeToList with listToMaybe should be the -- identity on singleton/empty lists: -- --
--   >>> maybeToList $ listToMaybe [5]
--   [5]
--   
--   >>> maybeToList $ listToMaybe []
--   []
--   
-- -- But not on lists with more than one element: -- --
--   >>> maybeToList $ listToMaybe [1,2,3]
--   [1]
--   
listToMaybe :: () => [a] -> Maybe a -- | The maybeToList function returns an empty list when given -- Nothing or a singleton list when not given Nothing. -- --

Examples

-- -- Basic usage: -- --
--   >>> maybeToList (Just 7)
--   [7]
--   
-- --
--   >>> maybeToList Nothing
--   []
--   
-- -- One can use maybeToList to avoid pattern matching when combined -- with a function that (safely) works on lists: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> sum $ maybeToList (readMaybe "3")
--   3
--   
--   >>> sum $ maybeToList (readMaybe "")
--   0
--   
maybeToList :: () => Maybe a -> [a] -- | The fromMaybe function takes a default value and and -- Maybe value. If the Maybe is Nothing, it returns -- the default values; otherwise, it returns the value contained in the -- Maybe. -- --

Examples

-- -- Basic usage: -- --
--   >>> fromMaybe "" (Just "Hello, World!")
--   "Hello, World!"
--   
-- --
--   >>> fromMaybe "" Nothing
--   ""
--   
-- -- Read an integer from a string using readMaybe. If we fail to -- parse an integer, we want to return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> fromMaybe 0 (readMaybe "5")
--   5
--   
--   >>> fromMaybe 0 (readMaybe "")
--   0
--   
fromMaybe :: () => a -> Maybe a -> a -- | The isNothing function returns True iff its argument is -- Nothing. -- --

Examples

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

Examples

-- -- Basic usage: -- --
--   >>> isJust (Just 3)
--   True
--   
-- --
--   >>> isJust (Just ())
--   True
--   
-- --
--   >>> isJust Nothing
--   False
--   
-- -- Only the outer constructor is taken into consideration: -- --
--   >>> isJust (Just Nothing)
--   True
--   
isJust :: () => Maybe a -> Bool -- | The maybe function takes a default value, a function, and a -- Maybe value. If the Maybe value is Nothing, the -- function returns the default value. Otherwise, it applies the function -- to the value inside the Just and returns the result. -- --

Examples

-- -- Basic usage: -- --
--   >>> maybe False odd (Just 3)
--   True
--   
-- --
--   >>> maybe False odd Nothing
--   False
--   
-- -- Read an integer from a string using readMaybe. If we succeed, -- return twice the integer; that is, apply (*2) to it. If -- instead we fail to parse an integer, return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> maybe 0 (*2) (readMaybe "5")
--   10
--   
--   >>> maybe 0 (*2) (readMaybe "")
--   0
--   
-- -- Apply show to a Maybe Int. If we have Just -- n, we want to show the underlying Int n. But if -- we have Nothing, we return the empty string instead of (for -- example) "Nothing": -- --
--   >>> maybe "" show (Just 5)
--   "5"
--   
--   >>> maybe "" show Nothing
--   ""
--   
maybe :: () => b -> (a -> b) -> Maybe a -> b -- | Swap the components of a pair. swap :: () => (a, b) -> (b, a) -- | uncurry converts a curried function to a function on pairs. -- --

Examples

-- --
--   >>> uncurry (+) (1,2)
--   3
--   
-- --
--   >>> uncurry ($) (show, 1)
--   "1"
--   
-- --
--   >>> map (uncurry max) [(1,2), (3,4), (6,8)]
--   [2,4,8]
--   
uncurry :: () => (a -> b -> c) -> (a, b) -> c -- | curry converts an uncurried function to a curried function. -- --

Examples

-- --
--   >>> curry fst 1 2
--   1
--   
curry :: () => ((a, b) -> c) -> a -> b -> c -- | An MVar (pronounced "em-var") is a synchronising variable, used -- for communication between concurrent threads. It can be thought of as -- a box, which may be empty or full. data MVar a -- | the same as flip (-). -- -- Because - is treated specially in the Haskell grammar, -- (- e) is not a section, but an application of -- prefix negation. However, (subtract -- exp) is equivalent to the disallowed section. subtract :: Num a => a -> a -> a -- | Returns a [String] representing the current call stack. This -- can be useful for debugging. -- -- The implementation uses the call-stack simulation maintained by the -- profiler, so it only works if the program was compiled with -- -prof and contains suitable SCC annotations (e.g. by using -- -fprof-auto). Otherwise, the list returned is likely to be -- empty or uninformative. currentCallStack :: IO [String] -- | asTypeOf is a type-restricted version of const. It is -- usually used as an infix operator, and its typing forces its first -- argument (which is usually overloaded) to have the same type as the -- second. asTypeOf :: () => a -> a -> a -- | Strict (call-by-value) application operator. It takes a function and -- an argument, evaluates the argument to weak head normal form (WHNF), -- then calls the function with that value. ($!) :: () => (a -> b) -> a -> b infixr 0 $! -- | flip f takes its (first) two arguments in the reverse -- order of f. -- --
--   >>> flip (++) "hello" "world"
--   "worldhello"
--   
flip :: () => (a -> b -> c) -> b -> a -> c -- | The fromEnum method restricted to the type Char. ord :: Char -> Int -- | 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 -- | A variant of <*> with the arguments reversed. (<**>) :: Applicative f => f a -> f (a -> b) -> f b infixl 4 <**> -- | Non-empty (and non-strict) list type. data NonEmpty a (:|) :: a -> [a] -> NonEmpty a infixr 5 :| -- | Extract a list of call-sites from the CallStack. -- -- The list is ordered by most recent call. getCallStack :: CallStack -> [([Char], SrcLoc)] -- | Request a CallStack. -- -- NOTE: The implicit parameter ?callStack :: CallStack is an -- implementation detail and should not be considered part of the -- CallStack API, we may decide to change the implementation in -- the future. type HasCallStack = ?callStack :: CallStack -- | 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 state transformer monad parameterized by: -- -- -- -- The return function leaves the state unchanged, while -- >>= uses the final state of the first computation as -- the initial state of the second. newtype StateT s (m :: Type -> Type) a StateT :: (s -> m (a, s)) -> StateT s a [runStateT] :: StateT s a -> s -> m (a, s) -- | The reader monad transformer, which adds a read-only environment to -- the given monad. -- -- The return function ignores the environment, while -- >>= passes the inherited environment to both -- subcomputations. newtype ReaderT r (m :: k -> Type) (a :: k) :: forall k. () => Type -> k -> Type -> k -> Type ReaderT :: (r -> m a) -> ReaderT r [runReaderT] :: ReaderT r -> r -> m a -- | The parameterizable maybe monad, obtained by composing an arbitrary -- monad with the Maybe monad. -- -- Computations are actions that may produce a value or exit. -- -- The return function yields a computation that produces that -- value, while >>= sequences two subcomputations, exiting -- if either computation does. newtype MaybeT (m :: Type -> Type) a MaybeT :: m (Maybe a) -> MaybeT a [runMaybeT] :: MaybeT a -> m (Maybe a) -- | A monad transformer that adds exceptions to other monads. -- -- ExceptT constructs a monad parameterized over two things: -- -- -- -- The return function yields a computation that produces the -- given value, while >>= sequences two subcomputations, -- exiting on the first exception. newtype ExceptT e (m :: Type -> Type) a ExceptT :: m (Either e a) -> ExceptT e a -- | The Resource transformer. This transformer keeps track of all -- registered actions, and calls them upon exit (via -- runResourceT). Actions may be registered via -- register, or resources may be allocated atomically via -- allocate. allocate corresponds closely to -- bracket. -- -- Releasing may be performed before exit via the release -- function. This is a highly recommended optimization, as it will ensure -- that scarce resources are freed early. Note that calling -- release will deregister the action, so that a release action -- will only ever be called once. -- -- Since 0.3.0 data ResourceT (m :: Type -> Type) a -- | Lift a ResourceT IO action into the current Monad. -- -- Since 0.4.0 liftResourceT :: MonadResource m => ResourceT IO a -> m a -- | Unwrap a ResourceT transformer, and call all registered release -- actions. -- -- Note that there is some reference counting involved due to -- resourceForkIO. If multiple threads are sharing the same -- collection of resources, only the last call to runResourceT -- will deallocate the resources. -- -- NOTE Since version 1.2.0, this function will throw a -- ResourceCleanupException if any of the cleanup functions throw -- an exception. runResourceT :: MonadUnliftIO m => ResourceT m a -> m a -- | The class of monad transformers. Instances should satisfy the -- following laws, which state that lift is a monad -- transformation: -- -- class MonadTrans (t :: Type -> Type -> Type -> Type) -- | Lift a computation from the argument monad to the constructed monad. lift :: (MonadTrans t, Monad m) => m a -> t m a -- | A map of integers to values a. data IntMap a -- | A set of integers. data IntSet -- | General-purpose finite sequences. data Seq a -- | A set of values a. data Set a -- | a variant of deepseq that is useful in some circumstances: -- --
--   force x = x `deepseq` x
--   
-- -- force x fully evaluates x, and then returns it. Note -- that force x only performs evaluation when the value of -- force x itself is demanded, so essentially it turns shallow -- evaluation into deep evaluation. -- -- force can be conveniently used in combination with -- ViewPatterns: -- --
--   {-# LANGUAGE BangPatterns, ViewPatterns #-}
--   import Control.DeepSeq
--   
--   someFun :: ComplexData -> SomeResult
--   someFun (force -> !arg) = {- 'arg' will be fully evaluated -}
--   
-- -- Another useful application is to combine force with -- evaluate in order to force deep evaluation relative to other -- IO operations: -- --
--   import Control.Exception (evaluate)
--   import Control.DeepSeq
--   
--   main = do
--     result <- evaluate $ force $ pureComputation
--     {- 'result' will be fully evaluated at this point -}
--     return ()
--   
-- -- Finally, here's an exception safe variant of the readFile' -- example: -- --
--   readFile' :: FilePath -> IO String
--   readFile' fn = bracket (openFile fn ReadMode) hClose $ \h ->
--                          evaluate . force =<< hGetContents h
--   
force :: NFData a => a -> a -- | 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 '()'. -- --

Generic NFData deriving

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

Compatibility with previous deepseq versions

-- -- Prior to version 1.4.0.0, the default implementation of the rnf -- method was defined as -- --
--   rnf a = seq a ()
--   
-- -- However, starting with deepseq-1.4.0.0, the default -- implementation is based on DefaultSignatures allowing for -- more accurate auto-derived NFData instances. If you need the -- previously used exact default rnf method implementation -- semantics, use -- --
--   instance NFData Colour where rnf x = seq x ()
--   
-- -- or alternatively -- --
--   instance NFData Colour where rnf = rwhnf
--   
-- -- or -- --
--   {-# LANGUAGE BangPatterns #-}
--   instance NFData Colour where rnf !_ = ()
--   
rnf :: NFData a => a -> () -- | Output a showable value (instance of Show) by turning it into -- Text. sh :: Show a => Format r (a -> r) -- | Output a strict text. st :: () => Format r (Text -> r) -- | Render an integral e.g. 123 -> "123", 0 -> "0". d :: Integral a => Format r (a -> r) -- | Output a lazy text. t :: () => Format r (Text -> r) -- | Run the formatter and return a strict Text value. sformat :: () => Format Text a -> a -- | Run the formatter and return a lazy Text value. format :: () => Format Text a -> a -- | Concatenate two formatters. -- -- formatter1 % formatter2 is a formatter that accepts arguments -- for formatter1 and formatter2 and concatenates their -- results. For example -- --
--   format1 :: Format r (Text -> r)
--   format1 = "Person's name is " % text
--   
-- --
--   format2 :: Format r r
--   format2 = ", "
--   
-- --
--   format3 :: Format r (Int -> r)
--   format3 = "age is " % hex
--   
-- --
--   myFormat :: Formatter r (Text -> Int -> r)
--   myFormat = format1 % format2 % format3
--   
-- -- Notice how the argument types of format1 and format3 -- are gathered into the type of myFormat. -- -- (This is actually the composition operator for Format's -- Category instance, but that is (at present) inconvenient to use -- with regular Prelude. So this function is provided as a -- convenience.) (%) :: () => Format r a -> Format r' r -> Format r' a infixr 9 % -- | Like encodePathSegments, but without the initial slash. encodePathSegmentsRelative :: [Text] -> Builder -- | HTTP 2.0 http20 :: HttpVersion -- | HTTP 1.1 http11 :: HttpVersion -- | HTTP 1.0 http10 :: HttpVersion -- | HTTP 0.9 http09 :: HttpVersion -- | HTTP Version. -- -- Note that the Show instance is intended merely for debugging. data HttpVersion HttpVersion :: !Int -> !Int -> HttpVersion [httpMajor] :: HttpVersion -> !Int [httpMinor] :: HttpVersion -> !Int -- | Types which can, and commonly are, converted to Query are in -- this class. -- -- You can use lists of simple key value pairs, with ByteString -- (strict, or lazy: ByteString), Text, or String as -- the key/value types. You can also have the value type lifted into a -- Maybe to support keys without values; and finally it is possible to -- put each pair into a Maybe for key-value pairs that aren't always -- present. class QueryLike a -- | Convert to Query. toQuery :: QueryLike a => a -> Query -- | Convert PartialEscapeQuery to a Builder. renderQueryBuilderPartialEscape :: Bool -> PartialEscapeQuery -> Builder -- | Convert PartialEscapeQuery to ByteString. renderQueryPartialEscape :: Bool -> PartialEscapeQuery -> ByteString -- | Decode a whole path (path segments + query). decodePath :: ByteString -> ([Text], Query) -- | Encode a whole path (path segments + query). encodePath :: [Text] -> Query -> Builder -- | Extract whole path (path segments + query) from a RFC 2616 -- Request-URI. -- --
--   >>> extractPath "/path"
--   "/path"
--   
-- --
--   >>> extractPath "http://example.com:8080/path"
--   "/path"
--   
-- --
--   >>> extractPath "http://example.com"
--   "/"
--   
-- --
--   >>> extractPath ""
--   "/"
--   
extractPath :: ByteString -> ByteString -- | Parse a list of path segments from a valid URL fragment. decodePathSegments :: ByteString -> [Text] -- | Encodes a list of path segments into a valid URL fragment. -- -- This function takes the following three steps: -- -- -- -- For example: -- --
--   encodePathSegments [\"foo\", \"bar\", \"baz\"]
--   
-- -- "/foo/bar/baz" -- --
--   encodePathSegments [\"foo bar\", \"baz\/bin\"]
--   
-- -- "/foo%20bar/baz%2Fbin" -- --
--   encodePathSegments [\"שלום\"]
--   
-- -- "/%D7%A9%D7%9C%D7%95%D7%9D" -- -- Huge thanks to Jeremy Shaw who created the original implementation of -- this function in web-routes and did such thorough research to -- determine all correct escaping procedures. encodePathSegments :: [Text] -> Builder -- | Percent-decoding. urlDecode :: Bool -> ByteString -> ByteString -- | Percent-encoding for URLs. urlEncode :: Bool -> ByteString -> ByteString -- | Percent-encoding for URLs (using Builder). urlEncodeBuilder :: Bool -> ByteString -> Builder -- | Parse SimpleQuery from a ByteString. parseSimpleQuery :: ByteString -> SimpleQuery -- | Split out the query string into a list of keys and values. A few -- importants points: -- -- parseQuery :: ByteString -> Query -- | Convert SimpleQuery to ByteString. renderSimpleQuery :: Bool -> SimpleQuery -> ByteString -- | Convert Query to ByteString. renderQuery :: Bool -> Query -> ByteString -- | Convert Query to a Builder. renderQueryBuilder :: Bool -> Query -> Builder -- | Convert SimpleQuery to Query. simpleQueryToQuery :: SimpleQuery -> Query -- | Parse QueryText from a ByteString. See parseQuery -- for details. parseQueryText :: ByteString -> QueryText -- | Convert Query to QueryText (leniently decoding the -- UTF-8). queryToQueryText :: Query -> QueryText -- | Convert QueryText to a Builder. renderQueryText :: Bool -> QueryText -> Builder -- | Convert QueryText to Query. queryTextToQuery :: QueryText -> Query -- | Query item type QueryItem = (ByteString, Maybe ByteString) -- | Query. -- -- General form: a=b&c=d, but if the value is Nothing, it -- becomes a&c=d. type Query = [QueryItem] -- | Like Query, but with Text instead of ByteString -- (UTF8-encoded). type QueryText = [(Text, Maybe Text)] -- | Simplified Query item type without support for parameter-less items. type SimpleQueryItem = (ByteString, ByteString) -- | Simplified Query type without support for parameter-less items. type SimpleQuery = [SimpleQueryItem] -- | For some URIs characters must not be URI encoded, e.g. '+' or -- ':' in -- q=a+language:haskell+created:2009-01-01..2009-02-01&sort=stars -- The character list unreservedPI instead of unreservedQS would solve -- this. But we explicitly decide what part to encode. This is mandatory -- when searching for '+': q=%2B+language:haskell. data EscapeItem QE :: ByteString -> EscapeItem QN :: ByteString -> EscapeItem -- | Query item type PartialEscapeQueryItem = (ByteString, [EscapeItem]) -- | Query with some chars that should not be escaped. -- -- General form: a=b&c=d:e+f&g=h type PartialEscapeQuery = [PartialEscapeQueryItem] -- | Server Error class statusIsServerError :: Status -> Bool -- | Client Error class statusIsClientError :: Status -> Bool -- | Redirection class statusIsRedirection :: Status -> Bool -- | Successful class statusIsSuccessful :: Status -> Bool -- | Informational class statusIsInformational :: Status -> Bool -- | Network Authentication Required 511 (RFC 6585) networkAuthenticationRequired511 :: Status -- | Network Authentication Required 511 (RFC 6585) status511 :: Status -- | HTTP Version Not Supported 505 httpVersionNotSupported505 :: Status -- | HTTP Version Not Supported 505 status505 :: Status -- | Gateway Timeout 504 gatewayTimeout504 :: Status -- | Gateway Timeout 504 status504 :: Status -- | Service Unavailable 503 serviceUnavailable503 :: Status -- | Service Unavailable 503 status503 :: Status -- | Bad Gateway 502 badGateway502 :: Status -- | Bad Gateway 502 status502 :: Status -- | Not Implemented 501 notImplemented501 :: Status -- | Not Implemented 501 status501 :: Status -- | Internal Server Error 500 internalServerError500 :: Status -- | Internal Server Error 500 status500 :: Status -- | Request Header Fields Too Large 431 (RFC 6585) requestHeaderFieldsTooLarge431 :: Status -- | Request Header Fields Too Large 431 (RFC 6585) status431 :: Status -- | Too Many Requests 429 (RFC 6585) tooManyRequests429 :: Status -- | Too Many Requests 429 (RFC 6585) status429 :: Status -- | Precondition Required 428 (RFC 6585) preconditionRequired428 :: Status -- | Precondition Required 428 (RFC 6585) status428 :: Status -- | Unprocessable Entity 422 (RFC 4918) unprocessableEntity422 :: Status -- | Unprocessable Entity 422 (RFC 4918) status422 :: Status -- | I'm a teapot 418 imATeapot418 :: Status -- | I'm a teapot 418 status418 :: Status -- | Expectation Failed 417 expectationFailed417 :: Status -- | Expectation Failed 417 status417 :: Status -- | Requested Range Not Satisfiable 416 requestedRangeNotSatisfiable416 :: Status -- | Requested Range Not Satisfiable 416 status416 :: Status -- | Unsupported Media Type 415 unsupportedMediaType415 :: Status -- | Unsupported Media Type 415 status415 :: Status -- | Request-URI Too Long 414 requestURITooLong414 :: Status -- | Request-URI Too Long 414 status414 :: Status -- | Request Entity Too Large 413 requestEntityTooLarge413 :: Status -- | Request Entity Too Large 413 status413 :: Status -- | Precondition Failed 412 preconditionFailed412 :: Status -- | Precondition Failed 412 status412 :: Status -- | Length Required 411 lengthRequired411 :: Status -- | Length Required 411 status411 :: Status -- | Gone 410 gone410 :: Status -- | Gone 410 status410 :: Status -- | Conflict 409 conflict409 :: Status -- | Conflict 409 status409 :: Status -- | Request Timeout 408 requestTimeout408 :: Status -- | Request Timeout 408 status408 :: Status -- | Proxy Authentication Required 407 proxyAuthenticationRequired407 :: Status -- | Proxy Authentication Required 407 status407 :: Status -- | Not Acceptable 406 notAcceptable406 :: Status -- | Not Acceptable 406 status406 :: Status -- | Method Not Allowed 405 methodNotAllowed405 :: Status -- | Method Not Allowed 405 status405 :: Status -- | Not Found 404 notFound404 :: Status -- | Not Found 404 status404 :: Status -- | Forbidden 403 forbidden403 :: Status -- | Forbidden 403 status403 :: Status -- | Payment Required 402 paymentRequired402 :: Status -- | Payment Required 402 status402 :: Status -- | Unauthorized 401 unauthorized401 :: Status -- | Unauthorized 401 status401 :: Status -- | Bad Request 400 badRequest400 :: Status -- | Bad Request 400 status400 :: Status -- | Permanent Redirect 308 permanentRedirect308 :: Status -- | Permanent Redirect 308 status308 :: Status -- | Temporary Redirect 307 temporaryRedirect307 :: Status -- | Temporary Redirect 307 status307 :: Status -- | Use Proxy 305 useProxy305 :: Status -- | Use Proxy 305 status305 :: Status -- | Not Modified 304 notModified304 :: Status -- | Not Modified 304 status304 :: Status -- | See Other 303 seeOther303 :: Status -- | See Other 303 status303 :: Status -- | Found 302 found302 :: Status -- | Found 302 status302 :: Status -- | Moved Permanently 301 movedPermanently301 :: Status -- | Moved Permanently 301 status301 :: Status -- | Multiple Choices 300 multipleChoices300 :: Status -- | Multiple Choices 300 status300 :: Status -- | Partial Content 206 partialContent206 :: Status -- | Partial Content 206 status206 :: Status -- | Reset Content 205 resetContent205 :: Status -- | Reset Content 205 status205 :: Status -- | No Content 204 noContent204 :: Status -- | No Content 204 status204 :: Status -- | Non-Authoritative Information 203 nonAuthoritative203 :: Status -- | Non-Authoritative Information 203 status203 :: Status -- | Accepted 202 accepted202 :: Status -- | Accepted 202 status202 :: Status -- | Created 201 created201 :: Status -- | Created 201 status201 :: Status -- | OK 200 ok200 :: Status -- | OK 200 status200 :: Status -- | Switching Protocols 101 switchingProtocols101 :: Status -- | Switching Protocols 101 status101 :: Status -- | Continue 100 continue100 :: Status -- | Continue 100 status100 :: Status -- | Create a Status from status code and message. mkStatus :: Int -> ByteString -> Status -- | HTTP Status. -- -- Only the statusCode is used for comparisons. -- -- Please use mkStatus to create status codes from code and -- message, or the Enum instance or the status code constants -- (like ok200). There might be additional record members in the -- future. -- -- Note that the Show instance is only for debugging. data Status Status :: Int -> ByteString -> Status [statusCode] :: Status -> Int [statusMessage] :: Status -> ByteString -- | Convert a StdMethod to a ByteString. renderStdMethod :: StdMethod -> Method -- | Convert an algebraic method to a ByteString. renderMethod :: Either ByteString StdMethod -> Method -- | Convert a method ByteString to a StdMethod if -- possible. parseMethod :: Method -> Either ByteString StdMethod -- | HTTP Method constants. methodPatch :: Method -- | HTTP Method constants. methodOptions :: Method -- | HTTP Method constants. methodConnect :: Method -- | HTTP Method constants. methodTrace :: Method -- | HTTP Method constants. methodDelete :: Method -- | HTTP Method constants. methodPut :: Method -- | HTTP Method constants. methodHead :: Method -- | HTTP Method constants. methodPost :: Method -- | HTTP Method constants. methodGet :: Method -- | HTTP method (flat string type). type Method = ByteString -- | HTTP standard method (as defined by RFC 2616, and PATCH which is -- defined by RFC 5789). data StdMethod GET :: StdMethod POST :: StdMethod HEAD :: StdMethod PUT :: StdMethod DELETE :: StdMethod TRACE :: StdMethod CONNECT :: StdMethod OPTIONS :: StdMethod PATCH :: StdMethod -- | Parse the value of a Range header into a ByteRanges. -- --
--   >>> parseByteRanges "error"
--   Nothing
--   
--   >>> parseByteRanges "bytes=0-499"
--   Just [ByteRangeFromTo 0 499]
--   
--   >>> parseByteRanges "bytes=500-999"
--   Just [ByteRangeFromTo 500 999]
--   
--   >>> parseByteRanges "bytes=-500"
--   Just [ByteRangeSuffix 500]
--   
--   >>> parseByteRanges "bytes=9500-"
--   Just [ByteRangeFrom 9500]
--   
--   >>> parseByteRanges "bytes=0-0,-1"
--   Just [ByteRangeFromTo 0 0,ByteRangeSuffix 1]
--   
--   >>> parseByteRanges "bytes=500-600,601-999"
--   Just [ByteRangeFromTo 500 600,ByteRangeFromTo 601 999]
--   
--   >>> parseByteRanges "bytes=500-700,601-999"
--   Just [ByteRangeFromTo 500 700,ByteRangeFromTo 601 999]
--   
parseByteRanges :: ByteString -> Maybe ByteRanges renderByteRanges :: ByteRanges -> ByteString renderByteRangesBuilder :: ByteRanges -> Builder renderByteRange :: ByteRange -> ByteString renderByteRangeBuilder :: ByteRange -> Builder -- | HTTP Header names according to -- https://tools.ietf.org/html/rfc6265#section-4 hCookie :: HeaderName -- | HTTP Header names according to -- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html hUserAgent :: HeaderName -- | HTTP Header names according to -- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html hServer :: HeaderName -- | HTTP Header names according to -- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html hReferer :: HeaderName -- | HTTP Header names according to -- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html hRange :: HeaderName -- | HTTP Header names according to -- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html hLocation :: HeaderName -- | HTTP Header names according to -- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html hLastModified :: HeaderName -- | HTTP Header names according to -- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html hIfRange :: HeaderName -- | HTTP Header names according to -- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html hIfModifiedSince :: HeaderName -- | HTTP Header names according to -- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html hDate :: HeaderName -- | HTTP Header names according to -- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html hContentType :: HeaderName -- | HTTP Header names according to -- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html hContentMD5 :: HeaderName -- | HTTP Header names according to -- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html hContentLength :: HeaderName -- | HTTP Header names according to -- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html hContentEncoding :: HeaderName -- | HTTP Header names according to -- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html hConnection :: HeaderName -- | HTTP Header names according to -- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html hCacheControl :: HeaderName -- | HTTP Header names according to -- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html hAuthorization :: HeaderName -- | HTTP Header names according to -- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html hAcceptLanguage :: HeaderName -- | HTTP Header names according to -- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html hAccept :: HeaderName -- | Header type Header = (HeaderName, ByteString) -- | Header name type HeaderName = CI ByteString -- | Request Headers type RequestHeaders = [Header] -- | Response Headers type ResponseHeaders = [Header] -- | RFC 2616 Byte range (individual). -- -- Negative indices are not allowed! data ByteRange ByteRangeFrom :: !Integer -> ByteRange ByteRangeFromTo :: !Integer -> !Integer -> ByteRange ByteRangeSuffix :: !Integer -> ByteRange -- | RFC 2616 Byte ranges (set). type ByteRanges = [ByteRange] -- | The trivial monad transformer, which maps a monad to an equivalent -- monad. data IdentityT (f :: k -> Type) (a :: k) :: forall k. () => k -> Type -> k -> Type -- | Gets specific component of the state, using a projection function -- supplied. gets :: MonadState s m => (s -> a) -> m a -- | A variant of modify in which the computation is strict in the -- new state. modify' :: MonadState s m => (s -> s) -> m () -- | Monadic state transformer. -- -- Maps an old state to a new state inside a state monad. The old state -- is thrown away. -- --
--   Main> :t modify ((+1) :: Int -> Int)
--   modify (...) :: (MonadState Int a) => a ()
--   
-- -- This says that modify (+1) acts over any Monad that is a -- member of the MonadState class, with an Int state. modify :: MonadState s m => (s -> s) -> m () -- | Minimal definition is either both of get and put or -- just state class Monad m => MonadState s (m :: Type -> Type) | m -> s -- | 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 -- | The inverse of ExceptT. runExceptT :: () => ExceptT e m a -> m (Either e a) -- | The parameterizable reader monad. -- -- Computations are functions of a shared environment. -- -- The return function ignores the environment, while -- >>= passes the inherited environment to both -- subcomputations. type Reader r = ReaderT r Identity -- | Runs a Reader and extracts the final value from it. (The -- inverse of reader.) runReader :: () => Reader r a -> r -> a -- | Execute a computation in a modified environment (a specialization of -- withReaderT). -- -- withReader :: () => (r' -> r) -> Reader r a -> Reader r' a -- | Execute a computation in a modified environment (a more general -- version of local). -- -- withReaderT :: () => (r' -> r) -> ReaderT r m a -> ReaderT r' m a -- | A state monad parameterized by the type s of the state to -- carry. -- -- The return function leaves the state unchanged, while -- >>= uses the final state of the first computation as -- the initial state of the second. type State s = StateT s Identity -- | Unwrap a state monad computation as a function. (The inverse of -- state.) runState :: () => State s a -> s -> (a, s) -- | Evaluate a state computation with the given initial state and return -- the final value, discarding the final state. -- -- evalState :: () => State s a -> s -> a -- | Evaluate a state computation with the given initial state and return -- the final state, discarding the final value. -- -- execState :: () => State s a -> s -> s -- | withState f m executes action m on a state -- modified by applying f. -- -- withState :: () => (s -> s) -> State s a -> State s a -- | Evaluate a state computation with the given initial state and return -- the final value, discarding the final state. -- -- evalStateT :: Monad m => StateT s m a -> s -> m a -- | Evaluate a state computation with the given initial state and return -- the final state, discarding the final value. -- -- execStateT :: Monad m => StateT s m a -> s -> m s -- | undefined that leaves warning in code on every usage. undefined :: HasCallStack => a -- | Version of traceId that leaves warning and takes Text. traceId :: Text -> Text -- | Version of traceM that leaves warning and takes Text. traceM :: Monad m => Text -> m () -- | Version of traceShowM that leaves warning. traceShowM :: (Show a, Monad m) => a -> m () -- | Version of traceShow that leaves warning. traceShowId :: Show a => a -> a -- | Version of traceShow that leaves warning. traceShow :: Show a => a -> b -> b -- | error that takes Text as an argument. error :: HasCallStack => Text -> a -- | Generalized over string version of trace that leaves warnings. trace :: Print b => b -> a -> a -- | Similar to undefined but data type. data Undefined Undefined :: Undefined -- | Monadic version of any. -- --
--   >>> anyM (readMaybe >=> pure . even) ["5", "10"]
--   Just True
--   
--   >>> anyM (readMaybe >=> pure . even) ["10", "aba"]
--   Just True
--   
--   >>> anyM (readMaybe >=> pure . even) ["aba", "10"]
--   Nothing
--   
anyM :: (Foldable f, Monad m) => (a -> m Bool) -> f a -> m Bool -- | Monadic version of all. -- --
--   >>> allM (readMaybe >=> pure . even) ["6", "10"]
--   Just True
--   
--   >>> allM (readMaybe >=> pure . even) ["5", "aba"]
--   Just False
--   
--   >>> allM (readMaybe >=> pure . even) ["aba", "10"]
--   Nothing
--   
allM :: (Foldable f, Monad m) => (a -> m Bool) -> f a -> m Bool -- | Monadic version of or. -- --
--   >>> orM [Just True, Just False]
--   Just True
--   
--   >>> orM [Just True, Nothing]
--   Just True
--   
--   >>> orM [Nothing, Just True]
--   Nothing
--   
orM :: (Foldable f, Monad m) => f (m Bool) -> m Bool -- | Monadic version of and. -- --
--   >>> andM [Just True, Just False]
--   Just False
--   
--   >>> andM [Just True]
--   Just True
--   
--   >>> andM [Just True, Just False, Nothing]
--   Just False
--   
--   >>> andM [Just True, Nothing]
--   Nothing
--   
--   >>> andM [putTextLn "1" >> pure True, putTextLn "2" >> pure False, putTextLn "3" >> pure True]
--   1
--   2
--   False
--   
andM :: (Foldable f, Monad m) => f (m Bool) -> m Bool -- | Like notElem but doesn't work on Set and HashSet -- for performance reasons. -- --
--   >>> notElem 'x' ("abc" :: String)
--   True
--   
--   >>> notElem False (one True :: Set Bool)
--   ...
--       • Do not use 'elem' and 'notElem' methods from 'Foldable' on Set
--         Suggestions:
--             Instead of
--                 elem :: (Foldable t, Eq a) => a -> t a -> Bool
--             use
--                 member :: ??? -- TODO
--   ...
--             Instead of
--                 notElem :: (Foldable t, Eq a) => a -> t a -> Bool
--             use
--                 notMember :: ??? -- TODO
--   ...
--   
notElem :: (Foldable f, DisallowElem f, Eq a) => a -> f a -> Bool -- | Like elem but doesn't work on Set and HashSet for -- performance reasons. -- --
--   >>> elem 'x' ("abc" :: String)
--   False
--   
--   >>> elem False (one True :: Set Bool)
--   ...
--       • Do not use 'elem' and 'notElem' methods from 'Foldable' on Set
--         Suggestions:
--             Instead of
--                 elem :: (Foldable t, Eq a) => a -> t a -> Bool
--             use
--                 member :: ??? -- TODO
--   ...
--             Instead of
--                 notElem :: (Foldable t, Eq a) => a -> t a -> Bool
--             use
--                 notMember :: ??? -- TODO
--   ...
--   
elem :: (Foldable f, DisallowElem f, Eq a) => a -> f a -> Bool -- | Stricter version of product. -- --
--   >>> product [1..10]
--   3628800
--   
product :: (Foldable f, Num a) => f a -> a -- | Stricter version of sum. -- --
--   >>> sum [1..10]
--   55
--   
sum :: (Foldable f, Num a) => f a -> a -- | Polymorphic version of concatMapM function. -- --
--   >>> foldMapM @[Int] (Just . replicate 3) [1..3]
--   Just [1,1,1,2,2,2,3,3,3]
--   
foldMapM :: (Monoid b, Monad m, Foldable f) => (a -> m b) -> f a -> m b -- | Polymorphic version of concatMapA function. -- --
--   >>> foldMapA @[Int] (Just . replicate 3) [1..3]
--   Just [1,1,1,2,2,2,3,3,3]
--   
foldMapA :: (Monoid b, Applicative m, Foldable f) => (a -> m b) -> f a -> m b -- | Similar to foldl' but takes a function with its arguments -- flipped. -- --
--   >>> flipfoldl' (/) 5 [2,3] :: Rational
--   15 % 2
--   
flipfoldl' :: Foldable f => (a -> b -> b) -> b -> f a -> b type family DisallowElem (f :: Type -> Type) :: Constraint type family ElemErrorMessage (t :: k) :: ErrorMessage -- | Monadic version of guard. Occasionally useful. Here some -- complex but real-life example: -- --
--   findSomePath :: IO (Maybe FilePath)
--   
--   somePath :: MaybeT IO FilePath
--   somePath = do
--       path <- MaybeT findSomePath
--       guardM $ liftIO $ doesDirectoryExist path
--       return path
--   
guardM :: MonadPlus m => m Bool -> m () -- | Monadic version of if-then-else. -- --
--   >>> ifM (pure True) (putTextLn "True text") (putTextLn "False text")
--   True text
--   
ifM :: Monad m => m Bool -> m a -> m a -> m a -- | Monadic version of unless. -- --
--   >>> unlessM (pure False) $ putTextLn "No text :("
--   No text :(
--   
--   >>> unlessM (pure True) $ putTextLn "Yes text :)"
--   
unlessM :: Monad m => m Bool -> m () -> m () -- | Monadic version of when. -- --
--   >>> whenM (pure False) $ putTextLn "No text :("
--   
--   >>> whenM (pure True)  $ putTextLn "Yes text :)"
--   Yes text :)
--   
--   >>> whenM (Just True) (pure ())
--   Just ()
--   
--   >>> whenM (Just False) (pure ())
--   Just ()
--   
--   >>> whenM Nothing (pure ())
--   Nothing
--   
whenM :: Monad m => m Bool -> m () -> m () -- | Alias for evaluateWHNF . rnf. Similar to evaluateNF -- but discards resulting value. evaluateNF_ :: (NFData a, MonadIO m) => a -> m () -- | Alias for evaluateWHNF . force with clearer name. evaluateNF :: (NFData a, MonadIO m) => a -> m a -- | Like evaluateWNHF but discards value. evaluateWHNF_ :: MonadIO m => a -> m () -- | Lifted alias for evaluate with clearer name. evaluateWHNF :: MonadIO m => a -> m a -- | Generate a pure value which, when forced, will synchronously throw the -- exception wrapped into Bug data type. bug :: (HasCallStack, Exception e) => e -> a -- | Pattern synonym to easy pattern matching on exceptions. So intead of -- writing something like this: -- --
--   isNonCriticalExc :: SomeException -> Bool
--   isNonCriticalExc e
--       | Just (_ :: NodeAttackedError) <- fromException e = True
--       | Just DialogUnexpected{} <- fromException e = True
--       | otherwise = False
--   
-- -- you can use Exc pattern synonym: -- --
--   isNonCriticalExc :: SomeException -> Bool
--   isNonCriticalExc = case
--       Exc (_ :: NodeAttackedError) -> True  -- matching all exceptions of type NodeAttackedError
--       Exc DialogUnexpected{} -> True
--       _ -> False
--   
-- -- This pattern is bidirectional. You can use Exc e instead of -- toException e. pattern Exc :: forall e. Exception e => () => e -> SomeException -- | Type that represents exceptions used in cases when a particular -- codepath is not meant to be ever executed, but happens to be executed -- anyway. data Bug Bug :: SomeException -> CallStack -> Bug -- | Monadic version of whenNotNull. whenNotNullM :: Monad m => m [a] -> (NonEmpty a -> m ()) -> m () -- | Performs given action over NonEmpty list if given list is non -- empty. -- --
--   >>> whenNotNull [] $ \(b :| _) -> print (not b)
--   
--   >>> whenNotNull [False,True] $ \(b :| _) -> print (not b)
--   True
--   
whenNotNull :: Applicative f => [a] -> (NonEmpty a -> f ()) -> f () -- | Destructuring list into its head and tail if possible. This function -- is total. -- --
--   >>> uncons []
--   Nothing
--   
--   >>> uncons [1..5]
--   Just (1,[2,3,4,5])
--   
--   >>> uncons (5 : [1..5]) >>= \(f, l) -> pure $ f == length l
--   Just True
--   
uncons :: () => [a] -> Maybe (a, [a]) -- | For safe work with lists using functinons for NonEmpty. -- --
--   >>> viaNonEmpty head [1]
--   Just 1
--   
--   >>> viaNonEmpty head []
--   Nothing
--   
viaNonEmpty :: () => (NonEmpty a -> b) -> [a] -> Maybe b -- | Monadic version of whenRight_. whenRightM_ :: Monad m => m (Either l r) -> (r -> m ()) -> m () -- | Monadic version of whenRight. whenRightM :: Monad m => a -> m (Either l r) -> (r -> m a) -> m a -- | Applies given action to Either content if Right is -- given. whenRight_ :: Applicative f => Either l r -> (r -> f ()) -> f () -- | Applies given action to Either content if Right is given -- and returns the result. In case of Left the default value will -- be returned. whenRight :: Applicative f => a -> Either l r -> (r -> f a) -> f a -- | Monadic version of whenLeft_. whenLeftM_ :: Monad m => m (Either l r) -> (l -> m ()) -> m () -- | Monadic version of whenLeft. whenLeftM :: Monad m => a -> m (Either l r) -> (l -> m a) -> m a -- | Applies given action to Either content if Left is given. whenLeft_ :: Applicative f => Either l r -> (l -> f ()) -> f () -- | Applies given action to Either content if Left is given -- and returns the result. In case of Right the default value will -- be returned. whenLeft :: Applicative f => a -> Either l r -> (l -> f a) -> f a -- | Maps Maybe to Either wrapping default value into -- Right. -- --
--   >>> maybeToLeft True (Just "aba")
--   Left "aba"
--   
--   >>> maybeToLeft True Nothing
--   Right True
--   
maybeToLeft :: () => r -> Maybe l -> Either l r -- | Maps Maybe to Either wrapping default value into -- Left. -- --
--   >>> maybeToRight True (Just "aba")
--   Right "aba"
--   
--   >>> maybeToRight True Nothing
--   Left True
--   
maybeToRight :: () => l -> Maybe r -> Either l r -- | Maps right part of Either to Maybe. -- --
--   >>> rightToMaybe (Left True)
--   Nothing
--   
--   >>> rightToMaybe (Right "aba")
--   Just "aba"
--   
rightToMaybe :: () => Either l r -> Maybe r -- | Maps left part of Either to Maybe. -- --
--   >>> leftToMaybe (Left True)
--   Just True
--   
--   >>> leftToMaybe (Right "aba")
--   Nothing
--   
leftToMaybe :: () => Either l r -> Maybe l fromStrict :: LazyStrict l s => s -> l fromLazy :: LazyStrict l s => l -> s -- | Generalized version of show. show :: (Show a, IsString b) => a -> b -- | Polymorhpic version of readEither. -- --
--   >>> readEither @Text @Int "123"
--   Right 123
--   
--   >>> readEither @Text @Int "aa"
--   Left "Prelude.read: no parse"
--   
readEither :: (ToString a, Read b) => a -> Either Text b -- | Type synonym for Text. type LText = Text -- | Type synonym for ByteString. type LByteString = ByteString -- | Type class for conversion to utf8 representation of text. class ConvertUtf8 a b -- | Encode as utf8 string (usually ByteString). -- --
--   >>> encodeUtf8 @Text @ByteString "патак"
--   "\208\191\208\176\209\130\208\176\208\186"
--   
encodeUtf8 :: ConvertUtf8 a b => a -> b -- | Decode from utf8 string. -- --
--   >>> decodeUtf8 @Text @ByteString "\208\191\208\176\209\130\208\176\208\186"
--   "\1087\1072\1090\1072\1082"
--   
--   >>> putStrLn $ decodeUtf8 @Text @ByteString "\208\191\208\176\209\130\208\176\208\186"
--   патак
--   
decodeUtf8 :: ConvertUtf8 a b => b -> a -- | Decode as utf8 string but returning execption if byte sequence is -- malformed. -- --
--   >>> decodeUtf8 @Text @ByteString "\208\208\176\209\130\208\176\208\186"
--   "\65533\1072\1090\1072\1082"
--   
-- --
--   >>> decodeUtf8Strict @Text @ByteString "\208\208\176\209\130\208\176\208\186"
--   Left Cannot decode byte '\xd0': Data.Text.Internal.Encoding.decodeUtf8: Invalid UTF-8 stream
--   
decodeUtf8Strict :: ConvertUtf8 a b => b -> Either UnicodeException a -- | Type class for converting other strings to Text. class ToText a toText :: ToText a => a -> Text -- | Type class for converting other strings to Text. class ToLText a toLText :: ToLText a => a -> Text -- | Type class for converting other strings to String. class ToString a toString :: ToString a => a -> String -- | Type class for lazy-strict conversions. class LazyStrict l s | l -> s, s -> l toLazy :: LazyStrict l s => s -> l toStrict :: LazyStrict l s => l -> s -- | Specialized to Text version of putStrLn or forcing type -- inference. putLTextLn :: MonadIO m => Text -> m () -- | Specialized to Text version of putStr or forcing type -- inference. putLText :: MonadIO m => Text -> m () -- | Specialized to Text version of putStrLn or forcing type -- inference. putTextLn :: MonadIO m => Text -> m () -- | Specialized to Text version of putStr or forcing type -- inference. putText :: MonadIO m => Text -> m () -- | Lifted version of print. print :: (MonadIO m, Show a) => a -> m () -- | Polymorfic over string and lifted to MonadIO printing -- functions. class Print a putStr :: (Print a, MonadIO m) => a -> m () putStrLn :: (Print a, MonadIO m) => a -> m () -- | Like hashNub but has better performance and also doesn't save -- the order. -- --
--   >>> unstableNub [3, 3, 3, 2, 2, -1, 1]
--   [1,2,3,-1]
--   
unstableNub :: (Eq a, Hashable a) => [a] -> [a] -- | Like ordNub but also sorts a list. -- --
--   >>> sortNub [3, 3, 3, 2, 2, -1, 1]
--   [-1,1,2,3]
--   
sortNub :: Ord a => [a] -> [a] -- | Like nub but runs in O(n * log_16(n)) time and -- requires Hashable. -- --
--   >>> hashNub [3, 3, 3, 2, 2, -1, 1]
--   [3,2,-1,1]
--   
hashNub :: (Eq a, Hashable a) => [a] -> [a] -- | Like nub but runs in O(n * log n) time and requires -- Ord. -- --
--   >>> ordNub [3, 3, 3, 2, 2, -1, 1]
--   [3,2,-1,1]
--   
ordNub :: Ord a => [a] -> [a] -- | Extracts Monoid value from Maybe returning mempty -- if Nothing. -- --
--   >>> maybeToMonoid (Just [1,2,3] :: Maybe [Int])
--   [1,2,3]
--   
--   >>> maybeToMonoid (Nothing :: Maybe [Int])
--   []
--   
maybeToMonoid :: Monoid m => Maybe m -> m -- | Alias for flip execState. It's not shorter but sometimes more -- readable. Done by analogy with using* functions family. executingState :: () => s -> State s a -> s -- | Alias for flip execStateT. It's not shorter but sometimes -- more readable. Done by analogy with using* functions family. executingStateT :: Functor f => s -> StateT s f a -> f s -- | Alias for flip evalState. It's not shorter but sometimes more -- readable. Done by analogy with using* functions family. evaluatingState :: () => s -> State s a -> a -- | Alias for flip evalStateT. It's not shorter but sometimes -- more readable. Done by analogy with using* functions family. evaluatingStateT :: Functor f => s -> StateT s f a -> f a -- | Shorter and more readable alias for flip runState. usingState :: () => s -> State s a -> (a, s) -- | Shorter and more readable alias for flip runStateT. usingStateT :: () => s -> StateT s m a -> m (a, s) -- | Shorter and more readable alias for flip runReader. usingReader :: () => r -> Reader r a -> a -- | Shorter and more readable alias for flip runReaderT. usingReaderT :: () => r -> ReaderT r m a -> m a -- | Monadic version of whenNothingM_. whenNothingM_ :: Monad m => m (Maybe a) -> m () -> m () -- | Monadic version of whenNothing. whenNothingM :: Monad m => m (Maybe a) -> m a -> m a -- | Performs default Applicative action if Nothing is given. -- Do nothing for Just. Convenient for discarding Just -- content. -- --
--   >>> whenNothing_ Nothing $ putTextLn "Nothing!"
--   Nothing!
--   
--   >>> whenNothing_ (Just True) $ putTextLn "Nothing!"
--   
whenNothing_ :: Applicative f => Maybe a -> f () -> f () -- | Performs default Applicative action if Nothing is given. -- Otherwise returns content of Just pured to Applicative. -- --
--   >>> whenNothing Nothing [True, False]
--   [True,False]
--   
--   >>> whenNothing (Just True) [True, False]
--   [True]
--   
whenNothing :: Applicative f => Maybe a -> f a -> f a -- | Monadic version of whenJust. whenJustM :: Monad m => m (Maybe a) -> (a -> m ()) -> m () -- | Specialized version of for_ for Maybe. It's used for -- code readability. Also helps to avoid space leaks: Foldable.mapM_ -- space leak. -- --
--   >>> whenJust Nothing $ \b -> print (not b)
--   
--   >>> whenJust (Just True) $ \b -> print (not b)
--   False
--   
whenJust :: Applicative f => Maybe a -> (a -> f ()) -> f () -- | Similar to fromMaybe but with flipped arguments. -- --
--   >>> readMaybe "True" ?: False
--   True
--   
-- --
--   >>> readMaybe "Tru" ?: False
--   False
--   
(?:) :: () => Maybe a -> a -> a infixr 0 ?: -- | Lifted version of atomicWriteIORef. atomicWriteIORef :: MonadIO m => IORef a -> a -> m () -- | Lifted version of atomicModifyIORef'. atomicModifyIORef' :: MonadIO m => IORef a -> (a -> (a, b)) -> m b -- | Lifted version of atomicModifyIORef. atomicModifyIORef :: MonadIO m => IORef a -> (a -> (a, b)) -> m b -- | Lifted version of modifyIORef'. modifyIORef' :: MonadIO m => IORef a -> (a -> a) -> m () -- | Lifted version of modifyIORef. modifyIORef :: MonadIO m => IORef a -> (a -> a) -> m () -- | Lifted version of writeIORef. writeIORef :: MonadIO m => IORef a -> a -> m () -- | Lifted version of readIORef. readIORef :: MonadIO m => IORef a -> m a -- | Lifted version of newIORef. newIORef :: MonadIO m => a -> m (IORef a) -- | Lifted version of openFile. openFile :: MonadIO m => FilePath -> IOMode -> m Handle -- | Lifted version of writeFile. writeFile :: MonadIO m => FilePath -> Text -> m () -- | Lifted version of readFile. readFile :: MonadIO m => FilePath -> m Text -- | Lifted version of getLine. getLine :: MonadIO m => m Text -- | Lifted version of appendFile. appendFile :: MonadIO m => FilePath -> Text -> m () -- | Lifted version of die. die is available since base-4.8, -- but it's more convenient to redefine it instead of using CPP. die :: MonadIO m => String -> m () -- | Lifted version of exitSuccess. exitSuccess :: MonadIO m => m a -- | Lifted version of exitFailure. exitFailure :: MonadIO m => m a -- | Lifted version of exitWith. exitWith :: MonadIO m => ExitCode -> m a -- | Lifted to MonadIO version of readTVarIO. readTVarIO :: MonadIO m => TVar a -> m a -- | Lifted to MonadIO version of newTVarIO. newTVarIO :: MonadIO m => a -> m (TVar a) -- | Lifted to MonadIO version of atomically. atomically :: MonadIO m => STM a -> m a -- | Lifted to MonadIO version of tryTakeMVar. tryTakeMVar :: MonadIO m => MVar a -> m (Maybe a) -- | Lifted to MonadIO version of tryReadMVar. tryReadMVar :: MonadIO m => MVar a -> m (Maybe a) -- | Lifted to MonadIO version of tryPutMVar. tryPutMVar :: MonadIO m => MVar a -> a -> m Bool -- | Lifted to MonadIO version of takeMVar. takeMVar :: MonadIO m => MVar a -> m a -- | Lifted to MonadIO version of swapMVar. swapMVar :: MonadIO m => MVar a -> a -> m a -- | Lifted to MonadIO version of readMVar. readMVar :: MonadIO m => MVar a -> m a -- | Lifted to MonadIO version of putMVar. putMVar :: MonadIO m => MVar a -> a -> m () -- | Lifted to MonadIO version of newMVar. newMVar :: MonadIO m => a -> m (MVar a) -- | Lifted to MonadIO version of newEmptyMVar. newEmptyMVar :: MonadIO m => m (MVar a) -- | Alias for fmap . fmap. Convenient to work with two nested -- Functors. -- --
--   >>> negate <<$>> Just [1,2,3]
--   Just [-1,-2,-3]
--   
(<<$>>) :: (Functor f, Functor g) => (a -> b) -> f (g a) -> f (g b) infixl 4 <<$>> -- | Renamed version of id. identity :: () => a -> a -- | Typeclass for data types that can be created from one element. -- --
--   >>> one True :: [Bool]
--   [True]
--   
--   >>> one 'a' :: Text
--   "a"
--   
--   >>> one (3, "hello") :: HashMap Int String
--   fromList [(3,"hello")]
--   
class One x where { -- | Type of single element of the structure. type family OneItem x :: Type; } -- | Create a list, map, Text, etc from a single element. one :: One x => OneItem x -> x -- | Shorter alias for pure (). -- --
--   >>> pass :: Maybe ()
--   Just ()
--   
pass :: Applicative f => f () -- | A set of values. A set cannot contain duplicate values. data HashSet a -- | Convert a MaybeT computation to ExceptT, with a default -- exception value. maybeToExceptT :: Functor m => e -> MaybeT m a -> ExceptT e m a -- | Convert a ExceptT computation to MaybeT, discarding the -- value of any exception. exceptToMaybeT :: Functor m => ExceptT e m a -> MaybeT m a -- | An exception type for representing Unicode encoding errors. data UnicodeException -- | A handler for a decoding error. type OnDecodeError = OnError Word8 Char -- | Function type for handling a coding error. It is supplied with two -- inputs: -- -- -- -- If the handler returns a value wrapped with Just, that value -- will be used in the output as the replacement for the invalid input. -- If it returns Nothing, no value will be used in the output. -- -- Should the handler need to abort processing, it should use -- error or throw an exception (preferably a -- UnicodeException). It may use the description provided to -- construct a more helpful error report. type OnError a b = String -> Maybe a -> Maybe b -- | Throw a UnicodeException if decoding fails. strictDecode :: OnDecodeError -- | Replace an invalid input byte with the Unicode replacement character -- U+FFFD. lenientDecode :: OnDecodeError -- | Decode a ByteString containing UTF-8 encoded text. -- -- NOTE: The replacement character returned by -- OnDecodeError MUST be within the BMP plane; surrogate code -- points will automatically be remapped to the replacement char -- U+FFFD (since 0.11.3.0), whereas code points beyond -- the BMP will throw an error (since 1.2.3.1); For earlier -- versions of text using those unsupported code points would -- result in undefined behavior. decodeUtf8With :: OnDecodeError -> ByteString -> Text -- | Decode a ByteString containing UTF-8 encoded text. -- -- If the input contains any invalid UTF-8 data, the relevant exception -- will be returned, otherwise the decoded text. decodeUtf8' :: ByteString -> Either UnicodeException Text -- | O(n) Breaks a Text up into a list of words, delimited by -- Chars representing white space. words :: Text -> [Text] -- | O(n) Breaks a Text up into a list of Texts at -- newline Chars. The resulting strings do not contain newlines. lines :: Text -> [Text] -- | O(n) Joins lines, after appending a terminating newline to -- each. unlines :: [Text] -> Text -- | O(n) Joins words using single space characters. unwords :: [Text] -> Text -- | Strict version of modifyTVar. modifyTVar' :: () => TVar a -> (a -> a) -> STM () -- | Synchronously throw the given exception. throwIO :: (MonadIO m, Exception e) => e -> m a -- | Get the request body as a lazy ByteString. This uses lazy I/O under -- the surface, and therefore all typical warnings regarding lazy I/O -- apply. -- -- Since 1.4.1 lazyRequestBody :: Request -> IO ByteString -- | Get the request body as a lazy ByteString. However, do not use -- any lazy I/O, instead reading the entire body into memory strictly. -- -- Since 3.0.1 strictRequestBody :: Request -> IO ByteString -- | conditionally apply a Middleware ifRequest :: (Request -> Bool) -> Middleware -> Middleware -- | apply a function that modifies a response as a Middleware modifyResponse :: (Response -> Response) -> Middleware -- | A default, blank request. -- -- Since 2.0.0 defaultRequest :: Request -- | Apply the provided function to the response status of the Response. mapResponseStatus :: (Status -> Status) -> Response -> Response -- | Apply the provided function to the response header list of the -- Response. mapResponseHeaders :: (ResponseHeaders -> ResponseHeaders) -> Response -> Response -- | Converting the body information in Response to a -- StreamingBody. responseToStream :: () => Response -> (Status, ResponseHeaders, (StreamingBody -> IO a) -> IO a) -- | Accessing ResponseHeaders in Response. responseHeaders :: Response -> ResponseHeaders -- | Accessing Status in Response. responseStatus :: Response -> Status -- | Create a response for a raw application. This is useful for "upgrade" -- situations such as WebSockets, where an application requests for the -- server to grant it raw network access. -- -- This function requires a backup response to be provided, for the case -- where the handler in question does not support such upgrading (e.g., -- CGI apps). -- -- In the event that you read from the request body before returning a -- responseRaw, behavior is undefined. -- -- Since 2.1.0 responseRaw :: (IO ByteString -> (ByteString -> IO ()) -> IO ()) -> Response -> Response -- | Creating Response from a stream of values. -- -- In order to allocate resources in an exception-safe manner, you can -- use the bracket pattern outside of the call to -- responseStream. As a trivial example: -- --
--   app :: Application
--   app req respond = bracket_
--       (putStrLn "Allocating scarce resource")
--       (putStrLn "Cleaning up")
--       $ respond $ responseStream status200 [] $ \write flush -> do
--           write $ byteString "Hello\n"
--           flush
--           write $ byteString "World\n"
--   
-- -- Note that in some cases you can use bracket from inside -- responseStream as well. However, placing the call on the -- outside allows your status value and response headers to depend on the -- scarce resource. -- -- Since 3.0.0 responseStream :: Status -> ResponseHeaders -> StreamingBody -> Response -- | Creating Response from ByteString. This is a wrapper for -- responseBuilder. responseLBS :: Status -> ResponseHeaders -> ByteString -> Response -- | Creating Response from Builder. -- -- Some questions and answers about the usage of Builder here: -- -- Q1. Shouldn't it be at the user's discretion to use Builders -- internally and then create a stream of ByteStrings? -- -- A1. That would be less efficient, as we wouldn't get cheap -- concatenation with the response headers. -- -- Q2. Isn't it really inefficient to convert from ByteString to Builder, -- and then right back to ByteString? -- -- A2. No. If the ByteStrings are small, then they will be copied into a -- larger buffer, which should be a performance gain overall (less system -- calls). If they are already large, then an insert operation is used to -- avoid copying. -- -- Q3. Doesn't this prevent us from creating comet-style servers, since -- data will be cached? -- -- A3. You can force a Builder to output a ByteString before it is an -- optimal size by sending a flush command. responseBuilder :: Status -> ResponseHeaders -> Builder -> Response -- | Creating Response from a file. responseFile :: Status -> ResponseHeaders -> FilePath -> Maybe FilePart -> Response -- | The WAI application. -- -- Note that, since WAI 3.0, this type is structured in continuation -- passing style to allow for proper safe resource handling. This was -- handled in the past via other means (e.g., ResourceT). As a -- demonstration: -- --
--   app :: Application
--   app req respond = bracket_
--       (putStrLn "Allocating scarce resource")
--       (putStrLn "Cleaning up")
--       (respond $ responseLBS status200 [] "Hello World")
--   
type Application = Request -> Response -> IO ResponseReceived -> IO ResponseReceived -- | Middleware is a component that sits between the server and -- application. It can do such tasks as GZIP encoding or response -- caching. What follows is the general definition of middleware, though -- a middleware author should feel free to modify this. -- -- As an example of an alternate type for middleware, suppose you write a -- function to load up session information. The session information is -- simply a string map <math>. A logical type signature for this -- middleware might be: -- --
--   loadSession :: ([(String, String)] -> Application) -> Application
--   
-- -- Here, instead of taking a standard Application as its first -- argument, the middleware takes a function which consumes the session -- information as well. type Middleware = Application -> Application -- | Get the next chunk of the body. Returns empty when the body is -- fully consumed. getRequestBodyChunk :: Request -> IO ByteString -- | Information on the request sent by the client. This abstracts away the -- details of the underlying implementation. data Request data Response -- | Represents a streaming HTTP response body. It's a function of two -- parameters; the first parameter provides a means of sending another -- chunk of data, and the second parameter provides a means of flushing -- the data to the client. -- -- Since 3.0.0 type StreamingBody = Builder -> IO () -> IO () -> IO () -- | The size of the request body. In the case of chunked bodies, the size -- will not be known. -- -- Since 1.4.0 data RequestBodyLength ChunkedBody :: RequestBodyLength KnownLength :: Word64 -> RequestBodyLength -- | Information on which part to be sent. Sophisticated application -- handles Range (and If-Range) then create FilePart. data FilePart FilePart :: Integer -> Integer -> Integer -> FilePart [filePartOffset] :: FilePart -> Integer [filePartByteCount] :: FilePart -> Integer [filePartFileSize] :: FilePart -> Integer -- | A special datatype to indicate that the WAI handler has received the -- response. This is to avoid the need for Rank2Types in the definition -- of Application. -- -- It is highly advised that only WAI handlers import and use the -- data constructor for this data type. -- -- Since 3.0.0 data ResponseReceived parseInt :: Integral a => Text -> Maybe a headMay :: [a] -> Maybe a module Webby -- | The main monad transformer stack used in the web-framework. -- -- The type of a handler for a request is `WebbyM appEnv ()`. The -- appEnv parameter is used by the web application to store an -- (read-only) environment. For e.g. it can be used to store a database -- connection pool. data WebbyM appEnv a -- | A route pattern represents logic to match a request to a handler. data RoutePattern -- | A route is a pair of a route pattern and a handler. type Route env = (RoutePattern, WebbyM env ()) -- | Create a route for a user-provided HTTP request method, pattern and -- handler function. mkRoute :: Method -> Text -> WebbyM appEnv () -> (RoutePattern, WebbyM appEnv ()) -- | Create a route for a POST request method, given the path pattern and -- handler. post :: Text -> WebbyM appEnv () -> (RoutePattern, WebbyM appEnv ()) -- | Create a route for a GET request method, given the path pattern and -- handler. get :: Text -> WebbyM appEnv () -> (RoutePattern, WebbyM appEnv ()) -- | Create a route for a PUT request method, given the path pattern and -- handler. put :: Text -> WebbyM appEnv () -> (RoutePattern, WebbyM appEnv ()) -- | Create a route for a DELETE request method, given path pattern and -- handler. delete :: Text -> WebbyM appEnv () -> (RoutePattern, WebbyM appEnv ()) -- | Captures are simply extracted path elements in a HashMap type Captures = HashMap Text Text -- | Retrieve all path captures captures :: WebbyM appEnv Captures -- | Retrieve a particular capture (TODO: extend?) getCapture :: FromHttpApiData a => Text -> WebbyM appEnv a flag :: Text -> WebbyM appEnv Bool header :: HeaderName -> WebbyM appEnv (Maybe Text) headers :: WebbyM appEnv [Header] jsonData :: FromJSON a => WebbyM appEnv a param :: FromHttpApiData a => Text -> WebbyM appEnv (Maybe a) param_ :: FromHttpApiData a => Text -> WebbyM appEnv a params :: WebbyM appEnv [(Text, Text)] request :: WebbyM appEnv Request -- | Return the raw request body as a lazy bytestring requestBodyLBS :: WebbyM appEnv LByteString requestBodyLength :: WebbyM appEnv (Maybe Int64) -- | Returns an action that returns successive chunks of the rquest body. -- It returns an empty bytestring after the request body is consumed. getRequestBodyChunkAction :: WebbyM appEnv (WebbyM appEnv ByteString) setStatus :: Status -> WebbyM appEnv () addHeader :: Header -> WebbyM appEnv () setHeader :: Header -> WebbyM appEnv () blob :: ByteString -> WebbyM appEnv () json :: ToJSON b => b -> WebbyM appEnv () text :: Text -> WebbyM appEnv () stream :: StreamingBody -> WebbyM appEnv () -- | Use this function, to create a WAI application. It takes a -- user/application defined appEnv data type and a list of -- routes. Routes are matched in the given order. If none of the requests -- match a request, a default 404 response is returned. mkWebbyApp :: appEnv -> [Route appEnv] -> IO Application -- | The WAI application. -- -- Note that, since WAI 3.0, this type is structured in continuation -- passing style to allow for proper safe resource handling. This was -- handled in the past via other means (e.g., ResourceT). As a -- demonstration: -- --
--   app :: Application
--   app req respond = bracket_
--       (putStrLn "Allocating scarce resource")
--       (putStrLn "Cleaning up")
--       (respond $ responseLBS status200 [] "Hello World")
--   
type Application = Request -> Response -> IO ResponseReceived -> IO ResponseReceived -- | The reader environment used by the web framework. It is parameterized -- by the application's environment data type. data WEnv appEnv -- | Retrieve the app environment given to the application at -- initialization. getAppEnv :: WebbyM appEnv appEnv runAppEnv :: ReaderT appEnv (WebbyM appEnv) a -> WebbyM appEnv a finish :: WebbyM appEnv a -- | Various kinds of errors thrown by this library - these can be caught -- by handler code. data WebbyError WebbyJSONParseError :: Text -> WebbyError WebbyParamParseError :: Text -> Text -> WebbyError [wppeParamName] :: WebbyError -> Text [wppeErrMsg] :: WebbyError -> Text WebbyMissingCapture :: Text -> WebbyError