-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | Convenient imperative eDSL over Lorentz. -- -- Syntax and implementation of Indigo eDSL. @package indigo @version 0.3.1 -- | This module is intended to be imported instead of -- morley-prelude by Backend Indigo modules. -- -- This only serves the purpose of listing hiding rules once and -- avoid boilerplate. module Indigo.Backend.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 infixr 0 `seq` -- | O(n). filter, applied to a predicate and a list, returns -- the list of those elements that satisfy the predicate; i.e., -- --
--   filter p xs = [ x | x <- xs, p x]
--   
-- --
--   >>> filter odd [1, 2, 3]
--   [1,3]
--   
filter :: (a -> Bool) -> [a] -> [a] -- | O(min(m,n)). 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 is capable of list fusion, but it is restricted to its -- first list argument and its resulting list. 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 -- | Application operator. This operator is redundant, since ordinary -- application (f x) means the same as (f $ x). -- However, $ has low, right-associative binding precedence, so it -- sometimes allows parentheses to be omitted; for example: -- --
--   f $ g $ h x  =  f (g (h x))
--   
-- -- It is also useful in higher-order situations, such as map -- ($ 0) xs, or zipWith ($) fs xs. -- -- Note that ($) is levity-polymorphic in its result -- type, so that foo $ True where foo :: Bool -> -- Int# is well-typed. ($) :: forall (r :: RuntimeRep) a (b :: TYPE r). (a -> b) -> a -> b infixr 0 $ -- | 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 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: -- -- -- -- 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 -- | Inject a value into the monadic type. return :: Monad m => a -> m a infixl 1 >>= -- | A type f is a Functor if it provides a function fmap -- which, given any types a and b lets you apply any -- function from (a -> b) to turn an f a into an -- f b, preserving the structure of f. Furthermore -- f needs to adhere to the following: -- -- -- -- Note, that the second law follows from the free theorem of the type -- fmap and the first law, so you need only check that the former -- condition holds. class Functor (f :: Type -> Type) fmap :: 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) -- | 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. -- --
--   t (pure x) = pure x
--   t (f <*> x) = t f <*> t x
--   
-- -- and the identity functor Identity and composition functors -- Compose are from Data.Functor.Identity and -- Data.Functor.Compose. -- -- (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 following: -- -- 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: -- -- -- -- 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 (:%) :: !a -> !a -> 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 -- | A value of type Ptr a represents a pointer to an -- object, or an array of objects, which may be marshalled to or from -- Haskell values of type a. -- -- The type a will often be an instance of class Storable -- which provides the marshalling operations. However this is not -- essential, and you can provide your own operations to access the -- pointer. For example you might write small foreign functions to get or -- set the fields of a C struct. data Ptr a -- | A value of type FunPtr a is a pointer to a function -- callable from foreign code. The type a will normally be a -- foreign type, a function type with zero or more arguments where -- -- -- -- A value of type FunPtr a may be a pointer to a foreign -- function, either returned by another foreign function or imported with -- a a static address import like -- --
--   foreign import ccall "stdlib.h &free"
--     p_free :: FunPtr (Ptr a -> IO ())
--   
-- -- or a pointer to a Haskell function created using a wrapper stub -- declared to produce a FunPtr of the correct type. For example: -- --
--   type Compare = Int -> Int -> Bool
--   foreign import ccall "wrapper"
--     mkCompare :: Compare -> IO (FunPtr Compare)
--   
-- -- Calls to wrapper stubs like mkCompare allocate storage, which -- should be released with freeHaskellFunPtr when no longer -- required. -- -- To convert FunPtr values to corresponding Haskell functions, -- one can define a dynamic stub for the specific foreign type, -- e.g. -- --
--   type IntFunction = CInt -> IO ()
--   foreign import ccall "dynamic"
--     mkFun :: FunPtr IntFunction -> IntFunction
--   
data FunPtr a -- | The Either type represents values with two possibilities: a -- value of type Either a b is either Left -- a or Right b. -- -- The Either type is sometimes used to represent a value which is -- either correct or an error; by convention, the Left constructor -- is used to hold an error value and the Right constructor is -- used to hold a correct value (mnemonic: "right" also means "correct"). -- --

Examples

-- -- The type Either String Int is the type -- of values which can be either a String or an Int. The -- Left constructor can be used only on Strings, and the -- Right constructor can be used only on Ints: -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> s
--   Left "foo"
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> n
--   Right 3
--   
--   >>> :type s
--   s :: Either String Int
--   
--   >>> :type n
--   n :: Either String Int
--   
-- -- The fmap from our Functor instance will ignore -- Left values, but will apply the supplied function to values -- contained in a Right: -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> fmap (*2) s
--   Left "foo"
--   
--   >>> fmap (*2) n
--   Right 6
--   
-- -- The Monad instance for Either allows us to chain -- together multiple actions which may fail, and fail overall if any of -- the individual steps failed. First we'll write a function that can -- either parse an Int from a Char, or fail. -- --
--   >>> import Data.Char ( digitToInt, isDigit )
--   
--   >>> :{
--       let parseEither :: Char -> Either String Int
--           parseEither c
--             | isDigit c = Right (digitToInt c)
--             | otherwise = Left "parse error"
--   
--   >>> :}
--   
-- -- The following should work, since both '1' and '2' -- can be parsed as Ints. -- --
--   >>> :{
--       let parseMultiple :: Either String Int
--           parseMultiple = do
--             x <- parseEither '1'
--             y <- parseEither '2'
--             return (x + y)
--   
--   >>> :}
--   
-- --
--   >>> parseMultiple
--   Right 3
--   
-- -- But the following should fail overall, since the first operation where -- we attempt to parse 'm' as an Int will fail: -- --
--   >>> :{
--       let parseMultiple :: Either String Int
--           parseMultiple = do
--             x <- parseEither 'm'
--             y <- parseEither '2'
--             return (x + y)
--   
--   >>> :}
--   
-- --
--   >>> parseMultiple
--   Left "parse error"
--   
data Either a b Left :: a -> Either a b Right :: b -> Either a b -- | The kind of constraints, like Show a data Constraint -- | 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 :: k) (b :: k) -- | 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 -- | Identity function. -- --
--   id x = x
--   
id :: a -> 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 -- | See examples in Control.Monad.Reader. Note, the partially -- applied function type (->) r is a simple reader monad. See -- the instance declaration below. class Monad m => MonadReader r (m :: Type -> Type) | m -> r -- | Retrieves the monad environment. ask :: MonadReader r m => m r -- | Executes a computation in a modified environment. local :: MonadReader r m => (r -> r) -> m a -> m a -- | Retrieves a function of the current environment. reader :: MonadReader r m => (r -> a) -> m a -- | Minimal definition is either both of get and put or -- just state class Monad m => MonadState s (m :: Type -> Type) | m -> s -- | Return the state from the internals of the monad. get :: MonadState s m => m s -- | Replace the state inside the monad. put :: MonadState s m => s -> m () -- | Embed a simple state action into the monad. state :: MonadState s m => (s -> (a, s)) -> m a -- | 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 <$> -- | A String is a list of characters. String constants in Haskell -- are values of type String. type String = [Char] -- | 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 . -- | 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. -- -- The Semigroup operation for Map is union, which -- prefers values from the left operand. If m1 maps a key -- k to a value a1, and m2 maps the same key -- to a different value a2, then their union m1 <> -- m2 maps k to a1. data Map k a -- | A handle managing output to the Haskell program's standard output -- channel. stdout :: Handle -- | 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 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 -- | Right-to-left composition of functors. The composition of applicative -- functors is always applicative, but the composition of monads is not -- always a monad. newtype Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) Compose :: f (g a) -> Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) [getCompose] :: Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) -> f (g a) infixr 9 `Compose` infixr 9 `Compose` -- | 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] -- | Like foldM, but discards the result. foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m () -- | The foldM function is analogous to foldl, except that -- its result is encapsulated in a monad. Note that foldM works -- from left-to-right over the list arguments. This could be an issue -- where (>>) and the `folded function' are not -- commutative. -- --
--   foldM f a1 [x1, x2, ..., xm]
--   
--   ==
--   
--   do
--     a2 <- f a1 x1
--     a3 <- f a2 x2
--     ...
--     f am xm
--   
-- -- If right-to-left evaluation is required, the input list should be -- reversed. -- -- Note: foldM is the same as foldlM foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | zipWithM_ is the extension of zipWithM which ignores the -- final result. zipWithM_ :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m () -- | The zipWithM function generalizes zipWith to arbitrary -- applicative functors. zipWithM :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m [c] -- | The mapAndUnzipM function maps its first argument over a list, -- returning the result as a pair of lists. This function is mainly used -- with complicated data structures or a state 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] -- | This function may be used as a value for foldMap in a -- Foldable instance. -- --
--   foldMapDefault f ≡ getConst . traverse (Const . f)
--   
foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m -- | This function may be used as a value for fmap in a -- Functor instance, provided that traverse is defined. -- (Using fmapDefault with a Traversable instance defined -- only by sequenceA will result in infinite recursion.) -- --
--   fmapDefault f ≡ runIdentity . traverse (Identity . f)
--   
fmapDefault :: Traversable t => (a -> b) -> t a -> t b -- | The mapAccumR function behaves like a combination of -- fmap and foldr; it applies a function to each element of -- a structure, passing an accumulating parameter from right to left, and -- returning a final value of this accumulator together with the new -- structure. mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) -- | The mapAccumL function behaves like a combination of -- fmap and foldl; it applies a function to each element of -- a structure, passing an accumulating parameter from left to right, and -- returning a final value of this accumulator together with the new -- structure. mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) -- | forM is mapM with its arguments flipped. For a version -- that ignores the results see forM_. forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b) -- | 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 -- | 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 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) Const :: a -> Const a (b :: k) [getConst] :: Const a (b :: k) -> a -- | The least element of a non-empty structure with respect to the given -- comparison function. minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a -- | The largest element of a non-empty structure with respect to the given -- comparison function. maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a -- | Map a function over all the elements of a container and concatenate -- the resulting lists. concatMap :: Foldable t => (a -> [b]) -> t a -> [b] -- | The concatenation of all the elements of a container of lists. concat :: Foldable t => t [a] -> [a] -- | Monadic fold over the elements of a structure, associating to the -- left, i.e. from left to right. foldlM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | Monadic fold over the elements of a structure, associating to the -- right, i.e. from right to left. foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b -- | 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) Alt :: f a -> Alt (f :: k -> Type) (a :: k) [getAlt] :: Alt (f :: k -> Type) (a :: k) -> f a -- | Convert an integer into an unknown type-level natural. someNatVal :: Natural -> SomeNat natVal :: forall (n :: Nat) proxy. KnownNat n => proxy n -> Natural -- | This type represents unknown type-level natural numbers. data SomeNat SomeNat :: 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]] -- | O(n). 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] -- | O(n). The genericLength function is an overloaded -- version of length. In particular, instead of returning an -- Int, it returns any type which is an instance of Num. It -- is, however, less efficient than length. -- --
--   >>> genericLength [1, 2, 3] :: Int
--   3
--   
--   >>> genericLength [1, 2, 3] :: Float
--   3.0
--   
genericLength :: Num i => [a] -> i -- | The 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] -- | O(n). 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] -- | O(min(m,n)). 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 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] -- |
--   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) Proxy :: Proxy (t :: k) -- | 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` integralEnumFromThenTo :: Integral a => a -> a -> a -> [a] integralEnumFromTo :: Integral a => a -> a -> [a] integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a] integralEnumFrom :: (Integral a, Bounded a) => a -> [a] gcdWord' :: Word -> Word -> Word gcdInt' :: Int -> Int -> Int -- | 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 (^^%^^) :: Integral a => Rational -> a -> Rational (^%^) :: Integral a => Rational -> a -> Rational -- | 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 numericEnumFromThenTo :: (Ord a, Fractional a) => a -> a -> a -> [a] numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a] numericEnumFromThen :: Fractional a => a -> a -> [a] numericEnumFrom :: Fractional a => a -> [a] -- | Extract the denominator of the ratio in reduced form: the numerator -- and denominator have no common factor and the denominator is positive. denominator :: 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 -- | reduce is a subsidiary function used only in this module. It -- normalises a ratio by dividing both numerator and denominator by their -- greatest common divisor. reduce :: Integral a => a -> a -> Ratio a notANumber :: Rational infinity :: Rational ratioPrec1 :: Int ratioPrec :: Int underflowError :: a overflowError :: a ratioZeroDenominatorError :: a divZeroError :: a boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a] boundedEnumFrom :: (Enum a, Bounded a) => 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]) -- | O(min(m,n)). 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 (+) [1, 2, 3] [4, 5, 6]
--   [5,7,9]
--   
-- -- zipWith is right-lazy: -- --
--   zipWith f [] _|_ = []
--   
-- -- zipWith is capable of list fusion, but it is restricted to its -- first list argument and its resulting list. zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] -- | zip3 takes three lists and returns a list of triples, analogous -- to zip. It is capable of list fusion, but it is restricted to -- its first list argument and its resulting list. zip3 :: [a] -> [b] -> [c] -> [(a, b, c)] -- | 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] -- | O(n). 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] -- | O(n). 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 given Just. -- --

Examples

-- -- Basic usage: -- --
--   >>> maybeToList (Just 7)
--   [7]
--   
-- --
--   >>> maybeToList Nothing
--   []
--   
-- -- One can use maybeToList to avoid pattern matching when combined -- with a function that (safely) works on lists: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> sum $ maybeToList (readMaybe "3")
--   3
--   
--   >>> sum $ maybeToList (readMaybe "")
--   0
--   
maybeToList :: Maybe a -> [a] -- | The 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 -- | 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 <&> -- | 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 -- | flip f takes its (first) two arguments in the reverse -- order of f. -- --
--   >>> flip (++) "hello" "world"
--   "worldhello"
--   
flip :: (a -> b -> c) -> b -> a -> c maxInt :: Int minInt :: Int -- | The fromEnum method restricted to the type Char. ord :: Char -> Int -- | In many situations, the liftM operations can be replaced by -- uses of ap, which promotes function application. -- --
--   return f `ap` x1 `ap` ... `ap` xn
--   
-- -- is equivalent to -- --
--   liftMn f x1 x2 ... xn
--   
ap :: Monad m => m (a -> b) -> m a -> m b -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM5 :: Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM4 :: Monad m => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM3 :: Monad m => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right. For example, -- --
--   liftM2 (+) [0,1] [0,2] = [0,2,1,3]
--   liftM2 (+) (Just 1) Nothing = Nothing
--   
liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r -- | 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 :: e -> SomeException -- | Boolean "and" (&&) :: Bool -> Bool -> Bool infixr 3 && -- | Boolean "or" (||) :: Bool -> Bool -> Bool infixr 2 || -- | Boolean "not" not :: Bool -> Bool -- | The trivial monad transformer, which maps a monad to an equivalent -- monad. data IdentityT (f :: k -> Type) (a :: k) -- | 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 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 -> () -- | 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 -- | The parameterizable maybe monad, obtained by composing an arbitrary -- monad with the Maybe monad. -- -- Computations are actions that may produce a value or exit. -- -- The return function yields a computation that produces that -- value, while >>= sequences two subcomputations, exiting -- if either computation does. newtype MaybeT (m :: Type -> Type) a MaybeT :: m (Maybe a) -> MaybeT (m :: Type -> Type) a [runMaybeT] :: MaybeT (m :: Type -> Type) 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 (m :: Type -> Type) a -- | A class for monads in which exceptions may be thrown. -- -- Instances should obey the following law: -- --
--   throwM e >> x = throwM e
--   
-- -- In other words, throwing an exception short-circuits the rest of the -- monadic computation. class Monad m => MonadThrow (m :: Type -> Type) -- | A class for monads which allow exceptions to be caught, in particular -- exceptions which were thrown by throwM. -- -- Instances should obey the following law: -- --
--   catch (throwM e) f = f e
--   
-- -- Note that the ability to catch an exception does not guarantee -- that we can deal with all possible exit points from a computation. -- Some monads, such as continuation-based stacks, allow for more than -- just a success/failure strategy, and therefore catch -- cannot be used by those monads to properly implement a function -- such as finally. For more information, see MonadMask. class MonadThrow m => MonadCatch (m :: Type -> Type) -- | A class for monads which provide for the ability to account for all -- possible exit points from a computation, and to mask asynchronous -- exceptions. Continuation-based monads are invalid instances of this -- class. -- -- Instances should ensure that, in the following code: -- --
--   fg = f `finally` g
--   
-- -- The action g is called regardless of what occurs within -- f, including async exceptions. Some monads allow f -- to abort the computation via other effects than throwing an exception. -- For simplicity, we will consider aborting and throwing an exception to -- be two forms of "throwing an error". -- -- If f and g both throw an error, the error thrown by -- fg depends on which errors we're talking about. In a monad -- transformer stack, the deeper layers override the effects of the inner -- layers; for example, ExceptT e1 (Except e2) a represents a -- value of type Either e2 (Either e1 a), so throwing both an -- e1 and an e2 will result in Left e2. If -- f and g both throw an error from the same layer, -- instances should ensure that the error from g wins. -- -- Effects other than throwing an error are also overriden by the deeper -- layers. For example, StateT s Maybe a represents a value of -- type s -> Maybe (a, s), so if an error thrown from -- f causes this function to return Nothing, any -- changes to the state which f also performed will be erased. -- As a result, g will see the state as it was before -- f. Once g completes, f's error will be -- rethrown, so g' state changes will be erased as well. This is -- the normal interaction between effects in a monad transformer stack. -- -- By contrast, lifted-base's version of finally always -- discards all of g's non-IO effects, and g never sees -- any of f's non-IO effects, regardless of the layer ordering -- and regardless of whether f throws an error. This is not the -- result of interacting effects, but a consequence of -- MonadBaseControl's approach. class MonadCatch m => MonadMask (m :: Type -> Type) -- | Runs an action with asynchronous exceptions disabled. The action is -- provided a method for restoring the async. environment to what it was -- at the mask call. See Control.Exception's mask. mask :: MonadMask m => ((forall a. () => m a -> m a) -> m b) -> m b -- | Like mask, but the masked computation is not interruptible (see -- Control.Exception's uninterruptibleMask. WARNING: Only -- use if you need to mask exceptions around an interruptible operation -- AND you can guarantee the interruptible operation will only block for -- a short period of time. Otherwise you render the program/thread -- unresponsive and/or unkillable. uninterruptibleMask :: MonadMask m => ((forall a. () => m a -> m a) -> m b) -> m b -- | A generalized version of bracket which uses ExitCase to -- distinguish the different exit cases, and returns the values of both -- the use and release actions. In practice, this extra -- information is rarely needed, so it is often more convenient to use -- one of the simpler functions which are defined in terms of this one, -- such as bracket, finally, onError, and -- bracketOnError. -- -- This function exists because in order to thread their effects through -- the execution of bracket, monad transformers need values to be -- threaded from use to release and from -- release to the output value. -- -- NOTE This method was added in version 0.9.0 of this library. -- Previously, implementation of functions like bracket and -- finally in this module were based on the mask and -- uninterruptibleMask functions only, disallowing some classes of -- tranformers from having MonadMask instances (notably -- multi-exit-point transformers like ExceptT). If you are a -- library author, you'll now need to provide an implementation for this -- method. The StateT implementation demonstrates most of the -- subtleties: -- --
--   generalBracket acquire release use = StateT $ s0 -> do
--     ((b, _s2), (c, s3)) <- generalBracket
--       (runStateT acquire s0)
--       ((resource, s1) exitCase -> case exitCase of
--         ExitCaseSuccess (b, s2) -> runStateT (release resource (ExitCaseSuccess b)) s2
--   
--         -- In the two other cases, the base monad overrides use's state
--         -- changes and the state reverts to s1.
--         ExitCaseException e     -> runStateT (release resource (ExitCaseException e)) s1
--         ExitCaseAbort           -> runStateT (release resource ExitCaseAbort) s1
--       )
--       ((resource, s1) -> runStateT (use resource) s1)
--     return ((b, c), s3)
--   
-- -- The StateT s m implementation of generalBracket -- delegates to the m implementation of generalBracket. -- The acquire, use, and release arguments -- given to StateT's implementation produce actions of type -- StateT s m a, StateT s m b, and StateT s m -- c. In order to run those actions in the base monad, we need to -- call runStateT, from which we obtain actions of type m -- (a, s), m (b, s), and m (c, s). Since each -- action produces the next state, it is important to feed the state -- produced by the previous action to the next action. -- -- In the ExitCaseSuccess case, the state starts at s0, -- flows through acquire to become s1, flows through -- use to become s2, and finally flows through -- release to become s3. In the other two cases, -- release does not receive the value s2, so its action -- cannot see the state changes performed by use. This is fine, -- because in those two cases, an error was thrown in the base monad, so -- as per the usual interaction between effects in a monad transformer -- stack, those state changes get reverted. So we start from s1 -- instead. -- -- Finally, the m implementation of generalBracket -- returns the pairs (b, s) and (c, s). For monad -- transformers other than StateT, this will be some other type -- representing the effects and values performed and returned by the -- use and release actions. The effect part of the -- use result, in this case _s2, usually needs to be -- discarded, since those effects have already been incorporated in the -- release action. -- -- The only effect which is intentionally not incorporated in the -- release action is the effect of throwing an error. In that -- case, the error must be re-thrown. One subtlety which is easy to miss -- is that in the case in which use and release both -- throw an error, the error from release should take priority. -- Here is an implementation for ExceptT which demonstrates how -- to do this. -- --
--   generalBracket acquire release use = ExceptT $ do
--     (eb, ec) <- generalBracket
--       (runExceptT acquire)
--       (eresource exitCase -> case eresource of
--         Left e -> return (Left e) -- nothing to release, acquire didn't succeed
--         Right resource -> case exitCase of
--           ExitCaseSuccess (Right b) -> runExceptT (release resource (ExitCaseSuccess b))
--           ExitCaseException e       -> runExceptT (release resource (ExitCaseException e))
--           _                         -> runExceptT (release resource ExitCaseAbort))
--       (either (return . Left) (runExceptT . use))
--     return $ do
--       -- The order in which we perform those two Either effects determines
--       -- which error will win if they are both Lefts. We want the error from
--       -- release to win.
--       c <- ec
--       b <- eb
--       return (b, c)
--   
generalBracket :: MonadMask m => m a -> (a -> ExitCase b -> m c) -> (a -> m b) -> m (b, c) -- | O(n) Convert a lazy Text into a strict Text. toStrict :: Text -> Text -- | A set of values. A set cannot contain duplicate values. data HashSet a -- | A state transformer monad parameterized by: -- -- -- -- The return function leaves the state unchanged, while -- >>= uses the final state of the first computation as -- the initial state of the second. newtype StateT s (m :: Type -> Type) a StateT :: (s -> m (a, s)) -> StateT s (m :: Type -> Type) a [runStateT] :: StateT s (m :: Type -> Type) a -> s -> m (a, s) -- | 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 -- | Boxed vectors, supporting efficient slicing. data Vector 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 -- | Gets specific component of the state, using a projection function -- supplied. gets :: MonadState s m => (s -> a) -> m a -- | s ^? t returns the 1st element t returns, or -- Nothing if t doesn't return anything. It's trivially -- implemented by passing the First monoid to the getter. -- -- Safe head: -- --
--   >>> [] ^? each
--   Nothing
--   
-- --
--   >>> [1..3] ^? each
--   Just 1
--   
-- -- Converting Either to Maybe: -- --
--   >>> Left 1 ^? _Right
--   Nothing
--   
-- --
--   >>> Right 1 ^? _Right
--   Just 1
--   
-- -- A non-operator version of (^?) is called preview, and -- – like view – it's a bit more general than (^?) (it -- works in MonadReader). If you need the general version, you -- can get it from microlens-mtl; otherwise there's preview -- available in Lens.Micro.Extras. (^?) :: s -> Getting (First a) s a -> Maybe a infixl 8 ^? -- | s ^.. t returns the list of all values that t gets -- from s. -- -- A Maybe contains either 0 or 1 values: -- --
--   >>> Just 3 ^.. _Just
--   [3]
--   
-- -- Gathering all values in a list of tuples: -- --
--   >>> [(1,2),(3,4)] ^.. each.each
--   [1,2,3,4]
--   
(^..) :: s -> Getting (Endo [a]) s a -> [a] infixl 8 ^.. -- | (^.) applies a getter to a value; in other words, it gets a -- value out of a structure using a getter (which can be a lens, -- traversal, fold, etc.). -- -- Getting 1st field of a tuple: -- --
--   (^. _1) :: (a, b) -> a
--   (^. _1) = fst
--   
-- -- When (^.) is used with a traversal, it combines all results -- using the Monoid instance for the resulting type. For instance, -- for lists it would be simple concatenation: -- --
--   >>> ("str","ing") ^. each
--   "string"
--   
-- -- The reason for this is that traversals use Applicative, and the -- Applicative instance for Const uses monoid concatenation -- to combine “effects” of Const. -- -- A non-operator version of (^.) is called view, and -- it's a bit more general than (^.) (it works in -- MonadReader). If you need the general version, you can get it -- from microlens-mtl; otherwise there's view available in -- Lens.Micro.Extras. (^.) :: s -> Getting a s a -> a infixl 8 ^. -- | set is a synonym for (.~). -- -- Setting the 1st component of a pair: -- --
--   set _1 :: x -> (a, b) -> (x, b)
--   set _1 = \x t -> (x, snd t)
--   
-- -- Using it to rewrite (<$): -- --
--   set mapped :: Functor f => a -> f b -> f a
--   set mapped = (<$)
--   
set :: ASetter s t a b -> b -> s -> t -- | (.~) assigns a value to the target. It's the same thing as -- using (%~) with const: -- --
--   l .~ x = l %~ const x
--   
-- -- See set if you want a non-operator synonym. -- -- Here it is used to change 2 fields of a 3-tuple: -- --
--   >>> (0,0,0) & _1 .~ 1 & _3 .~ 3
--   (1,0,3)
--   
(.~) :: ASetter s t a b -> b -> s -> t infixr 4 .~ -- | over is a synonym for (%~). -- -- Getting fmap in a roundabout way: -- --
--   over mapped :: Functor f => (a -> b) -> f a -> f b
--   over mapped = fmap
--   
-- -- Applying a function to both components of a pair: -- --
--   over both :: (a -> b) -> (a, a) -> (b, b)
--   over both = \f t -> (f (fst t), f (snd t))
--   
-- -- Using over _2 as a replacement for -- second: -- --
--   >>> over _2 show (10,20)
--   (10,"20")
--   
over :: ASetter s t a b -> (a -> b) -> s -> t -- | (%~) applies a function to the target; an alternative -- explanation is that it is an inverse of sets, which turns a -- setter into an ordinary function. mapped %~ -- reverse is the same thing as fmap -- reverse. -- -- See over if you want a non-operator synonym. -- -- Negating the 1st element of a pair: -- --
--   >>> (1,2) & _1 %~ negate
--   (-1,2)
--   
-- -- Turning all Lefts in a list to upper case: -- --
--   >>> (mapped._Left.mapped %~ toUpper) [Left "foo", Right "bar"]
--   [Left "FOO",Right "bar"]
--   
(%~) :: ASetter s t a b -> (a -> b) -> s -> t infixr 4 %~ -- | Gives access to the 1st field of a tuple (up to 5-tuples). -- -- Getting the 1st component: -- --
--   >>> (1,2,3,4,5) ^. _1
--   1
--   
-- -- Setting the 1st component: -- --
--   >>> (1,2,3) & _1 .~ 10
--   (10,2,3)
--   
-- -- Note that this lens is lazy, and can set fields even of -- undefined: -- --
--   >>> set _1 10 undefined :: (Int, Int)
--   (10,*** Exception: Prelude.undefined
--   
-- -- This is done to avoid violating a lens law stating that you can get -- back what you put: -- --
--   >>> view _1 . set _1 10 $ (undefined :: (Int, Int))
--   10
--   
-- -- The implementation (for 2-tuples) is: -- --
--   _1 f t = (,) <$> f    (fst t)
--                <*> pure (snd t)
--   
-- -- or, alternatively, -- --
--   _1 f ~(a,b) = (\a' -> (a',b)) <$> f a
--   
-- -- (where ~ means a lazy pattern). -- -- _2, _3, _4, and _5 are also available (see -- below). _1 :: Field1 s t a b => Lens s t a b _2 :: Field2 s t a b => Lens s t a b _3 :: Field3 s t a b => Lens s t a b _4 :: Field4 s t a b => Lens s t a b _5 :: Field5 s t a b => Lens s t a b -- | Lens s t a b is the lowest common denominator of a setter and -- a getter, something that has the power of both; it has a -- Functor constraint, and since both Const and -- Identity are functors, it can be used whenever a getter or a -- setter is needed. -- -- type Lens s t a b = forall (f :: Type -> Type). Functor f => a -> f b -> s -> f t -- | This is a type alias for monomorphic lenses which don't change the -- type of the container (or of the value inside). type Lens' s a = Lens s s a a -- | Traversal s t a b is a generalisation of Lens which -- allows many targets (possibly 0). It's achieved by changing the -- constraint to Applicative instead of Functor – indeed, -- the point of Applicative is that you can combine effects, which -- is just what we need to have many targets. -- -- Ultimately, traversals should follow 2 laws: -- --
--   t pure ≡ pure
--   fmap (t f) . t g ≡ getCompose . t (Compose . fmap f . g)
--   
-- -- The 1st law states that you can't change the shape of the structure or -- do anything funny with elements (traverse elements which aren't in the -- structure, create new elements out of thin air, etc.). The 2nd law -- states that you should be able to fuse 2 identical traversals into -- one. For a more detailed explanation of the laws, see this blog -- post (if you prefer rambling blog posts), or The Essence Of The -- Iterator Pattern (if you prefer papers). -- -- Traversing any value twice is a violation of traversal laws. You can, -- however, traverse values in any order. type Traversal s t a b = forall (f :: Type -> Type). Applicative f => a -> f b -> s -> f t -- | This is a type alias for monomorphic traversals which don't change the -- type of the container (or of the values inside). type Traversal' s a = Traversal s s a a -- | 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 () -- | Retrieves a function of the current environment. asks :: MonadReader r m => (r -> a) -> m a -- | The reader monad transformer, which adds a read-only environment to -- the given monad. -- -- The return function ignores the environment, while -- >>= passes the inherited environment to both -- subcomputations. newtype ReaderT r (m :: Type -> Type) a ReaderT :: (r -> m a) -> ReaderT r (m :: Type -> Type) a [runReaderT] :: ReaderT r (m :: Type -> Type) a -> r -> m a -- | preuse is (^?) (or preview) which implicitly -- operates on the state – it takes the state and applies a traversal (or -- fold) to it to extract the 1st element the traversal points at. -- --
--   preuse l = gets (preview l)
--   
preuse :: MonadState s m => Getting (First a) s a -> m (Maybe a) -- | use is (^.) (or view) which implicitly operates -- on the state; for instance, if your state is a record containing a -- field foo, you can write -- --
--   x <- use foo
--   
-- -- to extract foo from the state. In other words, use is -- the same as gets, but for getters instead of functions. -- -- The implementation of use is straightforward: -- --
--   use l = gets (view l)
--   
-- -- If you need to extract something with a fold or traversal, you need -- preuse. use :: MonadState s m => Getting a s a -> m a -- | preview is a synonym for (^?), generalised for -- MonadReader (just like view, which is a synonym for -- (^.)). -- --
--   >>> preview each [1..5]
--   Just 1
--   
preview :: MonadReader s m => Getting (First a) s a -> m (Maybe a) -- | view is a synonym for (^.), generalised for -- MonadReader (we are able to use it instead of (^.) since -- functions are instances of the MonadReader class): -- --
--   >>> view _1 (1, 2)
--   1
--   
-- -- When you're using Reader for config and your config type has -- lenses generated for it, most of the time you'll be using view -- instead of asks: -- --
--   doSomething :: (MonadReader Config m) => m Int
--   doSomething = do
--     thingy        <- view setting1  -- same as “asks (^. setting1)”
--     anotherThingy <- view setting2
--     ...
--   
view :: MonadReader s m => Getting a s 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 variant of modify in which the computation is strict in the -- new state. modify' :: MonadState s m => (s -> s) -> m () -- | The inverse of ExceptT. runExceptT :: ExceptT e m a -> m (Either e a) -- | Runs a Reader and extracts the final value from it. (The -- inverse of reader.) runReader :: Reader r a -> r -> a -- | 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 -- | Async safe version of bracketOnError bracketOnError :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c -- | Async safe version of finally finally :: MonadMask m => m a -> m b -> m a -- | Async safe version of bracket_ bracket_ :: MonadMask m => m a -> m b -> m c -> m c -- | Async safe version of bracket bracket :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c -- | Async safe version of onException onException :: MonadMask m => m a -> m b -> m a -- | try specialized to catch all synchronous exceptions tryAny :: MonadCatch m => m a -> m (Either SomeException a) -- | Same as upstream try, but will not catch asynchronous -- exceptions try :: (MonadCatch m, Exception e) => m a -> m (Either e a) -- | Flipped version of catchAny handleAny :: MonadCatch m => (SomeException -> m a) -> m a -> m a -- | catch specialized to catch all synchronous exception catchAny :: MonadCatch m => m a -> (SomeException -> m a) -> m a -- | Same as upstream catch, but will not catch asynchronous -- exceptions catch :: (MonadCatch m, Exception e) => m a -> (e -> m a) -> m a -- | Synonym for throw throwM :: (MonadThrow m, Exception e) => e -> m a -- | Strict version of modifyTVar. modifyTVar' :: TVar a -> (a -> a) -> STM () -- | O(c) Convert a strict Text into a lazy Text. fromStrict :: Text -> Text -- | O(n) Joins words using single space characters. unwords :: [Text] -> Text -- | O(n) Joins lines, after appending a terminating newline to -- each. unlines :: [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) Breaks a Text up into a list of words, delimited by -- Chars representing white space. words :: Text -> [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 -- | 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 -- | Replace an invalid input byte with the Unicode replacement character -- U+FFFD. lenientDecode :: OnDecodeError -- | Throw a UnicodeException if decoding fails. strictDecode :: OnDecodeError -- | 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 -- | A handler for a decoding error. type OnDecodeError = OnError Word8 Char -- | An exception type for representing Unicode encoding errors. data UnicodeException -- | Convert a ExceptT computation to MaybeT, discarding the -- value of any exception. exceptToMaybeT :: forall (m :: Type -> Type) e a. Functor m => ExceptT e m a -> MaybeT m a -- | Convert a MaybeT computation to ExceptT, with a default -- exception value. maybeToExceptT :: forall (m :: Type -> Type) e a. Functor m => e -> MaybeT m a -> ExceptT e m a -- | This type class allows to implement variadic composition operator. class SuperComposition a b c | a b -> c -- | Allows to apply function to result of another function with multiple -- arguments. -- --
--   >>> (show ... (+)) 1 2
--   "3"
--   
--   >>> show ... 5
--   "5"
--   
--   >>> (null ... zip5) [1] [2] [3] [] [5]
--   True
--   
-- -- Inspired by -- http://stackoverflow.com/questions/9656797/variadic-compose-function. -- --

Performance

-- -- To check the performance there was done a bunch of benchmarks. -- Benchmarks were made on examples given above and also on the functions -- of many arguments. The results are showing that the operator -- (...) performs as fast as plain applications of the operator -- (.) on almost all the tests, but (...) leads to the -- performance draw-down if ghc fails to inline it. Slow -- behavior was noticed on functions without type specifications. That's -- why keep in mind that providing explicit type declarations for -- functions is very important when using (...). Relying on type -- inference will lead to the situation when all optimizations disappear -- due to very general inferred type. However, functions without type -- specification but with applied INLINE pragma are fast again. (...) :: SuperComposition a b c => a -> b -> c infixl 8 ... -- | Infix application. -- --
--   f :: Either String $ Maybe Int
--   =
--   f :: Either String (Maybe Int)
--   
type (f :: k1 -> k) $ (a :: k1) = f a infixr 2 $ -- | Map several constraints over several variables. -- --
--   f :: Each [Show, Read] [a, b] => a -> b -> String
--   =
--   f :: (Show a, Show b, Read a, Read b) => a -> b -> String
--   
-- -- To specify list with single constraint / variable, don't forget to -- prefix it with ': -- --
--   f :: Each '[Show] [a, b] => a -> b -> String
--   
type family Each (c :: [k -> Constraint]) (as :: [k]) -- | Map several constraints over a single variable. Note, that With a -- b ≡ Each a '[b] -- --
--   a :: With [Show, Read] a => a -> a
--   =
--   a :: (Show a, Read a) => a -> a
--   
type With (a :: [k -> Constraint]) (b :: k) = a <+> b -- | Generalized version of show. show :: forall b a. (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 -- | undefined that leaves a warning in code on every usage. undefined :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => a -- | Version of traceId that leaves a warning. traceId :: Text -> Text -- | Version of traceM that leaves a warning and takes Text. traceM :: Monad m => Text -> m () -- | Version of traceShowM that leaves a warning. traceShowM :: (Show a, Monad m) => a -> m () -- | Version of traceShowId that leaves a warning. Useful to tag -- printed data, for instance: -- --
--   traceShowIdWith ("My data: ", ) (veryLargeExpression)
--   
traceShowIdWith :: Show s => (a -> s) -> a -> a -- | Version of traceId that leaves a warning. Useful to tag printed -- data, for instance: -- --
--   traceIdWith (x -> "My data: " <> show x) (veryLargeExpression)
--   
-- -- This is especially useful with custom formatters: -- --
--   traceIdWith (x -> "My data: " <> pretty x) (veryLargeExpression)
--   
traceIdWith :: (a -> Text) -> a -> a -- | Version of traceShowId that leaves a warning. traceShowId :: Show a => a -> a -- | Version of traceShow that leaves a warning. traceShow :: Show a => a -> b -> b -- | error that takes Text as an argument. error :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => Text -> a -- | Version of trace that leaves a warning and takes Text. trace :: Text -> a -> a -- | Similar to undefined but data type. data Undefined Undefined :: Undefined -- | 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 hPrint hPrint :: (MonadIO m, Show a) => Handle -> a -> m () -- | Lifted version of print. print :: forall a m. (MonadIO m, Show a) => a -> m () -- | Write a string like value to stdout appending a newline -- character. putStrLn :: (Print a, MonadIO m) => a -> m () -- | Write a string like value to stdout/. putStr :: (Print a, MonadIO m) => a -> m () -- | Write a string like value a to a supplied Handle, -- appending a newline character. hPutStrLn :: (Print a, MonadIO m) => Handle -> a -> m () -- | Write a string like value a to a supplied Handle. hPutStr :: (Print a, MonadIO m) => Handle -> a -> m () -- | Support class to overload writing of string like values. class Print a -- | 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] -- | 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 -- | Throws error for Maybe if Nothing is given. Operates -- over MonadError. note :: MonadError e m => e -> Maybe 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 e
--       | Just (_ :: NodeAttackedError) <- fromException e = True
--       | Just DialogUnexpected{} <- fromException e = True
--       | otherwise = False
--   
-- -- you can use Exc pattern synonym: -- --
--   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 :: 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]) -- | Monadic and constrained to Container 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 :: (Container f, Monad m) => (Element f -> m Bool) -> f -> m Bool -- | Monadic and constrained to Container 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 :: (Container f, Monad m) => (Element f -> m Bool) -> f -> m Bool -- | Monadic and constrained to Container version of or. -- --
--   >>> orM [Just True, Just False]
--   Just True
--   
--   >>> orM [Just True, Nothing]
--   Just True
--   
--   >>> orM [Nothing, Just True]
--   Nothing
--   
orM :: (Container f, Element f ~ m Bool, Monad m) => f -> m Bool -- | Monadic and constrained to Container 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 :: (Container f, Element f ~ m Bool, Monad m) => f -> m Bool -- | Like concatMapM, but has its arguments flipped, so can be used -- instead of the common fmap concat $ forM pattern. concatForM :: (Applicative f, Monoid m, Container (l m), Element (l m) ~ m, Traversable l) => l a -> (a -> f m) -> f m -- | Lifting bind into a monad. Generalized version of concatMap -- that works with a monadic predicate. Old and simpler specialized to -- list version had next type: -- --
--   concatMapM :: Monad m => (a -> m [b]) -> [a] -> m [b]
--   
-- -- Side note: previously it had type -- --
--   concatMapM :: (Applicative q, Monad m, Traversable m)
--              => (a -> q (m b)) -> m a -> q (m b)
--   
-- -- Such signature didn't allow to use this function when traversed -- container type and type of returned by function-argument differed. Now -- you can use it like e.g. -- --
--   concatMapM readFile files >>= putTextLn
--   
concatMapM :: (Applicative f, Monoid m, Container (l m), Element (l m) ~ m, Traversable l) => (a -> f m) -> l a -> f m -- | Constrained to Container version of asum. -- --
--   >>> asum [Nothing, Just [False, True], Nothing, Just [True]]
--   Just [False,True]
--   
asum :: (Container t, Alternative f, Element t ~ f a) => t -> f a -- | Constrained to Container version of sequence_. -- --
--   >>> sequence_ [putTextLn "foo", print True]
--   foo
--   True
--   
sequence_ :: (Container t, Monad m, Element t ~ m a) => t -> m () -- | Constrained to Container version of sequenceA_. -- --
--   >>> sequenceA_ [putTextLn "foo", print True]
--   foo
--   True
--   
sequenceA_ :: (Container t, Applicative f, Element t ~ f a) => t -> f () -- | Constrained to Container version of forM_. -- --
--   >>> forM_ [True, False] print
--   True
--   False
--   
forM_ :: (Container t, Monad m) => t -> (Element t -> m b) -> m () -- | Constrained to Container version of mapM_. -- --
--   >>> mapM_ print [True, False]
--   True
--   False
--   
mapM_ :: (Container t, Monad m) => (Element t -> m b) -> t -> m () -- | Constrained to Container version of for_. -- --
--   >>> for_ [1 .. 5 :: Int] $ \i -> when (even i) (print i)
--   2
--   4
--   
for_ :: (Container t, Applicative f) => t -> (Element t -> f b) -> f () -- | Constrained to Container version of traverse_. -- --
--   >>> traverse_ putTextLn ["foo", "bar"]
--   foo
--   bar
--   
traverse_ :: (Container t, Applicative f) => (Element t -> f b) -> t -> f () -- | Stricter version of product. -- --
--   >>> product [1..10]
--   3628800
--   
--   >>> product (Right 3)
--   ...
--       • Do not use 'Foldable' methods on Either
--         Suggestions:
--             Instead of
--                 for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f ()
--             use
--                 whenJust  :: Applicative f => Maybe a    -> (a -> f ()) -> f ()
--                 whenRight :: Applicative f => Either l r -> (r -> f ()) -> f ()
--   ...
--             Instead of
--                 fold :: (Foldable t, Monoid m) => t m -> m
--             use
--                 maybeToMonoid :: Monoid m => Maybe m -> m
--   ...
--   
product :: (Container t, Num (Element t)) => t -> Element t -- | Stricter version of sum. -- --
--   >>> sum [1..10]
--   55
--   
--   >>> sum (Just 3)
--   ...
--       • Do not use 'Foldable' methods on Maybe
--         Suggestions:
--             Instead of
--                 for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f ()
--             use
--                 whenJust  :: Applicative f => Maybe a    -> (a -> f ()) -> f ()
--                 whenRight :: Applicative f => Either l r -> (r -> f ()) -> f ()
--   ...
--             Instead of
--                 fold :: (Foldable t, Monoid m) => t m -> m
--             use
--                 maybeToMonoid :: Monoid m => Maybe m -> m
--   ...
--   
sum :: (Container t, Num (Element t)) => t -> Element t -- | Similar to foldl' but takes a function with its arguments -- flipped. -- --
--   >>> flipfoldl' (/) 5 [2,3] :: Rational
--   15 % 2
--   
flipfoldl' :: (Container t, Element t ~ a) => (a -> b -> b) -> b -> t -> b -- | Type class for data types that can be converted to List of Pairs. You -- can define ToPairs by just defining toPairs function. -- -- But the following laws should be met: -- --
--   toPairs m ≡ zip (keys m) (elems m)
--   keysmap fst . toPairs
--   elemsmap snd . toPairs
--   
class ToPairs t -- | Converts the structure to the list of the key-value pairs. -- >>> toPairs (HashMap.fromList [(a, "xxx"), -- (b, "yyy")]) [(a,"xxx"),(b,"yyy")] toPairs :: ToPairs t => t -> [(Key t, Val t)] -- | Converts the structure to the list of the keys. -- --
--   >>> keys (HashMap.fromList [('a', "xxx"), ('b', "yyy")])
--   "ab"
--   
keys :: ToPairs t => t -> [Key t] -- | Converts the structure to the list of the values. -- --
--   >>> elems (HashMap.fromList [('a', "xxx"), ('b', "yyy")])
--   ["xxx","yyy"]
--   
elems :: ToPairs t => t -> [Val t] -- | Type of element for some container. Implemented as an asscociated type -- family because some containers are monomorphic over element type (like -- Text, IntSet, etc.) so we can't implement nice interface -- using old higher-kinded types approach. Implementing this as an -- associated type family instead of top-level family gives you more -- control over element types. type family Element t -- | Very similar to Foldable but also allows instances for -- monomorphic types like Text but forbids instances for -- Maybe and similar. This class is used as a replacement for -- Foldable type class. It solves the following problems: -- --
    --
  1. length, foldr and other functions work on more types -- for which it makes sense.
  2. --
  3. You can't accidentally use length on polymorphic -- Foldable (like list), replace list with Maybe and then -- debug error for two days.
  4. --
  5. More efficient implementaions of functions for polymorphic types -- (like elem for Set).
  6. --
-- -- The drawbacks: -- --
    --
  1. Type signatures of polymorphic functions look more scary.
  2. --
  3. Orphan instances are involved if you want to use foldr (and -- similar) on types from libraries.
  4. --
class Container t where { -- | Type of element for some container. Implemented as an asscociated type -- family because some containers are monomorphic over element type (like -- Text, IntSet, etc.) so we can't implement nice interface -- using old higher-kinded types approach. Implementing this as an -- associated type family instead of top-level family gives you more -- control over element types. type family Element t; type Element t = ElementDefault t; } -- | Convert container to list of elements. -- --
--   >>> toList @Text "aba"
--   "aba"
--   
--   >>> :t toList @Text "aba"
--   toList @Text "aba" :: [Char]
--   
toList :: Container t => t -> [Element t] -- | Checks whether container is empty. -- --
--   >>> null @Text ""
--   True
--   
--   >>> null @Text "aba"
--   False
--   
null :: Container t => t -> Bool foldr :: Container t => (Element t -> b -> b) -> b -> t -> b foldl :: Container t => (b -> Element t -> b) -> b -> t -> b foldl' :: Container t => (b -> Element t -> b) -> b -> t -> b length :: Container t => t -> Int elem :: Container t => Element t -> t -> Bool maximum :: Container t => t -> Element t minimum :: Container t => t -> Element t foldMap :: (Container t, Monoid m) => (Element t -> m) -> t -> m fold :: Container t => t -> Element t foldr' :: Container t => (Element t -> b -> b) -> b -> t -> b foldr1 :: Container t => (Element t -> Element t -> Element t) -> t -> Element t foldl1 :: Container t => (Element t -> Element t -> Element t) -> t -> Element t notElem :: Container t => Element t -> t -> Bool all :: Container t => (Element t -> Bool) -> t -> Bool any :: Container t => (Element t -> Bool) -> t -> Bool and :: Container t => t -> Bool or :: Container t => t -> Bool find :: Container t => (Element t -> Bool) -> t -> Maybe (Element t) safeHead :: Container t => t -> Maybe (Element t) type family OneItem x -- | Type class for types that can be created from one element. -- singleton is lone name for this function. Also constructions -- of different type differ: :[] for lists, two arguments for -- Maps. Also some data types are monomorphic. -- --
--   >>> one True :: [Bool]
--   [True]
--   
--   >>> one 'a' :: Text
--   "a"
--   
--   >>> one (3, "hello") :: HashMap Int String
--   fromList [(3,"hello")]
--   
class One x where { type family OneItem x; } -- | Create a list, map, Text, etc from a single element. one :: One x => OneItem x -> x -- | 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 whenRight. whenRightM :: Monad m => m (Either l r) -> (r -> m ()) -> m () -- | Applies given action to Either content if Right is -- given. whenRight :: Applicative f => Either l r -> (r -> f ()) -> f () -- | Monadic version of whenLeft. whenLeftM :: Monad m => m (Either l r) -> (l -> m ()) -> m () -- | Applies given action to Either content if Left is given. whenLeft :: Applicative f => Either l r -> (l -> f ()) -> f () -- | 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 -- | Extracts value from Right or return given default value. -- --
--   >>> fromRight 0 (Left 3)
--   0
--   
--   >>> fromRight 0 (Right 5)
--   5
--   
fromRight :: b -> Either a b -> b -- | Extracts value from Left or return given default value. -- --
--   >>> fromLeft 0 (Left 3)
--   3
--   
--   >>> fromLeft 0 (Right 5)
--   0
--   
fromLeft :: a -> Either a b -> 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) -- | Opens a file, manipulates it with the provided function and closes the -- handle before returning. The Handle can be written to using the -- hPutStr and hPutStrLn functions. -- -- withFile is essentially the bracket pattern, specialized -- to files. This should be preferred over openFile + -- hClose as it properly deals with (asynchronous) exceptions. In -- cases where withFile is insufficient, for instance because the -- it is not statically known when manipulating the Handle has -- finished, one should consider other safe paradigms for resource usage, -- such as the ResourceT transformer from the resourcet -- package, before resorting to openFile and hClose. withFile :: (MonadIO m, MonadMask m) => FilePath -> IOMode -> (Handle -> m a) -> m a -- | Close a file handle -- -- See also withFile for more information. hClose :: MonadIO m => Handle -> m () -- | Lifted version of openFile. -- -- See also withFile for more information. openFile :: MonadIO m => FilePath -> IOMode -> m Handle -- | 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 a -- | 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 <<$>> -- | map generalized to Functor. -- --
--   >>> map not (Just True)
--   Just False
--   
--   >>> map not [True,False,True,True]
--   [False,True,False,False]
--   
map :: Functor f => (a -> b) -> f a -> f b -- | Stricter version of $ operator. Default Prelude defines this at -- the toplevel module, so we do as well. -- --
--   >>> const 3 $ Prelude.undefined
--   3
--   
--   >>> const 3 $! Prelude.undefined
--   *** Exception: Prelude.undefined
--   ...
--   
($!) :: (a -> b) -> a -> b infixr 0 $! -- | Shorter alias for pure (). -- --
--   >>> pass :: Maybe ()
--   Just ()
--   
pass :: Applicative f => f () -- | This module is intended to be imported instead of Lorentz by -- Indigo modules. -- -- The idea is to avoid repeating common hiding rules and to not -- export any of Lorentz's Instructions and Macros. module Indigo.Lorentz data Bool False :: Bool True :: Bool -- | 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 -- | A space-efficient representation of a Word8 vector, supporting -- many efficient operations. -- -- A ByteString contains 8-bit bytes, or by using the operations -- from Data.ByteString.Char8 it can be interpreted as containing -- 8-bit characters. data ByteString -- | A Map from keys k to values a. -- -- The Semigroup operation for Map is union, which -- prefers values from the left operand. If m1 maps a key -- k to a value a1, and m2 maps the same key -- to a different value a2, then their union m1 <> -- m2 maps k to a1. data Map k a -- | From a Dict, takes a value in an environment where the instance -- witnessed by the Dict is in scope, and evaluates it. -- -- Essentially a deconstruction of a Dict into its -- continuation-style form. -- -- Can also be used to deconstruct an entailment, a :- b, -- using a context a. -- --
--   withDict :: Dict c -> (c => r) -> r
--   withDict :: a => (a :- c) -> (c => r) -> r
--   
withDict :: HasDict c e => e -> (c => r) -> r -- | A set of values a. data Set a -- | A class for types with a default value. class Default a -- | The default value for this type. def :: Default a => a -- | A variation of arg for optional arguments. Requires a default -- value to handle the case when the optional argument was omitted: -- --
--   fn (argDef #answer 42 -> ans) = ...
--   
-- -- In case you want to get a value wrapped in Maybe instead, use -- argF or ArgF. argDef :: forall (name :: Symbol) a. Name name -> a -> (name :? a) -> a -- | argF is similar to arg: it unwraps a named parameter -- with the specified name. The difference is that the result of -- argF is inside an arity wrapper, which is Identity for -- normal parameters and Maybe for optional parameters. argF :: forall (name :: Symbol) f a. Name name -> NamedF f a name -> f a -- | arg unwraps a named parameter with the specified name. One way -- to use it is to match on arguments with -XViewPatterns: -- --
--   fn (arg #t -> t) (arg #f -> f) = ...
--   
-- -- This way, the names of parameters can be inferred from the patterns: -- no type signature for fn is required. In case a type -- signature for fn is provided, the parameters must come in the -- same order: -- --
--   fn :: "t" :! Integer -> "f" :! Integer -> ...
--   fn (arg #t -> t) (arg #f -> f) = ... -- ok
--   fn (arg #f -> f) (arg #t -> t) = ... -- does not typecheck
--   
arg :: forall (name :: Symbol) a. Name name -> (name :! a) -> a -- | Infix notation for the type of a named parameter. type (name :: Symbol) :! a = NamedF Identity a name -- | Infix notation for the type of an optional named parameter. type (name :: Symbol) :? a = NamedF Maybe a name -- | A record is parameterized by a universe u, an interpretation -- f and a list of rows rs. The labels or indices of -- the record are given by inhabitants of the kind u; the type -- of values at any label r :: u is given by its interpretation -- f r :: *. data Rec (a :: u -> Type) (b :: [u]) [RNil] :: forall u (a :: u -> Type). Rec a ('[] :: [u]) [:&] :: forall u (a :: u -> Type) (r :: u) (rs :: [u]). !a r -> !Rec a rs -> Rec a (r : rs) infixr 7 :& constructStack :: forall dt (fields :: [Type]) (st :: [Type]). (InstrConstructC dt, ToTs fields ~ ToTs (ConstructorFieldTypes dt), KnownList fields) => (fields ++ st) :-> (dt & st) deconstruct :: forall dt (fields :: [Type]) (st :: [Type]). (InstrDeconstructC dt, KnownList fields, ToTs fields ~ ToTs (ConstructorFieldTypes dt)) => (dt & st) :-> (fields ++ st) fieldCtor :: forall (st :: [Type]) f. HasCallStack => (st :-> (f & st)) -> FieldConstructor st f getField :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt & st) :-> (GetFieldType dt name & (dt : st)) getFieldNamed :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt & st) :-> ((name :! GetFieldType dt name) & (dt : st)) modifyField :: forall dt (name :: Symbol) (st :: [Type]). (InstrGetFieldC dt name, InstrSetFieldC dt name) => Label name -> (forall (st0 :: [Type]). () => (GetFieldType dt name : st0) :-> (GetFieldType dt name : st0)) -> (dt & st) :-> (dt & st) toField :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt & st) :-> (GetFieldType dt name & st) toFieldNamed :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt & st) :-> ((name :! GetFieldType dt name) & st) unwrapUnsafe_ :: forall dt (name :: Symbol) (st :: [Type]). InstrUnwrapC dt name => Label name -> (dt & st) :-> (CtorOnlyField name dt : st) wrapOne :: forall dt (name :: Symbol) (st :: [Type]). InstrWrapOneC dt name => Label name -> (CtorOnlyField name dt : st) :-> (dt & st) wrap_ :: forall dt (name :: Symbol) (st :: [Type]). InstrWrapC dt name => Label name -> AppendCtorField (GetCtorField dt name) st :-> (dt & st) type (n :: Symbol) := ty = 'NamedField n ty class CaseArrow (name :: Symbol) body clause | clause -> name, clause -> body (/->) :: CaseArrow name body clause => Label name -> body -> clause data CaseClauseL (inp :: [Type]) (out :: [Type]) (param :: CaseClauseParam) [CaseClauseL] :: forall (x :: CtorField) (inp :: [Type]) (out :: [Type]) (ctor :: Symbol). (AppendCtorField x inp :-> out) -> CaseClauseL inp out ('CaseClauseParam ctor x) type CaseTC dt (out :: [Type]) (inp :: [Type]) clauses = (InstrCaseC dt, RMap CaseClauses dt, RecFromTuple clauses, clauses ~ Rec CaseClauseL inp out CaseClauses dt) type HasFieldOfType dt (fname :: Symbol) fieldTy = (HasField dt fname, GetFieldType dt fname ~ fieldTy) type family HasFieldsOfType dt (fs :: [NamedField]) data NamedField NamedField :: Symbol -> Type -> NamedField type ConstructorFieldTypes dt = GFieldTypes Rep dt type InstrConstructC dt = (GenericIsoValue dt, GInstrConstruct Rep dt) newtype (inp :: [Type]) :-> (out :: [Type]) LorentzInstr :: RemFail Instr (ToTs inp) (ToTs out) -> (:->) (inp :: [Type]) (out :: [Type]) [unLorentzInstr] :: (:->) (inp :: [Type]) (out :: [Type]) -> RemFail Instr (ToTs inp) (ToTs out) data Label (name :: Symbol) [Label] :: forall (name :: Symbol). KnownSymbol name => Label name type a & (b :: [Type]) = a : b class HasAnnotation a type family ToT a :: T data Address newtype BigMap k v BigMap :: Map k v -> BigMap k v [unBigMap] :: BigMap k v -> Map k v data ChainId data ContractRef arg ContractRef :: Address -> SomeEntrypointCall arg -> ContractRef arg [crAddress] :: ContractRef arg -> Address [crEntrypoint] :: ContractRef arg -> SomeEntrypointCall arg data EpAddress EpAddress :: Address -> EpName -> EpAddress [eaAddress] :: EpAddress -> Address [eaEntrypoint] :: EpAddress -> EpName data KeyHash data MText data Mutez type Operation = Operation' Instr data PublicKey data Signature data Timestamp class (ArithOp aop ToT n ToT m, NiceComparable n, NiceComparable m, ToT ArithResHs aop n m ~ ArithRes aop ToT n ToT m) => ArithOpHs aop n m where { type family ArithResHs aop n m; } type family ArithResHs aop n m class (UnaryArithOp aop ToT n, NiceComparable n, ToT UnaryArithResHs aop n ~ UnaryArithRes aop ToT n) => UnaryArithOpHs aop n where { type family UnaryArithResHs aop n; } type family UnaryArithResHs aop n type NiceComparable n = (KnownValue n, Comparable ToT n) (#) :: forall (a :: [Type]) (b :: [Type]) (c :: [Type]). (a :-> b) -> (b :-> c) -> a :-> c (##) :: forall (a :: [Type]) (b :: [Type]) (c :: [Type]). (a :-> b) -> (b :-> c) -> a :-> c pattern FI :: (forall (out' :: [T]). () => Instr (ToTs inp) out') -> inp :-> out pattern I :: Instr (ToTs inp) (ToTs out) -> inp :-> out iAnyCode :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> Instr (ToTs inp) (ToTs out) iForceNotFail :: forall (i :: [Type]) (o :: [Type]). (i :-> o) -> i :-> o iGenericIf :: forall (a :: [Type]) (b :: [Type]) (c :: [Type]) (s :: [Type]). (forall (s' :: [T]). () => Instr (ToTs a) s' -> Instr (ToTs b) s' -> Instr (ToTs c) s') -> (a :-> s) -> (b :-> s) -> c :-> s iMapAnyCode :: forall (i1 :: [Type]) (i2 :: [Type]) (o :: [Type]). (forall (o' :: [T]). () => Instr (ToTs i1) o' -> Instr (ToTs i2) o') -> (i1 :-> o) -> i2 :-> o iNonFailingCode :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => (inp :-> out) -> Instr (ToTs inp) (ToTs out) iWithVarAnnotations :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => [Text] -> (inp :-> out) -> inp :-> out optimizeLorentz :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> inp :-> out optimizeLorentzWithConf :: forall (inp :: [Type]) (out :: [Type]). OptimizerConf -> (inp :-> out) -> inp :-> out parseLorentzValue :: KnownValue v => Text -> Either ParseLorentzError v transformBytesLorentz :: forall (inp :: [Type]) (out :: [Type]). Bool -> (ByteString -> ByteString) -> (inp :-> out) -> inp :-> out transformStringsLorentz :: forall (inp :: [Type]) (out :: [Type]). Bool -> (MText -> MText) -> (inp :-> out) -> inp :-> out type (%>) = (:->) type ContractCode cp st = '[(cp, st)] :-> ContractOut st type ContractOut st = '[([Operation], st)] type Lambda i o = '[i] :-> '[o] class MapLorentzInstr instr mapLorentzInstr :: MapLorentzInstr instr => (forall (i :: [Type]) (o :: [Type]). () => (i :-> o) -> i :-> o) -> instr -> instr data SomeContractCode [SomeContractCode] :: forall cp st. (NiceParameterFull cp, NiceStorage st) => ContractCode cp st -> SomeContractCode type NiceParameterFull cp = (Typeable cp, ParameterDeclaresEntrypoints cp) type NiceStorage a = (HasAnnotation a, KnownValue a, ProperStorageBetterErrors ToT a) class (IsoValue a, Typeable a) => KnownValue a allowCheckedCoerce :: forall k1 k2 (a :: k1) (b :: k2). Dict (CanCastTo a b, CanCastTo b a) allowCheckedCoerceTo :: forall k1 k2 (b :: k1) (a :: k2). Dict (CanCastTo a b) castDummyG :: (Generic a, Generic b, GCanCastTo (Rep a) (Rep b)) => Proxy a -> Proxy b -> () checkedCoerce :: (CanCastTo a b, Coercible a b) => a -> b checkedCoerce_ :: forall a b (s :: [Type]). Castable_ a b => (a : s) :-> (b : s) checkedCoercing_ :: forall a b (s :: [Type]). Coercible_ a b => ((b : s) :-> (b : s)) -> (a : s) :-> (a : s) coerceUnwrap :: forall a (s :: [Type]). Wrappable a => (a : s) :-> (Unwrappable a : s) coerceWrap :: forall a (s :: [Type]). Wrappable a => (Unwrappable a : s) :-> (a : s) fakeCoerce :: forall (s1 :: [Type]) (s2 :: [Type]). s1 :-> s2 fakeCoercing :: forall (s1 :: [Type]) (s2 :: [Type]) (s1' :: [Type]) (s2' :: [Type]). (s1 :-> s2) -> s1' :-> s2' forcedCoerce :: Coercible a b => a -> b forcedCoerce_ :: forall a b (s :: [Type]). MichelsonCoercible a b => (a & s) :-> (b & s) fromNamed :: forall (name :: Symbol) a (s :: [Type]). Label name -> (NamedF Identity a name : s) :-> (a : s) gForcedCoerce_ :: forall k t (a :: k) (b :: k) (s :: [Type]). MichelsonCoercible (t a) (t b) => (t a : s) :-> (t b : s) toNamed :: forall (name :: Symbol) a (s :: [Type]). Label name -> (a : s) :-> (NamedF Identity a name : s) class CanCastTo (a :: k) (b :: k1) castDummy :: CanCastTo a b => Proxy a -> Proxy b -> () type Castable_ a b = (MichelsonCoercible a b, CanCastTo a b) type Coercible_ a b = (MichelsonCoercible a b, CanCastTo a b, CanCastTo b a) type MichelsonCoercible a b = ToT a ~ ToT b class ToT s ~ ToT Unwrappable s => Wrappable s where { type family Unwrappable s; type Unwrappable s = GUnwrappable Rep s; } type family Unwrappable s newtype TAddress (p :: k) TAddress :: Address -> TAddress (p :: k) [unTAddress] :: TAddress (p :: k) -> Address newtype FutureContract arg FutureContract :: ContractRef arg -> FutureContract arg [unFutureContract] :: FutureContract arg -> ContractRef arg type Entrypoint param store = '[param, store] :-> ContractOut store type Entrypoint_ store = '[store] :-> ContractOut store niceConstantEvi :: NiceConstant a :- ConstantScope (ToT a) nicePackedValueEvi :: NicePackedValue a :- PackedValScope (ToT a) niceParameterEvi :: NiceParameter a :- ParameterScope (ToT a) nicePrintedValueEvi :: NicePrintedValue a :- PrintedValScope (ToT a) niceStorageEvi :: NiceStorage a :- StorageScope (ToT a) niceUnpackedValueEvi :: NiceUnpackedValue a :- UnpackedValScope (ToT a) class (IsoValue a, HasNoNestedBigMaps ToT a) => CanHaveBigMap a type NiceConstant a = (KnownValue a, ProperConstantBetterErrors ToT a) type NiceFullPackedValue a = (NicePackedValue a, NiceUnpackedValue a) type NicePackedValue a = (KnownValue a, ProperPackedValBetterErrors ToT a) type NiceParameter a = (KnownValue a, ProperParameterBetterErrors ToT a) type NicePrintedValue a = (KnownValue a, ProperPrintedValBetterErrors ToT a) type NiceUnpackedValue a = (KnownValue a, ProperUnpackedValBetterErrors ToT a) class (IsoValue a, ForbidBigMap ToT a) => NoBigMap a class (IsoValue a, ForbidContract ToT a) => NoContractType a class (IsoValue a, ForbidOp ToT a) => NoOperation a buildLorentzDoc :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> ContractDoc buildLorentzDocWithGitRev :: forall (inp :: [Type]) (out :: [Type]). DGitRevision -> (inp :-> out) -> ContractDoc cutLorentzNonDoc :: forall (inp :: [Type]) (out :: [Type]) (s :: [Type]). (inp :-> out) -> s :-> s mkDEntrypointExample :: NiceParameter a => a -> DEntrypointExample renderLorentzDoc :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> LText renderLorentzDocWithGitRev :: forall (inp :: [Type]) (out :: [Type]). DGitRevision -> (inp :-> out) -> LText contractDocToMarkdown :: ContractDoc -> LText docDefinitionRef :: (DocItem d, DocItemPlacement d ~ 'DocItemInDefinitions) => Markdown -> d -> Markdown docItemPosition :: DocItem d => DocItemPos mdTocFromRef :: (DocItem d, DocItemReferenced d ~ 'True) => HeaderLevel -> Markdown -> d -> Markdown mkDGitRevision :: ExpQ morleyRepoSettings :: GitRepoSettings subDocToMarkdown :: HeaderLevel -> SubDoc -> Markdown concreteTypeDocHaskellRep :: (Typeable a, GenericIsoValue a, GTypeHasDoc (Rep a), HaveCommonTypeCtor b a) => TypeDocHaskellRep b concreteTypeDocHaskellRepUnsafe :: (Typeable a, GenericIsoValue a, GTypeHasDoc (Rep a)) => TypeDocHaskellRep b concreteTypeDocMichelsonRep :: forall k a (b :: k). (Typeable a, SingI (ToT a), HaveCommonTypeCtor b a) => TypeDocMichelsonRep b concreteTypeDocMichelsonRepUnsafe :: forall k a (b :: k). (Typeable a, SingI (ToT a)) => TypeDocMichelsonRep b customTypeDocMdReference :: (Text, DType) -> [DType] -> WithinParens -> Markdown dTypeDep :: TypeHasDoc t => SomeDocDefinitionItem genericTypeDocDependencies :: (Generic a, GTypeHasDoc (Rep a)) => Proxy a -> [SomeDocDefinitionItem] haskellAddNewtypeField :: Text -> TypeDocHaskellRep a -> TypeDocHaskellRep a haskellRepNoFields :: TypeDocHaskellRep a -> TypeDocHaskellRep a haskellRepStripFieldPrefix :: HasCallStack => TypeDocHaskellRep a -> TypeDocHaskellRep a homomorphicTypeDocHaskellRep :: (Generic a, GTypeHasDoc (Rep a)) => TypeDocHaskellRep a homomorphicTypeDocMdReference :: (Typeable t, TypeHasDoc t, IsHomomorphic t) => Proxy t -> WithinParens -> Markdown homomorphicTypeDocMichelsonRep :: SingI (ToT a) => TypeDocMichelsonRep a poly1TypeDocMdReference :: forall (t :: Type -> Type) r a. (r ~ t a, Typeable t, Each '[TypeHasDoc] '[r, a], IsHomomorphic t) => Proxy r -> WithinParens -> Markdown poly2TypeDocMdReference :: forall (t :: Type -> Type -> Type) r a b. (r ~ t a b, Typeable t, Each '[TypeHasDoc] '[r, a, b], IsHomomorphic t) => Proxy r -> WithinParens -> Markdown data DEntrypointExample DEntrypointExample :: Value t -> DEntrypointExample data ContractDoc ContractDoc :: DocBlock -> DocBlock -> Set SomeDocDefinitionItem -> Set DocItemId -> ContractDoc [cdContents] :: ContractDoc -> DocBlock [cdDefinitions] :: ContractDoc -> DocBlock [cdDefinitionsSet] :: ContractDoc -> Set SomeDocDefinitionItem [cdDefinitionIds] :: ContractDoc -> Set DocItemId data DAnchor DAnchor :: Anchor -> DAnchor data DComment DComment :: Text -> DComment data DDescription DDescription :: Markdown -> DDescription data DGitRevision DGitRevisionKnown :: DGitRevisionInfo -> DGitRevision DGitRevisionUnknown :: DGitRevision data DocElem d DocElem :: d -> Maybe SubDoc -> DocElem d [deItem] :: DocElem d -> d [deSub] :: DocElem d -> Maybe SubDoc type DocGrouping = SubDoc -> SomeDocItem class (Typeable d, DOrd d) => DocItem d where { type family DocItemPlacement d :: DocItemPlacementKind; type family DocItemReferenced d :: DocItemReferencedKind; type DocItemPlacement d = 'DocItemInlined; type DocItemReferenced d = 'False; } docItemPos :: DocItem d => Natural docItemSectionName :: DocItem d => Maybe Text docItemSectionDescription :: DocItem d => Maybe Markdown docItemSectionNameStyle :: DocItem d => DocSectionNameStyle docItemRef :: DocItem d => d -> DocItemRef (DocItemPlacement d) (DocItemReferenced d) docItemToMarkdown :: DocItem d => HeaderLevel -> d -> Markdown docItemToToc :: DocItem d => HeaderLevel -> d -> Markdown docItemDependencies :: DocItem d => d -> [SomeDocDefinitionItem] docItemsOrder :: DocItem d => [d] -> [d] type family DocItemPlacement d :: DocItemPlacementKind type family DocItemReferenced d :: DocItemReferencedKind newtype DocItemId DocItemId :: Text -> DocItemId data DocItemPlacementKind DocItemInlined :: DocItemPlacementKind DocItemInDefinitions :: DocItemPlacementKind newtype DocItemPos DocItemPos :: (Natural, Text) -> DocItemPos data DocItemRef (p :: DocItemPlacementKind) (r :: DocItemReferencedKind) [DocItemRef] :: DocItemId -> DocItemRef 'DocItemInDefinitions 'True [DocItemRefInlined] :: DocItemId -> DocItemRef 'DocItemInlined 'True [DocItemNoRef] :: DocItemRef 'DocItemInlined 'False data DocSection DocSection :: (NonEmpty $ DocElem d) -> DocSection data DocSectionNameStyle DocSectionNameBig :: DocSectionNameStyle DocSectionNameSmall :: DocSectionNameStyle newtype GitRepoSettings GitRepoSettings :: (Text -> Text) -> GitRepoSettings [grsMkGitRevision] :: GitRepoSettings -> Text -> Text data SomeDocDefinitionItem [SomeDocDefinitionItem] :: forall d. (DocItem d, DocItemPlacement d ~ 'DocItemInDefinitions) => d -> SomeDocDefinitionItem data SomeDocItem [SomeDocItem] :: forall d. DocItem d => d -> SomeDocItem newtype SubDoc SubDoc :: DocBlock -> SubDoc data DType [DType] :: forall a. TypeHasDoc a => Proxy a -> DType class HaveCommonTypeCtor (a :: k) (b :: k1) class IsHomomorphic (a :: k) data SomeTypeWithDoc [SomeTypeWithDoc] :: forall td. TypeHasDoc td => Proxy td -> SomeTypeWithDoc class (Typeable a, SingI TypeDocFieldDescriptions a, FieldDescriptionsValid TypeDocFieldDescriptions a a) => TypeHasDoc a where { type family TypeDocFieldDescriptions a :: FieldDescriptions; type TypeDocFieldDescriptions a = '[] :: [(Symbol, (Maybe Symbol, [(Symbol, Symbol)]))]; } typeDocName :: TypeHasDoc a => Proxy a -> Text typeDocMdDescription :: TypeHasDoc a => Markdown typeDocMdReference :: TypeHasDoc a => Proxy a -> WithinParens -> Markdown typeDocDependencies :: TypeHasDoc a => Proxy a -> [SomeDocDefinitionItem] typeDocHaskellRep :: TypeHasDoc a => TypeDocHaskellRep a typeDocMichelsonRep :: TypeHasDoc a => TypeDocMichelsonRep a type family TypeDocFieldDescriptions a :: FieldDescriptions type Markdown = Builder type Value = Value' Instr eprName :: forall (mname :: Maybe Symbol). EntrypointRef mname -> EpName parameterEntrypointCall :: forall cp (name :: Symbol). ParameterDeclaresEntrypoints cp => Label name -> EntrypointCall cp (GetEntrypointArg cp name) parameterEntrypointCallCustom :: forall cp (mname :: Maybe Symbol). ParameterDeclaresEntrypoints cp => EntrypointRef mname -> EntrypointCall cp (GetEntrypointArgCustom cp mname) parameterEntrypointCallDefault :: ParameterDeclaresEntrypoints cp => EntrypointCall cp (GetDefaultEntrypointArg cp) parameterEntrypointsToNotes :: ParameterDeclaresEntrypoints cp => ParamNotes (ToT cp) sepcCallRootChecked :: (NiceParameter cp, ForbidExplicitDefaultEntrypoint cp) => SomeEntrypointCall cp type (n :: Symbol) :> ty = 'NamedEp n ty type family AllParameterEntrypoints cp :: [(Symbol, Type)] data EntrypointRef (mname :: Maybe Symbol) [CallDefault] :: EntrypointRef ('Nothing :: Maybe Symbol) [Call] :: forall (name :: Symbol). NiceEntrypointName name => EntrypointRef ('Just name) class EntrypointsDerivation (deriv :: k) cp where { type family EpdAllEntrypoints (deriv :: k) cp :: [(Symbol, Type)]; type family EpdLookupEntrypoint (deriv :: k) cp :: Symbol -> Exp Maybe Type; } epdNotes :: EntrypointsDerivation deriv cp => (Notes (ToT cp), RootAnn) epdCall :: forall (name :: Symbol). (EntrypointsDerivation deriv cp, ParameterScope (ToT cp)) => Label name -> EpConstructionRes (ToT cp) (Eval (EpdLookupEntrypoint deriv cp name)) epdDescs :: EntrypointsDerivation deriv cp => Rec EpCallingDesc (EpdAllEntrypoints deriv cp) type family EpdAllEntrypoints (deriv :: k) cp :: [(Symbol, Type)] type family EpdLookupEntrypoint (deriv :: k) cp :: Symbol -> Exp Maybe Type data EpdNone type ForbidExplicitDefaultEntrypoint cp = Eval LiftM3 UnMaybe :: Exp Constraint -> Type -> Exp Constraint -> Maybe Type -> Constraint -> Type Pure Pure () TError 'Text "Parameter used here must have no explicit \"default\" entrypoint" :$$: 'Text "In parameter type `" :<>: 'ShowType cp :<>: 'Text "`" :: Type -> Exp Constraint -> Type LookupParameterEntrypoint cp DefaultEpName type GetDefaultEntrypointArg cp = Eval LiftM2 FromMaybe :: Type -> Maybe Type -> Type -> Type Pure cp LookupParameterEntrypoint cp DefaultEpName type GetEntrypointArg cp (name :: Symbol) = Eval LiftM2 FromMaybe :: Type -> Maybe Type -> Type -> Type TError 'Text "Entrypoint not found: " :<>: 'ShowType name :$$: 'Text "In contract parameter `" :<>: 'ShowType cp :<>: 'Text "`" :: Type -> Type LookupParameterEntrypoint cp name type family GetEntrypointArgCustom cp (mname :: Maybe Symbol) type HasDefEntrypointArg (cp :: k) defEpName defArg = (defEpName ~ EntrypointRef 'Nothing :: Maybe Symbol, HasEntrypointArg cp defEpName defArg) class HasEntrypointArg (cp :: k) name arg useHasEntrypointArg :: HasEntrypointArg cp name arg => name -> (Dict (ParameterScope (ToT arg)), EpName) type HasEntrypointOfType param (con :: Symbol) exp = (GetEntrypointArgCustom param 'Just con ~ exp, ParameterDeclaresEntrypoints param) type family LookupParameterEntrypoint cp :: Symbol -> Exp Maybe Type type NoExplicitDefaultEntrypoint cp = Eval LookupParameterEntrypoint cp DefaultEpName ~ 'Nothing :: Maybe Type type family ParameterContainsEntrypoints param (fields :: [NamedEp]) type ParameterDeclaresEntrypoints cp = (If CanHaveEntrypoints cp ParameterHasEntrypoints cp (), NiceParameter cp, EntrypointsDerivation GetParameterEpDerivation cp cp) class (EntrypointsDerivation ParameterEntrypointsDerivation cp cp, RequireAllUniqueEntrypoints cp) => ParameterHasEntrypoints cp where { type family ParameterEntrypointsDerivation cp; } type family ParameterEntrypointsDerivation cp type RequireAllUniqueEntrypoints cp = RequireAllUniqueEntrypoints' ParameterEntrypointsDerivation cp cp newtype TrustEpName TrustEpName :: EpName -> TrustEpName newtype ShouldHaveEntrypoints a ShouldHaveEntrypoints :: a -> ShouldHaveEntrypoints a [unHasEntrypoints] :: ShouldHaveEntrypoints a -> a data EpdDelegate data EpdPlain data EpdRecursive data EpdWithRoot (r :: Symbol) (epd :: k) newtype ParameterWrapper deriv cp ParameterWrapper :: cp -> ParameterWrapper deriv cp [unParameterWraper] :: ParameterWrapper deriv cp -> cp areFinalizedParamBuildingSteps :: [ParamBuildingStep] -> Bool clarifyParamBuildingSteps :: forall (inp :: [Type]) (out :: [Type]). ParamBuildingStep -> (inp :-> out) -> inp :-> out constructDEpArg :: (TypeHasDoc arg, HasAnnotation arg, KnownValue arg) => DEntrypointArg diEntrypointToMarkdown :: HeaderLevel -> DEntrypoint level -> Markdown documentEntrypoint :: forall kind (epName :: Symbol) param (s :: [Type]) (out :: [Type]). (KnownSymbol epName, DocItem (DEntrypoint kind), TypeHasDoc param, HasAnnotation param, KnownValue param) => ((param & s) :-> out) -> (param & s) :-> out emptyDEpArg :: DEntrypointArg entryCaseSimple_ :: forall cp (out :: [Type]) (inp :: [Type]). (InstrCaseC cp, RMap (CaseClauses cp), DocumentEntrypoints PlainEntrypointsKind cp, NiceParameterFull cp, RequireFlatParamEps cp) => Rec (CaseClauseL inp out) (CaseClauses cp) -> (cp & inp) :-> out mkDEntrypointArgSimple :: (KnownValue t, HasAnnotation t, TypeHasDoc t) => DEntrypointArg mkDEpUType :: (KnownValue t, HasAnnotation t) => Type mkPbsWrapIn :: Text -> ParamBuilder -> ParamBuildingStep mkUType :: forall (x :: T). SingI x => Notes x -> Type data DEntrypoint kind DEntrypoint :: Text -> SubDoc -> DEntrypoint kind [depName] :: DEntrypoint kind -> Text [depSub] :: DEntrypoint kind -> SubDoc data DEntrypointArg DEntrypointArg :: Maybe DType -> [ParamBuildingStep] -> Type -> DEntrypointArg [epaArg] :: DEntrypointArg -> Maybe DType [epaBuilding] :: DEntrypointArg -> [ParamBuildingStep] [epaType] :: DEntrypointArg -> Type data DEntrypointReference DEntrypointReference :: Text -> Anchor -> DEntrypointReference class KnownSymbol con => DeriveCtorFieldDoc (con :: Symbol) (cf :: CtorField) deriveCtorFieldDoc :: DeriveCtorFieldDoc con cf => DEntrypointArg type DocumentEntrypoints kind a = (Generic a, GDocumentEntrypoints kind Rep a) class EntryArrow (kind :: k) (name :: Symbol) body (#->) :: EntryArrow kind name body => (Label name, Proxy kind) -> body -> body newtype ParamBuilder ParamBuilder :: (Markdown -> Markdown) -> ParamBuilder [unParamBuilder] :: ParamBuilder -> Markdown -> Markdown data ParamBuildingDesc ParamBuildingDesc :: Markdown -> ParamBuilder -> ParamBuilder -> ParamBuildingDesc [pbdEnglish] :: ParamBuildingDesc -> Markdown [pbdHaskell] :: ParamBuildingDesc -> ParamBuilder [pbdMichelson] :: ParamBuildingDesc -> ParamBuilder data ParamBuildingStep PbsWrapIn :: Text -> ParamBuildingDesc -> ParamBuildingStep PbsCallEntrypoint :: EpName -> ParamBuildingStep PbsCustom :: ParamBuildingDesc -> ParamBuildingStep PbsUncallable :: [ParamBuildingStep] -> ParamBuildingStep data PlainEntrypointsKind type family RequireFlatEpDerivation (cp :: t) deriv type family RequireFlatParamEps cp data EpName customErrorDocHaskellRepGeneral :: forall (tag :: Symbol). (SingI (ToT (ErrorArg tag)), IsError (CustomError tag), TypeHasDoc (ErrorArg tag), CustomErrorHasDoc tag) => Text -> Proxy tag -> Markdown errorTagToMText :: forall (tag :: Symbol). Label tag -> MText errorTagToText :: forall (tag :: Symbol). KnownSymbol tag => Text failUnexpected :: forall (s :: [Type]) (t :: [Type]). MText -> s :-> t failUsing :: forall e (s :: [Type]) (t :: [Type]). IsError e => e -> s :-> t isoErrorFromVal :: forall (t :: T) e. (Typeable t, Typeable (ToT e), IsoValue e) => Value t -> Either Text e isoErrorToVal :: (KnownError e, IsoValue e) => e -> (forall (t :: T). ErrorScope t => Value t -> r) -> r typeDocMdDescriptionReferToError :: IsError e => Markdown data CustomError (tag :: Symbol) CustomError :: Label tag -> ErrorArg tag -> CustomError (tag :: Symbol) [ceTag] :: CustomError (tag :: Symbol) -> Label tag [ceArg] :: CustomError (tag :: Symbol) -> ErrorArg tag class (KnownSymbol tag, TypeHasDoc ErrorArg tag, IsError CustomError tag) => CustomErrorHasDoc (tag :: Symbol) customErrDocMdCause :: CustomErrorHasDoc tag => Markdown customErrDocMdCauseInEntrypoint :: CustomErrorHasDoc tag => Markdown customErrClass :: CustomErrorHasDoc tag => ErrorClass customErrArgumentSemantics :: CustomErrorHasDoc tag => Maybe Markdown data DError [DError] :: forall e. ErrorHasDoc e => Proxy e -> DError data DThrows [DThrows] :: forall e. ErrorHasDoc e => Proxy e -> DThrows type family ErrorArg (tag :: Symbol) data ErrorClass ErrClassActionException :: ErrorClass ErrClassBadArgument :: ErrorClass ErrClassContractInternal :: ErrorClass ErrClassUnknown :: ErrorClass class Typeable e => ErrorHasDoc e where { type family ErrorRequirements e; type ErrorRequirements e = (); } errorDocName :: ErrorHasDoc e => Text errorDocMdCause :: ErrorHasDoc e => Markdown errorDocMdCauseInEntrypoint :: ErrorHasDoc e => Markdown errorDocHaskellRep :: ErrorHasDoc e => Markdown errorDocClass :: ErrorHasDoc e => ErrorClass errorDocDependencies :: ErrorHasDoc e => [SomeDocDefinitionItem] errorDocRequirements :: ErrorHasDoc e => Dict (ErrorRequirements e) type family ErrorRequirements e type ErrorScope (t :: T) = (Typeable t, ConstantScope t) class (Typeable e, ErrorHasDoc e) => IsError e errorToVal :: IsError e => e -> (forall (t :: T). ErrorScope t => Value t -> r) -> r errorFromVal :: forall (t :: T). (IsError e, KnownT t) => Value t -> Either Text e type RequireNoArgError (tag :: Symbol) (msg :: ErrorMessage) = (TypeErrorUnless ErrorArg tag == () msg, msg ~ 'Text "Expected no-arg error, but given error requires argument of type " :<>: 'ShowType ErrorArg tag) data SomeError SomeError :: e -> SomeError data UnspecifiedError UnspecifiedError :: UnspecifiedError class WellTypedToT a => IsoValue a where { type family ToT a :: T; type ToT a = GValueType Rep a; } toVal :: IsoValue a => a -> Value (ToT a) fromVal :: IsoValue a => Value (ToT a) -> a type WellTypedIsoValue a = (WellTyped ToT a, IsoValue a) addNewErrorTags :: ErrorTagMap -> HashSet MText -> ErrorTagMap applyErrorTagMap :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => ErrorTagMap -> (inp :-> out) -> inp :-> out applyErrorTagMapWithExclusions :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => ErrorTagMap -> ErrorTagExclusions -> (inp :-> out) -> inp :-> out buildErrorTagMap :: HashSet MText -> ErrorTagMap errorFromValNumeric :: forall (t :: T) e. (KnownT t, IsError e) => ErrorTagMap -> Value t -> Either Text e errorToValNumeric :: IsError e => ErrorTagMap -> e -> (forall (t :: T). ErrorScope t => Value t -> r) -> r excludeErrorTags :: HasCallStack => ErrorTagExclusions -> ErrorTagMap -> ErrorTagMap gatherErrorTags :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> HashSet MText useNumericErrors :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => (inp :-> out) -> (inp :-> out, ErrorTagMap) applyErrorTagToErrorsDoc :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => ErrorTagMap -> (inp :-> out) -> inp :-> out applyErrorTagToErrorsDocWith :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => [NumericErrorDocHandler] -> ErrorTagMap -> (inp :-> out) -> inp :-> out baseErrorDocHandlers :: [NumericErrorDocHandler] customErrorDocHandler :: NumericErrorDocHandler voidResultDocHandler :: NumericErrorDocHandler type ErrorTagExclusions = HashSet MText type ErrorTagMap = Bimap Natural MText data DDescribeErrorTagMap DDescribeErrorTagMap :: Text -> DDescribeErrorTagMap [detmSrcLoc] :: DDescribeErrorTagMap -> Text data NumericErrorDocHandler data NumericErrorDocHandlerError data NumericErrorWrapper (numTag :: Nat) err printComment :: forall (s :: [Type]). PrintComment (ToTs s) -> s :-> s stackRef :: forall (gn :: Nat) (st :: [T]) (n :: Peano). (n ~ ToPeano gn, SingI n, KnownPeano n, RequireLongerThan st n) => PrintComment st stackType :: forall (s :: [Type]). s :-> s testAssert :: forall (out :: [Type]) (inp :: [Type]). (Typeable (ToTs out), HasCallStack) => Text -> PrintComment (ToTs inp) -> (inp :-> (Bool & out)) -> inp :-> inp class NonZero t class ConcatOp ToT c => ConcatOpHs c type List = [] class (EDivOp ToT n ToT m, NiceComparable n, NiceComparable m, ToT EDivOpResHs n m ~ EDivOpRes ToT n ToT m, ToT EModOpResHs n m ~ EModOpRes ToT n ToT m) => EDivOpHs n m where { type family EDivOpResHs n m; type family EModOpResHs n m; } type family EDivOpResHs n m type family EModOpResHs n m class (MemOp ToT c, ToT MemOpKeyHs c ~ MemOpKey ToT c) => MemOpHs c where { type family MemOpKeyHs c; } type family MemOpKeyHs c class (GetOp ToT c, ToT GetOpKeyHs c ~ GetOpKey ToT c, ToT GetOpValHs c ~ GetOpVal ToT c) => GetOpHs c where { type family GetOpKeyHs c; type family GetOpValHs c; } type family GetOpValHs c type family GetOpKeyHs c class (IterOp ToT c, ToT IterOpElHs c ~ IterOpEl ToT c) => IterOpHs c where { type family IterOpElHs c; } type family IterOpElHs c class (MapOp ToT c, ToT MapOpInpHs c ~ MapOpInp ToT c, ToT MapOpResHs c () ~ MapOpRes ToT c ToT ()) => MapOpHs c where { type family MapOpInpHs c; type family MapOpResHs c :: Type -> Type; } type family IsoMapOpRes c b type family MapOpInpHs c type family MapOpResHs c :: Type -> Type class SizeOp ToT c => SizeOpHs c class SliceOp ToT c => SliceOpHs c class (UpdOp ToT c, ToT UpdOpKeyHs c ~ UpdOpKey ToT c, ToT UpdOpParamsHs c ~ UpdOpParams ToT c) => UpdOpHs c where { type family UpdOpKeyHs c; type family UpdOpParamsHs c; } type family UpdOpKeyHs c type family UpdOpParamsHs c voidResultTag :: MText data View a r data VoidResult r data Void_ a b class ToContractRef cp contract toContractRef :: ToContractRef cp contract => contract -> ContractRef cp expressionToScriptExpr :: Expression -> ByteString lEncodeValue :: NicePrintedValue a => a -> ByteString lPackValue :: NicePackedValue a => a -> ByteString lUnpackValue :: NiceUnpackedValue a => ByteString -> Either UnpackError a valueToScriptExpr :: NicePackedValue t => t -> ByteString printLorentzContract :: (NiceParameterFull cp, NiceStorage st) => Bool -> Contract cp st -> LText printLorentzValue :: NicePrintedValue v => Bool -> v -> LText dipT :: forall a (inp :: [Type]) (dinp :: [Type]) (dout :: [Type]) (out :: [Type]). DipT inp a inp dinp dout out => (dinp :-> dout) -> inp :-> out dropT :: forall a (inp :: [Type]) (dinp :: [Type]) (dout :: [Type]) (out :: [Type]). (DipT inp a inp dinp dout out, dinp ~ (a : dout)) => inp :-> out dupT :: forall a (st :: [Type]). DupT st a st => st :-> (a : st) analyzeLorentz :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> AnalyzerRes compileLorentz :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> Instr (ToTs inp) (ToTs out) compileLorentzContract :: (NiceParameterFull cp, NiceStorage st) => Contract cp st -> Contract (ToT cp) (ToT st) compileLorentzWithOptions :: forall (inp :: [Type]) (out :: [Type]). CompilationOptions -> (inp :-> out) -> Instr (ToTs inp) (ToTs out) defaultCompilationOptions :: CompilationOptions defaultContract :: ContractCode cp st -> Contract cp st interpretLorentzInstr :: forall (inp :: [Type]) (out :: [Type]). (IsoValuesStack inp, IsoValuesStack out) => ContractEnv -> (inp :-> out) -> Rec Identity inp -> Either MichelsonFailed (Rec Identity out) interpretLorentzLambda :: (IsoValue inp, IsoValue out) => ContractEnv -> Lambda inp out -> inp -> Either MichelsonFailed out data CompilationOptions CompilationOptions :: Maybe OptimizerConf -> (Bool, MText -> MText) -> (Bool, ByteString -> ByteString) -> CompilationOptions [coOptimizerConf] :: CompilationOptions -> Maybe OptimizerConf [coStringTransformer] :: CompilationOptions -> (Bool, MText -> MText) [coBytesTransformer] :: CompilationOptions -> (Bool, ByteString -> ByteString) composeStoreEntrypointOps :: forall (nameInStore :: Symbol) store substore (epName :: Symbol) epParam epStore. Label nameInStore -> StoreFieldOps store nameInStore substore -> StoreEntrypointOps substore epName epParam epStore -> StoreEntrypointOps store epName epParam epStore composeStoreFieldOps :: forall (nameInStore :: Symbol) store substore (nameInSubstore :: Symbol) field. Label nameInStore -> StoreFieldOps store nameInStore substore -> StoreFieldOps substore nameInSubstore field -> StoreFieldOps store nameInSubstore field composeStoreSubmapOps :: forall (nameInStore :: Symbol) store substore (mname :: Symbol) key value. Label nameInStore -> StoreFieldOps store nameInStore substore -> StoreSubmapOps substore mname key value -> StoreSubmapOps store mname key value mkStoreEp :: forall (epName :: Symbol) epParam epStore. Label epName -> EntrypointLambda epParam epStore -> EntrypointsField epParam epStore stEntrypoint :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (epParam : (store : s)) :-> (([Operation], store) : s) stGetEpLambda :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : (store : s)) stGetEpStore :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (epStore : (store : s)) stGetField :: forall store (fname :: Symbol) ftype (s :: [Type]). StoreHasField store fname ftype => Label fname -> (store : s) :-> (ftype : (store : s)) stSetEpLambda :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (EntrypointLambda epParam epStore : (store : s)) :-> (store : s) stSetEpStore :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (epStore : (store : s)) :-> (store : s) stSetField :: forall store (fname :: Symbol) ftype (s :: [Type]). StoreHasField store fname ftype => Label fname -> (ftype : (store : s)) :-> (store : s) stToEpLambda :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : s) stToEpStore :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (epStore : s) stToField :: forall store (fname :: Symbol) ftype (s :: [Type]). StoreHasField store fname ftype => Label fname -> (store : s) :-> (ftype : s) storeEntrypointOpsADT :: forall store (epmName :: Symbol) epParam epStore (epsName :: Symbol) (epName :: Symbol). (HasFieldOfType store epmName (EntrypointsField epParam epStore), HasFieldOfType store epsName epStore, KnownValue epParam, KnownValue epStore) => Label epmName -> Label epsName -> StoreEntrypointOps store epName epParam epStore storeEntrypointOpsDeeper :: forall store (nameInStore :: Symbol) substore (epName :: Symbol) epParam epStore. (HasFieldOfType store nameInStore substore, StoreHasEntrypoint substore epName epParam epStore) => Label nameInStore -> StoreEntrypointOps store epName epParam epStore storeEntrypointOpsFields :: forall store (epmName :: Symbol) epParam epStore (epsName :: Symbol) (epName :: Symbol). (StoreHasField store epmName (EntrypointsField epParam epStore), StoreHasField store epsName epStore, KnownValue epParam, KnownValue epStore) => Label epmName -> Label epsName -> StoreEntrypointOps store epName epParam epStore storeEntrypointOpsReferTo :: forall (epName :: Symbol) store epParam epStore (desiredName :: Symbol). Label epName -> StoreEntrypointOps store epName epParam epStore -> StoreEntrypointOps store desiredName epParam epStore storeEntrypointOpsSubmapField :: forall store (epmName :: Symbol) epParam epStore (epsName :: Symbol) (epName :: Symbol). (StoreHasSubmap store epmName MText (EntrypointLambda epParam epStore), StoreHasField store epsName epStore, KnownValue epParam, KnownValue epStore) => Label epmName -> Label epsName -> StoreEntrypointOps store epName epParam epStore storeFieldOpsADT :: forall dt (fname :: Symbol) ftype. HasFieldOfType dt fname ftype => StoreFieldOps dt fname ftype storeFieldOpsDeeper :: forall storage (fieldsPartName :: Symbol) fields (fname :: Symbol) ftype. (HasFieldOfType storage fieldsPartName fields, StoreHasField fields fname ftype) => Label fieldsPartName -> StoreFieldOps storage fname ftype storeFieldOpsReferTo :: forall (name :: Symbol) storage field (desiredName :: Symbol). Label name -> StoreFieldOps storage name field -> StoreFieldOps storage desiredName field storeSubmapOpsDeeper :: forall storage (bigMapPartName :: Symbol) fields (mname :: Symbol) key value. (HasFieldOfType storage bigMapPartName fields, StoreHasSubmap fields mname key value) => Label bigMapPartName -> StoreSubmapOps storage mname key value storeSubmapOpsReferTo :: forall (name :: Symbol) storage key value (desiredName :: Symbol). Label name -> StoreSubmapOps storage name key value -> StoreSubmapOps storage desiredName key value data (param :: k) ::-> (store :: k1) type EntrypointLambda param store = Lambda (param, store) ([Operation], store) type EntrypointsField param store = BigMap MText EntrypointLambda param store type family StorageContains store (content :: [NamedField]) data StoreEntrypointOps store (epName :: Symbol) epParam epStore StoreEntrypointOps :: (forall (s :: [Type]). () => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : s)) -> (forall (s :: [Type]). () => Label epName -> (EntrypointLambda epParam epStore : (store : s)) :-> (store : s)) -> (forall (s :: [Type]). () => Label epName -> (store : s) :-> (epStore : s)) -> (forall (s :: [Type]). () => Label epName -> (epStore : (store : s)) :-> (store : s)) -> StoreEntrypointOps store (epName :: Symbol) epParam epStore [sopToEpLambda] :: StoreEntrypointOps store (epName :: Symbol) epParam epStore -> forall (s :: [Type]). () => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : s) [sopSetEpLambda] :: StoreEntrypointOps store (epName :: Symbol) epParam epStore -> forall (s :: [Type]). () => Label epName -> (EntrypointLambda epParam epStore : (store : s)) :-> (store : s) [sopToEpStore] :: StoreEntrypointOps store (epName :: Symbol) epParam epStore -> forall (s :: [Type]). () => Label epName -> (store : s) :-> (epStore : s) [sopSetEpStore] :: StoreEntrypointOps store (epName :: Symbol) epParam epStore -> forall (s :: [Type]). () => Label epName -> (epStore : (store : s)) :-> (store : s) data StoreFieldOps store (fname :: Symbol) ftype StoreFieldOps :: (forall (s :: [Type]). () => Label fname -> (store : s) :-> (ftype : s)) -> (forall (s :: [Type]). () => Label fname -> (ftype : (store : s)) :-> (store : s)) -> StoreFieldOps store (fname :: Symbol) ftype [sopToField] :: StoreFieldOps store (fname :: Symbol) ftype -> forall (s :: [Type]). () => Label fname -> (store : s) :-> (ftype : s) [sopSetField] :: StoreFieldOps store (fname :: Symbol) ftype -> forall (s :: [Type]). () => Label fname -> (ftype : (store : s)) :-> (store : s) class StoreHasEntrypoint store (epName :: Symbol) epParam epStore | store epName -> epParam epStore storeEpOps :: StoreHasEntrypoint store epName epParam epStore => StoreEntrypointOps store epName epParam epStore class StoreHasField store (fname :: Symbol) ftype | store fname -> ftype storeFieldOps :: StoreHasField store fname ftype => StoreFieldOps store fname ftype class StoreHasSubmap store (mname :: Symbol) key value | store mname -> key value storeSubmapOps :: StoreHasSubmap store mname key value => StoreSubmapOps store mname key value data StoreSubmapOps store (mname :: Symbol) key value StoreSubmapOps :: (forall (s :: [Type]). () => Label mname -> (key : (store : s)) :-> (Bool : s)) -> (forall (s :: [Type]). KnownValue value => Label mname -> (key : (store : s)) :-> (Maybe value : s)) -> (forall (s :: [Type]). () => Label mname -> (key : (Maybe value : (store : s))) :-> (store : s)) -> (forall (s :: [Type]). () => Maybe (Label mname -> (key : (store : s)) :-> (store : s))) -> (forall (s :: [Type]). () => Maybe (Label mname -> (key : (value : (store : s))) :-> (store : s))) -> StoreSubmapOps store (mname :: Symbol) key value [sopMem] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). () => Label mname -> (key : (store : s)) :-> (Bool : s) [sopGet] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). KnownValue value => Label mname -> (key : (store : s)) :-> (Maybe value : s) [sopUpdate] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). () => Label mname -> (key : (Maybe value : (store : s))) :-> (store : s) [sopDelete] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). () => Maybe (Label mname -> (key : (store : s)) :-> (store : s)) [sopInsert] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). () => Maybe (Label mname -> (key : (value : (store : s))) :-> (store : s)) data (k2 :: k) ~> (v :: k1) caseUParam :: forall (entries :: [EntrypointKind]) (inp :: [Type]) (out :: [Type]). (CaseUParam entries, RequireUniqueEntrypoints entries) => Rec (CaseClauseU inp out) entries -> UParamFallback inp out -> (UParam entries : inp) :-> out caseUParamT :: forall (entries :: [EntrypointKind]) (inp :: [Type]) (out :: [Type]) clauses. (clauses ~ Rec (CaseClauseU inp out) entries, RecFromTuple clauses, CaseUParam entries) => IsoRecTuple clauses -> UParamFallback inp out -> (UParam entries : inp) :-> out mkUParam :: forall a (name :: Symbol) (entries :: [EntrypointKind]). (NicePackedValue a, LookupEntrypoint name entries ~ a, RequireUniqueEntrypoints entries) => Label name -> a -> UParam entries pbsUParam :: forall (ctorName :: Symbol). KnownSymbol ctorName => ParamBuildingStep unwrapUParam :: forall (entries :: [EntrypointKind]) (s :: [Type]). (UParam entries : s) :-> ((MText, ByteString) : s) uparamFallbackFail :: forall (inp :: [Type]) (out :: [Type]). UParamFallback inp out uparamFromAdt :: UParamLinearize up => up -> UParam (UParamLinearized up) type (n :: Symbol) ?: (a :: k) = '(n, a) class CaseUParam (entries :: [EntrypointKind]) data ConstrainedSome (c :: Type -> Constraint) [ConstrainedSome] :: forall (c :: Type -> Constraint) a. c a => a -> ConstrainedSome c type EntrypointKind = (Symbol, Type) data EntrypointLookupError NoSuchEntrypoint :: MText -> EntrypointLookupError ArgumentUnpackFailed :: EntrypointLookupError type EntrypointsImpl (inp :: [Type]) (out :: [Type]) (entries :: [EntrypointKind]) = Rec CaseClauseU inp out entries type family LookupEntrypoint (name :: Symbol) (entries :: [EntrypointKind]) type family RequireUniqueEntrypoints (entries :: [EntrypointKind]) type SomeInterface = '[ '("SomeEntrypoints", Void)] newtype UParam (entries :: [EntrypointKind]) UParamUnsafe :: (MText, ByteString) -> UParam (entries :: [EntrypointKind]) type UParamFallback (inp :: [Type]) (out :: [Type]) = (MText, ByteString) : inp :-> out type UParamLinearize p = (Generic p, GUParamLinearize Rep p) type UParamLinearized p = GUParamLinearized Rep p type UParam_ = UParam SomeInterface class UnpackUParam (c :: Type -> Constraint) (entries :: [EntrypointKind]) unpackUParam :: UnpackUParam c entries => UParam entries -> Either EntrypointLookupError (MText, ConstrainedSome c) entrypointDoc :: QuasiQuoter errorDoc :: QuasiQuoter typeDoc :: QuasiQuoter callingDefTAddress :: NiceParameterFull cp => TAddress cp -> ContractRef (GetDefaultEntrypointArg cp) callingTAddress :: forall cp (mname :: Maybe Symbol). NiceParameterFull cp => TAddress cp -> EntrypointRef mname -> ContractRef (GetEntrypointArgCustom cp mname) convertContractRef :: forall cp contract2 contract1. (ToContractRef cp contract1, FromContractRef cp contract2) => contract1 -> contract2 mt :: QuasiQuoter coerceContractRef :: ToT a ~ ToT b => ContractRef a -> ContractRef b pattern DefEpName :: EpName oneMutez :: Mutez timestampFromSeconds :: Integer -> Timestamp timestampFromUTCTime :: UTCTime -> Timestamp timestampQuote :: QuasiQuoter toMutez :: Word32 -> Mutez zeroMutez :: Mutez cstr :: forall (n :: Nat). KnownNat n => [Natural] -> CstrDepth customGeneric :: String -> GenericStrategy -> Q [Dec] fld :: forall (n :: Nat). KnownNat n => Natural leftBalanced :: GenericStrategy leftComb :: GenericStrategy rightBalanced :: GenericStrategy rightComb :: GenericStrategy withDepths :: [CstrDepth] -> GenericStrategy class FromContractRef cp contract fromContractRef :: FromContractRef cp contract => ContractRef cp -> contract class ToAddress a toAddress :: ToAddress a => a -> Address class ToTAddress cp a toTAddress :: ToTAddress cp a => a -> TAddress cp type EntrypointCall param arg = EntrypointCallT ToT param ToT arg type SomeEntrypointCall arg = SomeEntrypointCallT ToT arg module Indigo.Internal.Var -- | A variable referring to an element in the stack. data Var a Var :: RefId -> Var a -- | Reference id to a stack cell data RefId -- | Stack of the symbolic interpreter. type StackVars (stk :: [Type]) = Rec StkEl stk -- | Stack element of the symbolic interpreter. -- -- It holds either a reference index that refers to this element or just -- NoRef, indicating that there are no references to this element. data StkEl a [NoRef] :: KnownValue a => StkEl a [Ref] :: KnownValue a => RefId -> StkEl a emptyStack :: StackVars '[] -- | Given a StackVars and a Peano singleton for a depth, -- it puts a new Var at that depth (0-indexed) and returns it with -- the updated StackVars. -- -- If there is a Var there already it is used and the -- StackVars not changed. assignVarAt :: (KnownValue a, a ~ At n inp, RequireLongerThan inp n) => Var a -> StackVars inp -> Sing n -> StackVars inp -- | Push a new stack element with a reference to it, given the variable. pushRef :: KnownValue a => Var a -> StackVars inp -> StackVars (a & inp) -- | Push a new stack element without a reference to it. pushNoRef :: KnownValue a => StackVars inp -> StackVars (a & inp) -- | Remove the top element of the stack. It's supposed that no variable -- refers to this element. popNoRef :: StackVars (a & inp) -> StackVars inp type Ops = [Operation] -- | Allows to get a variable with operations type HasSideEffects = Given (Var Ops) -- | Return a variable which refers to a stack cell with operations operationsVar :: HasSideEffects => Var Ops -- | Allows to get a variable with storage type HasStorage st = (Given (Var st), KnownValue st) -- | Return a variable which refers to a stack cell with storage storageVar :: HasStorage st => Var st instance forall k (a :: k). GHC.Show.Show (Indigo.Internal.Var.Var a) instance forall k (a :: k). GHC.Generics.Generic (Indigo.Internal.Var.Var a) instance GHC.Enum.Bounded Indigo.Internal.Var.RefId instance GHC.Num.Num Indigo.Internal.Var.RefId instance GHC.Real.Real Indigo.Internal.Var.RefId instance GHC.Classes.Ord Indigo.Internal.Var.RefId instance GHC.Classes.Eq Indigo.Internal.Var.RefId instance GHC.Generics.Generic Indigo.Internal.Var.RefId instance GHC.Show.Show Indigo.Internal.Var.RefId instance Data.Default.Class.Default (Indigo.Internal.Var.StackVars '[]) instance (Lorentz.Constraints.Scopes.KnownValue x, Data.Default.Class.Default (Indigo.Internal.Var.StackVars xs)) => Data.Default.Class.Default (Indigo.Internal.Var.StackVars (x : xs)) instance Data.Type.Equality.TestEquality Indigo.Internal.Var.StkEl module Indigo.Internal.Object -- | A object that can be either stored in the single stack cell or split -- into fields. Fields are identified by their names. -- -- f is a functor to be applied to each of field names. data IndigoObjectF f a -- | Value stored on the stack, it might be either complex product type, -- like (a, b), Storage, etc, or sum type like Either, or -- primitive like Int, Operation, etc. [Cell] :: KnownValue a => RefId -> IndigoObjectF f a -- | Decomposed product type, which is NOT stored as one cell on the stack. [Decomposed] :: ComplexObjectC a => Rec f (ConstructorFieldNames a) -> IndigoObjectF f a -- | Auxiliary datatype to define a Objiable. Keeps field name as type -- param data NamedFieldObj a name [NamedFieldObj] :: IsObject (GetFieldType a name) => {unFieldObj :: Object (GetFieldType a name)} -> NamedFieldObj a name -- | Like NamedFieldObj, but this one doesn't keep name of a field data TypedFieldObj a [TypedFieldObj] :: IsObject a => Object a -> TypedFieldObj a type FieldTypes a = MapGFT a (ConstructorFieldNames a) type Object a = IndigoObjectF (NamedFieldObj a) a data SomeObject [SomeObject] :: IsObject a => Object a -> SomeObject -- | Convert a list of fields from name-based list to type-based one namedToTypedRec :: forall a f g. (forall name. f name -> g (GetFieldType a name)) -> Rec f (ConstructorFieldNames a) -> Rec g (FieldTypes a) -- | Convert a list of fields from type-based list to named-based one typedToNamedRec :: forall a f g. KnownList (ConstructorFieldNames a) => (forall name. f (GetFieldType a name) -> g name) -> Rec f (FieldTypes a) -> Rec g (ConstructorFieldNames a) namedToTypedFieldObj :: forall a name. NamedFieldObj a name -> TypedFieldObj (GetFieldType a name) typedToNamedFieldObj :: forall a name. TypedFieldObj (GetFieldType a name) -> NamedFieldObj a name class IsObject' (TypeDecision a) a => IsObject a complexObjectDict :: forall a. IsObject a => Maybe (Dict (ComplexObjectC a)) type ComplexObjectC a = (ToDeconstructC a, ToConstructC a, AllConstrained IsObject (FieldTypes a)) castFieldConstructors :: forall a st. CastFieldConstructors (FieldTypes a) (ConstructorFieldTypes a) => Rec (FieldConstructor st) (FieldTypes a) -> Rec (FieldConstructor st) (ConstructorFieldTypes a) instance Indigo.Internal.Object.IsObject' (Indigo.Internal.Object.TypeDecision a) a => Indigo.Internal.Object.IsObject a instance Lorentz.Constraints.Scopes.KnownValue a => Indigo.Internal.Object.IsObject' 'Indigo.Internal.Object.PrimitiveD a instance Lorentz.Constraints.Scopes.KnownValue a => Indigo.Internal.Object.IsObject' 'Indigo.Internal.Object.SumTypeD a instance Indigo.Internal.Object.ComplexObjectC a => Indigo.Internal.Object.IsObject' 'Indigo.Internal.Object.ProductTypeD a -- | This module contains the core of Indigo language: IndigoState, -- a datatype that represents its state. It also includes some convenient -- functions to work with it, to provide rebindable syntax. -- -- IndigoState implements the functionality of a symbolic -- interpreter. During its execution Lorentz code is being generated. -- -- Functionally, it's the same as having Lorentz instruction that can -- access and modify a StackVars, referring to values on the stack -- with a RefId. module Indigo.Internal.State -- | IndigoState data type. -- -- It takes as input a StackVars (for the initial state) and -- returns a GenCode (for the resulting state and the generated -- Lorentz code). -- -- IndigoState has to be used to write backend typed Lorentz code from -- the corresponding frontend constructions. -- -- It has no return type, IndigoState instruction may take one or more -- "return variables", that they assign to values produced during their -- execution. newtype IndigoState inp out IndigoState :: (MetaData inp -> GenCode inp out) -> IndigoState inp out [runIndigoState] :: IndigoState inp out -> MetaData inp -> GenCode inp out -- | Inverse of runIndigoState for utility. usingIndigoState :: MetaData inp -> IndigoState inp out -> GenCode inp out -- | Then for rebindable syntax. (>>) :: IndigoState inp out -> IndigoState out out1 -> IndigoState inp out1 -- | 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 <$> -- | Put new GenCode. iput :: GenCode inp out -> IndigoState inp out -- | The simplest IndigoState, it does not modify the stack, nor the -- produced code. nopState :: IndigoState inp inp -- | Assigns a variable to reference the element on top of the stack. assignTopVar :: KnownValue x => Var x -> IndigoState (x & inp) (x & inp) withObject :: forall a r. KnownValue a => DecomposedObjects -> Var a -> (Object a -> r) -> r withObjectState :: forall a inp out. KnownValue a => Var a -> (Object a -> IndigoState inp out) -> IndigoState inp out -- | Utility function to create IndigoState that need access to the -- current StackVars. withStackVars :: (StackVars inp -> IndigoState inp out) -> IndigoState inp out type DecomposedObjects = Map RefId SomeObject data MetaData inp MetaData :: StackVars inp -> DecomposedObjects -> MetaData inp [mdStack] :: MetaData inp -> StackVars inp [mdObjects] :: MetaData inp -> DecomposedObjects replStkMd :: MetaData inp -> StackVars inp1 -> MetaData inp1 alterStkMd :: MetaData inp -> (StackVars inp -> StackVars inp1) -> MetaData inp1 -- | pushRef version for MetaData pushRefMd :: KnownValue a => Var a -> MetaData inp -> MetaData (a & inp) -- | pushNoRef version for MetaData pushNoRefMd :: KnownValue a => MetaData inp -> MetaData (a & inp) -- | popNoRef version for MetaData popNoRefMd :: MetaData (a & inp) -> MetaData inp -- | Resulting state of IndigoM. data GenCode inp out GenCode :: ~StackVars out -> (inp :-> out) -> (out :-> inp) -> GenCode inp out -- | Stack of the symbolic interpreter. [gcStack] :: GenCode inp out -> ~StackVars out -- | Generated Lorentz code. [gcCode] :: GenCode inp out -> inp :-> out -- | Clearing Lorentz code. [gcClear] :: GenCode inp out -> out :-> inp -- | Produces the generated Lorentz code that cleans after itself, leaving -- the same stack as the input one cleanGenCode :: GenCode inp out -> inp :-> inp -- | This module contains the logic to lookup Vars in a stack and -- the actions to manipulate it. -- -- For efficiency, actions are implemented using Lorentz macros. To do so -- every necessary constraint is checked at runtime. module Indigo.Internal.Lookup -- | Puts a copy of the value for the given Var on top of the stack varActionGet :: forall a stk. KnownValue a => RefId -> StackVars stk -> stk :-> (a & stk) -- | Sets the value for the given Var to the topmost value on the -- stack varActionSet :: forall a stk. KnownValue a => RefId -> StackVars stk -> (a & stk) :-> stk -- | Updates the value for the given Var with the topmost value on -- the stack using the given binary instruction. varActionUpdate :: forall a b stk. (KnownValue a, KnownValue b) => RefId -> StackVars stk -> ('[b, a] :-> '[a]) -> (b : stk) :-> stk -- | Given a stack with a list of Operations on its bottom, updates -- it by appending the Operation on the top. varActionOperation :: HasSideEffects => StackVars stk -> (Operation : stk) :-> stk rtake :: Sing n -> Rec any s -> Rec any (Take n s) rdrop :: Sing n -> Rec any s -> Rec any (Drop n s) instance Data.Type.Equality.TestEquality Indigo.Internal.Lookup.TVal -- | This module serves the purpose of listing hiding rules of -- Prelude that conflicts with Indigo exported functions. module Indigo.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 infixr 0 `seq` -- | O(n). filter, applied to a predicate and a list, returns -- the list of those elements that satisfy the predicate; i.e., -- --
--   filter p xs = [ x | x <- xs, p x]
--   
-- --
--   >>> filter odd [1, 2, 3]
--   [1,3]
--   
filter :: (a -> Bool) -> [a] -> [a] -- | O(min(m,n)). 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 is capable of list fusion, but it is restricted to its -- first list argument and its resulting list. zip :: [a] -> [b] -> [(a, b)] -- | otherwise is defined as the value True. It helps to make -- guards more readable. eg. -- --
--   f x | x < 0     = ...
--       | otherwise = ...
--   
otherwise :: Bool -- | Application operator. This operator is redundant, since ordinary -- application (f x) means the same as (f $ x). -- However, $ has low, right-associative binding precedence, so it -- sometimes allows parentheses to be omitted; for example: -- --
--   f $ g $ h x  =  f (g (h x))
--   
-- -- It is also useful in higher-order situations, such as map -- ($ 0) xs, or zipWith ($) fs xs. -- -- Note that ($) is levity-polymorphic in its result -- type, so that foo $ True where foo :: Bool -> -- Int# is well-typed. ($) :: forall (r :: RuntimeRep) a (b :: TYPE r). (a -> b) -> a -> b infixr 0 $ -- | 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 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 -- | 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 -- | 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 -- | 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 -- | 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` -- | The Monad class defines the basic operations over a -- monad, a concept from a branch of mathematics known as -- category theory. From the perspective of a Haskell programmer, -- however, it is best to think of a monad as an abstract datatype -- of actions. Haskell's do expressions provide a convenient -- syntax for writing monadic expressions. -- -- Instances of Monad should satisfy the following: -- -- -- -- Furthermore, the Monad and Applicative operations should -- relate as follows: -- -- -- -- The above laws imply: -- -- -- -- and that pure and (<*>) satisfy the applicative -- functor laws. -- -- The instances of Monad for lists, Maybe and IO -- defined in the Prelude satisfy these laws. class Applicative m => Monad (m :: Type -> Type) -- | Sequentially compose two actions, passing any value produced by the -- first as an argument to the second. (>>=) :: 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 >> -- | A type f is a Functor if it provides a function fmap -- which, given any types a and b lets you apply any -- function from (a -> b) to turn an f a into an -- f b, preserving the structure of f. Furthermore -- f needs to adhere to the following: -- -- -- -- Note, that the second law follows from the free theorem of the type -- fmap and the first law, so you need only check that the former -- condition holds. class Functor (f :: Type -> Type) fmap :: 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 -- | Unary negation. negate :: Num a => a -> a -- | Sign of a number. The functions abs and signum should -- satisfy the law: -- --
--   abs x * signum x == x
--   
-- -- For real numbers, the signum is either -1 (negative), -- 0 (zero) or 1 (positive). signum :: Num a => a -> a -- | The 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 max :: Ord a => a -> a -> a min :: Ord a => a -> a -> a -- | 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) -- | 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. -- --
--   t (pure x) = pure x
--   t (f <*> x) = t f <*> t x
--   
-- -- and the identity functor Identity and composition functors -- Compose are from Data.Functor.Identity and -- Data.Functor.Compose. -- -- (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 following: -- -- class Semigroup 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 -- | The class of monoids (types with an associative binary operation that -- has an identity). Instances should satisfy the following: -- -- -- -- The method names refer to the monoid of lists under concatenation, but -- there are many other instances. -- -- Some types can be viewed as a monoid in more than one way, e.g. both -- addition and multiplication on numbers. In such cases we often define -- newtypes and make those instances of Monoid, e.g. -- Sum and Product. -- -- NOTE: Semigroup is a superclass of Monoid since -- base-4.11.0.0. class Semigroup a => Monoid a -- | Identity of mappend 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 (:%) :: !a -> !a -> 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 -- | A value of type Ptr a represents a pointer to an -- object, or an array of objects, which may be marshalled to or from -- Haskell values of type a. -- -- The type a will often be an instance of class Storable -- which provides the marshalling operations. However this is not -- essential, and you can provide your own operations to access the -- pointer. For example you might write small foreign functions to get or -- set the fields of a C struct. data Ptr a -- | A value of type FunPtr a is a pointer to a function -- callable from foreign code. The type a will normally be a -- foreign type, a function type with zero or more arguments where -- -- -- -- A value of type FunPtr a may be a pointer to a foreign -- function, either returned by another foreign function or imported with -- a a static address import like -- --
--   foreign import ccall "stdlib.h &free"
--     p_free :: FunPtr (Ptr a -> IO ())
--   
-- -- or a pointer to a Haskell function created using a wrapper stub -- declared to produce a FunPtr of the correct type. For example: -- --
--   type Compare = Int -> Int -> Bool
--   foreign import ccall "wrapper"
--     mkCompare :: Compare -> IO (FunPtr Compare)
--   
-- -- Calls to wrapper stubs like mkCompare allocate storage, which -- should be released with freeHaskellFunPtr when no longer -- required. -- -- To convert FunPtr values to corresponding Haskell functions, -- one can define a dynamic stub for the specific foreign type, -- e.g. -- --
--   type IntFunction = CInt -> IO ()
--   foreign import ccall "dynamic"
--     mkFun :: FunPtr IntFunction -> IntFunction
--   
data FunPtr a -- | The Either type represents values with two possibilities: a -- value of type Either a b is either Left -- a or Right b. -- -- The Either type is sometimes used to represent a value which is -- either correct or an error; by convention, the Left constructor -- is used to hold an error value and the Right constructor is -- used to hold a correct value (mnemonic: "right" also means "correct"). -- --

Examples

-- -- The type Either String Int is the type -- of values which can be either a String or an Int. The -- Left constructor can be used only on Strings, and the -- Right constructor can be used only on Ints: -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> s
--   Left "foo"
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> n
--   Right 3
--   
--   >>> :type s
--   s :: Either String Int
--   
--   >>> :type n
--   n :: Either String Int
--   
-- -- The fmap from our Functor instance will ignore -- Left values, but will apply the supplied function to values -- contained in a Right: -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> fmap (*2) s
--   Left "foo"
--   
--   >>> fmap (*2) n
--   Right 6
--   
-- -- The Monad instance for Either allows us to chain -- together multiple actions which may fail, and fail overall if any of -- the individual steps failed. First we'll write a function that can -- either parse an Int from a Char, or fail. -- --
--   >>> import Data.Char ( digitToInt, isDigit )
--   
--   >>> :{
--       let parseEither :: Char -> Either String Int
--           parseEither c
--             | isDigit c = Right (digitToInt c)
--             | otherwise = Left "parse error"
--   
--   >>> :}
--   
-- -- The following should work, since both '1' and '2' -- can be parsed as Ints. -- --
--   >>> :{
--       let parseMultiple :: Either String Int
--           parseMultiple = do
--             x <- parseEither '1'
--             y <- parseEither '2'
--             return (x + y)
--   
--   >>> :}
--   
-- --
--   >>> parseMultiple
--   Right 3
--   
-- -- But the following should fail overall, since the first operation where -- we attempt to parse 'm' as an Int will fail: -- --
--   >>> :{
--       let parseMultiple :: Either String Int
--           parseMultiple = do
--             x <- parseEither 'm'
--             y <- parseEither '2'
--             return (x + y)
--   
--   >>> :}
--   
-- --
--   >>> parseMultiple
--   Left "parse error"
--   
data Either a b Left :: a -> Either a b Right :: b -> Either a b -- | The kind of constraints, like Show a data Constraint -- | 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 :: k) (b :: k) -- | 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 -- | Identity function. -- --
--   id x = x
--   
id :: a -> 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 -- | See examples in Control.Monad.Reader. Note, the partially -- applied function type (->) r is a simple reader monad. See -- the instance declaration below. class Monad m => MonadReader r (m :: Type -> Type) | m -> r -- | Retrieves the monad environment. ask :: MonadReader r m => m r -- | Executes a computation in a modified environment. local :: MonadReader r m => (r -> r) -> m a -> m a -- | Retrieves a function of the current environment. reader :: MonadReader r m => (r -> a) -> m a -- | Minimal definition is either both of get and put or -- just state class Monad m => MonadState s (m :: Type -> Type) | m -> s -- | Replace the state inside the monad. put :: MonadState s m => s -> m () -- | Embed a simple state action into the monad. state :: MonadState s m => (s -> (a, s)) -> m a -- | 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 <$> -- | A String is a list of characters. String constants in Haskell -- are values of type String. type String = [Char] -- | 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 . -- | 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. -- -- The Semigroup operation for Map is union, which -- prefers values from the left operand. If m1 maps a key -- k to a value a1, and m2 maps the same key -- to a different value a2, then their union m1 <> -- m2 maps k to a1. data Map k a -- | A handle managing output to the Haskell program's standard output -- channel. stdout :: Handle -- | 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 monoid on applicative functors. -- -- If defined, some and many should be the least solutions -- of the equations: -- -- class Applicative f => Alternative (f :: Type -> Type) -- | An associative binary operation (<|>) :: Alternative f => f a -> 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 -- | Right-to-left composition of functors. The composition of applicative -- functors is always applicative, but the composition of monads is not -- always a monad. newtype Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) Compose :: f (g a) -> Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) [getCompose] :: Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) -> f (g a) infixr 9 `Compose` infixr 9 `Compose` -- | 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 <$!> -- | Like replicateM, but discards the result. replicateM_ :: Applicative m => Int -> m a -> m () -- | replicateM n act performs the action n times, -- gathering the results. replicateM :: Applicative m => Int -> m a -> m [a] -- | Like foldM, but discards the result. foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m () -- | The foldM function is analogous to foldl, except that -- its result is encapsulated in a monad. Note that foldM works -- from left-to-right over the list arguments. This could be an issue -- where (>>) and the `folded function' are not -- commutative. -- --
--   foldM f a1 [x1, x2, ..., xm]
--   
--   ==
--   
--   do
--     a2 <- f a1 x1
--     a3 <- f a2 x2
--     ...
--     f am xm
--   
-- -- If right-to-left evaluation is required, the input list should be -- reversed. -- -- Note: foldM is the same as foldlM foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | zipWithM_ is the extension of zipWithM which ignores the -- final result. zipWithM_ :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m () -- | The zipWithM function generalizes zipWith to arbitrary -- applicative functors. zipWithM :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m [c] -- | The mapAndUnzipM function maps its first argument over a list, -- returning the result as a pair of lists. This function is mainly used -- with complicated data structures or a state 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] -- | This function may be used as a value for foldMap in a -- Foldable instance. -- --
--   foldMapDefault f ≡ getConst . traverse (Const . f)
--   
foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m -- | This function may be used as a value for fmap in a -- Functor instance, provided that traverse is defined. -- (Using fmapDefault with a Traversable instance defined -- only by sequenceA will result in infinite recursion.) -- --
--   fmapDefault f ≡ runIdentity . traverse (Identity . f)
--   
fmapDefault :: Traversable t => (a -> b) -> t a -> t b -- | The mapAccumR function behaves like a combination of -- fmap and foldr; it applies a function to each element of -- a structure, passing an accumulating parameter from right to left, and -- returning a final value of this accumulator together with the new -- structure. mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) -- | The mapAccumL function behaves like a combination of -- fmap and foldl; it applies a function to each element of -- a structure, passing an accumulating parameter from left to right, and -- returning a final value of this accumulator together with the new -- structure. mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) -- | forM is mapM with its arguments flipped. For a version -- that ignores the results see forM_. forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b) -- | 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 -- | 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 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) Const :: a -> Const a (b :: k) [getConst] :: Const a (b :: k) -> a -- | The least element of a non-empty structure with respect to the given -- comparison function. minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a -- | The largest element of a non-empty structure with respect to the given -- comparison function. maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a -- | Map a function over all the elements of a container and concatenate -- the resulting lists. concatMap :: Foldable t => (a -> [b]) -> t a -> [b] -- | Monadic fold over the elements of a structure, associating to the -- left, i.e. from left to right. foldlM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | Monadic fold over the elements of a structure, associating to the -- right, i.e. from right to left. foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b -- | 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) Alt :: f a -> Alt (f :: k -> Type) (a :: k) [getAlt] :: Alt (f :: k -> Type) (a :: k) -> f a -- | Convert an integer into an unknown type-level natural. someNatVal :: Natural -> SomeNat natVal :: forall (n :: Nat) proxy. KnownNat n => proxy n -> Natural -- | This type represents unknown type-level natural numbers. data SomeNat SomeNat :: 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]] -- | O(n). 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] -- | O(n). The genericLength function is an overloaded -- version of length. In particular, instead of returning an -- Int, it returns any type which is an instance of Num. It -- is, however, less efficient than length. -- --
--   >>> genericLength [1, 2, 3] :: Int
--   3
--   
--   >>> genericLength [1, 2, 3] :: Float
--   3.0
--   
genericLength :: Num i => [a] -> i -- | The 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] -- | O(n). 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] -- | O(min(m,n)). 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 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] -- |
--   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) Proxy :: Proxy (t :: k) -- | 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 integralEnumFromThenTo :: Integral a => a -> a -> a -> [a] integralEnumFromTo :: Integral a => a -> a -> [a] integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a] integralEnumFrom :: (Integral a, Bounded a) => a -> [a] gcdWord' :: Word -> Word -> Word gcdInt' :: Int -> Int -> Int -- | 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 (^^%^^) :: Integral a => Rational -> a -> Rational (^%^) :: Integral a => Rational -> a -> Rational -- | raise a number to an integral power (^^) :: (Fractional a, Integral b) => a -> b -> a infixr 8 ^^ odd :: Integral a => a -> Bool even :: Integral a => a -> Bool numericEnumFromThenTo :: (Ord a, Fractional a) => a -> a -> a -> [a] numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a] numericEnumFromThen :: Fractional a => a -> a -> [a] numericEnumFrom :: Fractional a => a -> [a] -- | Extract the denominator of the ratio in reduced form: the numerator -- and denominator have no common factor and the denominator is positive. denominator :: 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 -- | reduce is a subsidiary function used only in this module. It -- normalises a ratio by dividing both numerator and denominator by their -- greatest common divisor. reduce :: Integral a => a -> a -> Ratio a notANumber :: Rational infinity :: Rational ratioPrec1 :: Int ratioPrec :: Int underflowError :: a overflowError :: a ratioZeroDenominatorError :: a divZeroError :: a boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a] boundedEnumFrom :: (Enum a, Bounded a) => 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]) -- | O(min(m,n)). 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 (+) [1, 2, 3] [4, 5, 6]
--   [5,7,9]
--   
-- -- zipWith is right-lazy: -- --
--   zipWith f [] _|_ = []
--   
-- -- zipWith is capable of list fusion, but it is restricted to its -- first list argument and its resulting list. zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] -- | zip3 takes three lists and returns a list of triples, analogous -- to zip. It is capable of list fusion, but it is restricted to -- its first list argument and its resulting list. zip3 :: [a] -> [b] -> [c] -> [(a, b, c)] -- | 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] -- | O(n). 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] -- | O(n). 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 given Just. -- --

Examples

-- -- Basic usage: -- --
--   >>> maybeToList (Just 7)
--   [7]
--   
-- --
--   >>> maybeToList Nothing
--   []
--   
-- -- One can use maybeToList to avoid pattern matching when combined -- with a function that (safely) works on lists: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> sum $ maybeToList (readMaybe "3")
--   3
--   
--   >>> sum $ maybeToList (readMaybe "")
--   0
--   
maybeToList :: Maybe a -> [a] -- | The 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 -- | 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 <&> -- | 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 -- | flip f takes its (first) two arguments in the reverse -- order of f. -- --
--   >>> flip (++) "hello" "world"
--   "worldhello"
--   
flip :: (a -> b -> c) -> b -> a -> c maxInt :: Int minInt :: Int -- | The fromEnum method restricted to the type Char. ord :: Char -> Int -- | In many situations, the liftM operations can be replaced by -- uses of ap, which promotes function application. -- --
--   return f `ap` x1 `ap` ... `ap` xn
--   
-- -- is equivalent to -- --
--   liftMn f x1 x2 ... xn
--   
ap :: Monad m => m (a -> b) -> m a -> m b -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM5 :: Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM4 :: Monad m => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM3 :: Monad m => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right. For example, -- --
--   liftM2 (+) [0,1] [0,2] = [0,2,1,3]
--   liftM2 (+) (Just 1) Nothing = Nothing
--   
liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r -- | 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 :: e -> SomeException -- | The trivial monad transformer, which maps a monad to an equivalent -- monad. data IdentityT (f :: k -> Type) (a :: k) -- | 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 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 -> () -- | 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 -- | The parameterizable maybe monad, obtained by composing an arbitrary -- monad with the Maybe monad. -- -- Computations are actions that may produce a value or exit. -- -- The return function yields a computation that produces that -- value, while >>= sequences two subcomputations, exiting -- if either computation does. newtype MaybeT (m :: Type -> Type) a MaybeT :: m (Maybe a) -> MaybeT (m :: Type -> Type) a [runMaybeT] :: MaybeT (m :: Type -> Type) 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 (m :: Type -> Type) a -- | A class for monads in which exceptions may be thrown. -- -- Instances should obey the following law: -- --
--   throwM e >> x = throwM e
--   
-- -- In other words, throwing an exception short-circuits the rest of the -- monadic computation. class Monad m => MonadThrow (m :: Type -> Type) -- | A class for monads which allow exceptions to be caught, in particular -- exceptions which were thrown by throwM. -- -- Instances should obey the following law: -- --
--   catch (throwM e) f = f e
--   
-- -- Note that the ability to catch an exception does not guarantee -- that we can deal with all possible exit points from a computation. -- Some monads, such as continuation-based stacks, allow for more than -- just a success/failure strategy, and therefore catch -- cannot be used by those monads to properly implement a function -- such as finally. For more information, see MonadMask. class MonadThrow m => MonadCatch (m :: Type -> Type) -- | A class for monads which provide for the ability to account for all -- possible exit points from a computation, and to mask asynchronous -- exceptions. Continuation-based monads are invalid instances of this -- class. -- -- Instances should ensure that, in the following code: -- --
--   fg = f `finally` g
--   
-- -- The action g is called regardless of what occurs within -- f, including async exceptions. Some monads allow f -- to abort the computation via other effects than throwing an exception. -- For simplicity, we will consider aborting and throwing an exception to -- be two forms of "throwing an error". -- -- If f and g both throw an error, the error thrown by -- fg depends on which errors we're talking about. In a monad -- transformer stack, the deeper layers override the effects of the inner -- layers; for example, ExceptT e1 (Except e2) a represents a -- value of type Either e2 (Either e1 a), so throwing both an -- e1 and an e2 will result in Left e2. If -- f and g both throw an error from the same layer, -- instances should ensure that the error from g wins. -- -- Effects other than throwing an error are also overriden by the deeper -- layers. For example, StateT s Maybe a represents a value of -- type s -> Maybe (a, s), so if an error thrown from -- f causes this function to return Nothing, any -- changes to the state which f also performed will be erased. -- As a result, g will see the state as it was before -- f. Once g completes, f's error will be -- rethrown, so g' state changes will be erased as well. This is -- the normal interaction between effects in a monad transformer stack. -- -- By contrast, lifted-base's version of finally always -- discards all of g's non-IO effects, and g never sees -- any of f's non-IO effects, regardless of the layer ordering -- and regardless of whether f throws an error. This is not the -- result of interacting effects, but a consequence of -- MonadBaseControl's approach. class MonadCatch m => MonadMask (m :: Type -> Type) -- | Runs an action with asynchronous exceptions disabled. The action is -- provided a method for restoring the async. environment to what it was -- at the mask call. See Control.Exception's mask. mask :: MonadMask m => ((forall a. () => m a -> m a) -> m b) -> m b -- | Like mask, but the masked computation is not interruptible (see -- Control.Exception's uninterruptibleMask. WARNING: Only -- use if you need to mask exceptions around an interruptible operation -- AND you can guarantee the interruptible operation will only block for -- a short period of time. Otherwise you render the program/thread -- unresponsive and/or unkillable. uninterruptibleMask :: MonadMask m => ((forall a. () => m a -> m a) -> m b) -> m b -- | A generalized version of bracket which uses ExitCase to -- distinguish the different exit cases, and returns the values of both -- the use and release actions. In practice, this extra -- information is rarely needed, so it is often more convenient to use -- one of the simpler functions which are defined in terms of this one, -- such as bracket, finally, onError, and -- bracketOnError. -- -- This function exists because in order to thread their effects through -- the execution of bracket, monad transformers need values to be -- threaded from use to release and from -- release to the output value. -- -- NOTE This method was added in version 0.9.0 of this library. -- Previously, implementation of functions like bracket and -- finally in this module were based on the mask and -- uninterruptibleMask functions only, disallowing some classes of -- tranformers from having MonadMask instances (notably -- multi-exit-point transformers like ExceptT). If you are a -- library author, you'll now need to provide an implementation for this -- method. The StateT implementation demonstrates most of the -- subtleties: -- --
--   generalBracket acquire release use = StateT $ s0 -> do
--     ((b, _s2), (c, s3)) <- generalBracket
--       (runStateT acquire s0)
--       ((resource, s1) exitCase -> case exitCase of
--         ExitCaseSuccess (b, s2) -> runStateT (release resource (ExitCaseSuccess b)) s2
--   
--         -- In the two other cases, the base monad overrides use's state
--         -- changes and the state reverts to s1.
--         ExitCaseException e     -> runStateT (release resource (ExitCaseException e)) s1
--         ExitCaseAbort           -> runStateT (release resource ExitCaseAbort) s1
--       )
--       ((resource, s1) -> runStateT (use resource) s1)
--     return ((b, c), s3)
--   
-- -- The StateT s m implementation of generalBracket -- delegates to the m implementation of generalBracket. -- The acquire, use, and release arguments -- given to StateT's implementation produce actions of type -- StateT s m a, StateT s m b, and StateT s m -- c. In order to run those actions in the base monad, we need to -- call runStateT, from which we obtain actions of type m -- (a, s), m (b, s), and m (c, s). Since each -- action produces the next state, it is important to feed the state -- produced by the previous action to the next action. -- -- In the ExitCaseSuccess case, the state starts at s0, -- flows through acquire to become s1, flows through -- use to become s2, and finally flows through -- release to become s3. In the other two cases, -- release does not receive the value s2, so its action -- cannot see the state changes performed by use. This is fine, -- because in those two cases, an error was thrown in the base monad, so -- as per the usual interaction between effects in a monad transformer -- stack, those state changes get reverted. So we start from s1 -- instead. -- -- Finally, the m implementation of generalBracket -- returns the pairs (b, s) and (c, s). For monad -- transformers other than StateT, this will be some other type -- representing the effects and values performed and returned by the -- use and release actions. The effect part of the -- use result, in this case _s2, usually needs to be -- discarded, since those effects have already been incorporated in the -- release action. -- -- The only effect which is intentionally not incorporated in the -- release action is the effect of throwing an error. In that -- case, the error must be re-thrown. One subtlety which is easy to miss -- is that in the case in which use and release both -- throw an error, the error from release should take priority. -- Here is an implementation for ExceptT which demonstrates how -- to do this. -- --
--   generalBracket acquire release use = ExceptT $ do
--     (eb, ec) <- generalBracket
--       (runExceptT acquire)
--       (eresource exitCase -> case eresource of
--         Left e -> return (Left e) -- nothing to release, acquire didn't succeed
--         Right resource -> case exitCase of
--           ExitCaseSuccess (Right b) -> runExceptT (release resource (ExitCaseSuccess b))
--           ExitCaseException e       -> runExceptT (release resource (ExitCaseException e))
--           _                         -> runExceptT (release resource ExitCaseAbort))
--       (either (return . Left) (runExceptT . use))
--     return $ do
--       -- The order in which we perform those two Either effects determines
--       -- which error will win if they are both Lefts. We want the error from
--       -- release to win.
--       c <- ec
--       b <- eb
--       return (b, c)
--   
generalBracket :: MonadMask m => m a -> (a -> ExitCase b -> m c) -> (a -> m b) -> m (b, c) -- | O(n) Convert a lazy Text into a strict Text. toStrict :: Text -> Text -- | A set of values. A set cannot contain duplicate values. data HashSet a -- | A state transformer monad parameterized by: -- -- -- -- The return function leaves the state unchanged, while -- >>= uses the final state of the first computation as -- the initial state of the second. newtype StateT s (m :: Type -> Type) a StateT :: (s -> m (a, s)) -> StateT s (m :: Type -> Type) a [runStateT] :: StateT s (m :: Type -> Type) a -> s -> m (a, s) -- | 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 -- | Boxed vectors, supporting efficient slicing. data Vector 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 -- | Gets specific component of the state, using a projection function -- supplied. gets :: MonadState s m => (s -> a) -> m a -- | s ^.. t returns the list of all values that t gets -- from s. -- -- A Maybe contains either 0 or 1 values: -- --
--   >>> Just 3 ^.. _Just
--   [3]
--   
-- -- Gathering all values in a list of tuples: -- --
--   >>> [(1,2),(3,4)] ^.. each.each
--   [1,2,3,4]
--   
(^..) :: s -> Getting (Endo [a]) s a -> [a] infixl 8 ^.. -- | set is a synonym for (.~). -- -- Setting the 1st component of a pair: -- --
--   set _1 :: x -> (a, b) -> (x, b)
--   set _1 = \x t -> (x, snd t)
--   
-- -- Using it to rewrite (<$): -- --
--   set mapped :: Functor f => a -> f b -> f a
--   set mapped = (<$)
--   
set :: ASetter s t a b -> b -> s -> t -- | (.~) assigns a value to the target. It's the same thing as -- using (%~) with const: -- --
--   l .~ x = l %~ const x
--   
-- -- See set if you want a non-operator synonym. -- -- Here it is used to change 2 fields of a 3-tuple: -- --
--   >>> (0,0,0) & _1 .~ 1 & _3 .~ 3
--   (1,0,3)
--   
(.~) :: ASetter s t a b -> b -> s -> t infixr 4 .~ -- | over is a synonym for (%~). -- -- Getting fmap in a roundabout way: -- --
--   over mapped :: Functor f => (a -> b) -> f a -> f b
--   over mapped = fmap
--   
-- -- Applying a function to both components of a pair: -- --
--   over both :: (a -> b) -> (a, a) -> (b, b)
--   over both = \f t -> (f (fst t), f (snd t))
--   
-- -- Using over _2 as a replacement for -- second: -- --
--   >>> over _2 show (10,20)
--   (10,"20")
--   
over :: ASetter s t a b -> (a -> b) -> s -> t -- | Gives access to the 1st field of a tuple (up to 5-tuples). -- -- Getting the 1st component: -- --
--   >>> (1,2,3,4,5) ^. _1
--   1
--   
-- -- Setting the 1st component: -- --
--   >>> (1,2,3) & _1 .~ 10
--   (10,2,3)
--   
-- -- Note that this lens is lazy, and can set fields even of -- undefined: -- --
--   >>> set _1 10 undefined :: (Int, Int)
--   (10,*** Exception: Prelude.undefined
--   
-- -- This is done to avoid violating a lens law stating that you can get -- back what you put: -- --
--   >>> view _1 . set _1 10 $ (undefined :: (Int, Int))
--   10
--   
-- -- The implementation (for 2-tuples) is: -- --
--   _1 f t = (,) <$> f    (fst t)
--                <*> pure (snd t)
--   
-- -- or, alternatively, -- --
--   _1 f ~(a,b) = (\a' -> (a',b)) <$> f a
--   
-- -- (where ~ means a lazy pattern). -- -- _2, _3, _4, and _5 are also available (see -- below). _1 :: Field1 s t a b => Lens s t a b _2 :: Field2 s t a b => Lens s t a b _3 :: Field3 s t a b => Lens s t a b _4 :: Field4 s t a b => Lens s t a b _5 :: Field5 s t a b => Lens s t a b -- | Lens s t a b is the lowest common denominator of a setter and -- a getter, something that has the power of both; it has a -- Functor constraint, and since both Const and -- Identity are functors, it can be used whenever a getter or a -- setter is needed. -- -- type Lens s t a b = forall (f :: Type -> Type). Functor f => a -> f b -> s -> f t -- | This is a type alias for monomorphic lenses which don't change the -- type of the container (or of the value inside). type Lens' s a = Lens s s a a -- | Traversal s t a b is a generalisation of Lens which -- allows many targets (possibly 0). It's achieved by changing the -- constraint to Applicative instead of Functor – indeed, -- the point of Applicative is that you can combine effects, which -- is just what we need to have many targets. -- -- Ultimately, traversals should follow 2 laws: -- --
--   t pure ≡ pure
--   fmap (t f) . t g ≡ getCompose . t (Compose . fmap f . g)
--   
-- -- The 1st law states that you can't change the shape of the structure or -- do anything funny with elements (traverse elements which aren't in the -- structure, create new elements out of thin air, etc.). The 2nd law -- states that you should be able to fuse 2 identical traversals into -- one. For a more detailed explanation of the laws, see this blog -- post (if you prefer rambling blog posts), or The Essence Of The -- Iterator Pattern (if you prefer papers). -- -- Traversing any value twice is a violation of traversal laws. You can, -- however, traverse values in any order. type Traversal s t a b = forall (f :: Type -> Type). Applicative f => a -> f b -> s -> f t -- | This is a type alias for monomorphic traversals which don't change the -- type of the container (or of the values inside). type Traversal' s a = Traversal s s a a -- | 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 () -- | Retrieves a function of the current environment. asks :: MonadReader r m => (r -> a) -> m a -- | The reader monad transformer, which adds a read-only environment to -- the given monad. -- -- The return function ignores the environment, while -- >>= passes the inherited environment to both -- subcomputations. newtype ReaderT r (m :: Type -> Type) a ReaderT :: (r -> m a) -> ReaderT r (m :: Type -> Type) a [runReaderT] :: ReaderT r (m :: Type -> Type) a -> r -> m a -- | preuse is (^?) (or preview) which implicitly -- operates on the state – it takes the state and applies a traversal (or -- fold) to it to extract the 1st element the traversal points at. -- --
--   preuse l = gets (preview l)
--   
preuse :: MonadState s m => Getting (First a) s a -> m (Maybe a) -- | use is (^.) (or view) which implicitly operates -- on the state; for instance, if your state is a record containing a -- field foo, you can write -- --
--   x <- use foo
--   
-- -- to extract foo from the state. In other words, use is -- the same as gets, but for getters instead of functions. -- -- The implementation of use is straightforward: -- --
--   use l = gets (view l)
--   
-- -- If you need to extract something with a fold or traversal, you need -- preuse. use :: MonadState s m => Getting a s a -> m a -- | preview is a synonym for (^?), generalised for -- MonadReader (just like view, which is a synonym for -- (^.)). -- --
--   >>> preview each [1..5]
--   Just 1
--   
preview :: MonadReader s m => Getting (First a) s a -> m (Maybe a) -- | view is a synonym for (^.), generalised for -- MonadReader (we are able to use it instead of (^.) since -- functions are instances of the MonadReader class): -- --
--   >>> view _1 (1, 2)
--   1
--   
-- -- When you're using Reader for config and your config type has -- lenses generated for it, most of the time you'll be using view -- instead of asks: -- --
--   doSomething :: (MonadReader Config m) => m Int
--   doSomething = do
--     thingy        <- view setting1  -- same as “asks (^. setting1)”
--     anotherThingy <- view setting2
--     ...
--   
view :: MonadReader s m => Getting a s 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 variant of modify in which the computation is strict in the -- new state. modify' :: MonadState s m => (s -> s) -> m () -- | The inverse of ExceptT. runExceptT :: ExceptT e m a -> m (Either e a) -- | Runs a Reader and extracts the final value from it. (The -- inverse of reader.) runReader :: Reader r a -> r -> a -- | 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 -- | Async safe version of bracketOnError bracketOnError :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c -- | Async safe version of finally finally :: MonadMask m => m a -> m b -> m a -- | Async safe version of bracket_ bracket_ :: MonadMask m => m a -> m b -> m c -> m c -- | Async safe version of bracket bracket :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c -- | Async safe version of onException onException :: MonadMask m => m a -> m b -> m a -- | try specialized to catch all synchronous exceptions tryAny :: MonadCatch m => m a -> m (Either SomeException a) -- | Same as upstream try, but will not catch asynchronous -- exceptions try :: (MonadCatch m, Exception e) => m a -> m (Either e a) -- | Flipped version of catchAny handleAny :: MonadCatch m => (SomeException -> m a) -> m a -> m a -- | catch specialized to catch all synchronous exception catchAny :: MonadCatch m => m a -> (SomeException -> m a) -> m a -- | Same as upstream catch, but will not catch asynchronous -- exceptions catch :: (MonadCatch m, Exception e) => m a -> (e -> m a) -> m a -- | Synonym for throw throwM :: (MonadThrow m, Exception e) => e -> m a -- | Strict version of modifyTVar. modifyTVar' :: TVar a -> (a -> a) -> STM () -- | O(c) Convert a strict Text into a lazy Text. fromStrict :: Text -> Text -- | O(n) Joins words using single space characters. unwords :: [Text] -> Text -- | O(n) Joins lines, after appending a terminating newline to -- each. unlines :: [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) Breaks a Text up into a list of words, delimited by -- Chars representing white space. words :: Text -> [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 -- | 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 -- | Replace an invalid input byte with the Unicode replacement character -- U+FFFD. lenientDecode :: OnDecodeError -- | Throw a UnicodeException if decoding fails. strictDecode :: OnDecodeError -- | 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 -- | A handler for a decoding error. type OnDecodeError = OnError Word8 Char -- | An exception type for representing Unicode encoding errors. data UnicodeException -- | Convert a ExceptT computation to MaybeT, discarding the -- value of any exception. exceptToMaybeT :: forall (m :: Type -> Type) e a. Functor m => ExceptT e m a -> MaybeT m a -- | Convert a MaybeT computation to ExceptT, with a default -- exception value. maybeToExceptT :: forall (m :: Type -> Type) e a. Functor m => e -> MaybeT m a -> ExceptT e m a -- | This type class allows to implement variadic composition operator. class SuperComposition a b c | a b -> c -- | Allows to apply function to result of another function with multiple -- arguments. -- --
--   >>> (show ... (+)) 1 2
--   "3"
--   
--   >>> show ... 5
--   "5"
--   
--   >>> (null ... zip5) [1] [2] [3] [] [5]
--   True
--   
-- -- Inspired by -- http://stackoverflow.com/questions/9656797/variadic-compose-function. -- --

Performance

-- -- To check the performance there was done a bunch of benchmarks. -- Benchmarks were made on examples given above and also on the functions -- of many arguments. The results are showing that the operator -- (...) performs as fast as plain applications of the operator -- (.) on almost all the tests, but (...) leads to the -- performance draw-down if ghc fails to inline it. Slow -- behavior was noticed on functions without type specifications. That's -- why keep in mind that providing explicit type declarations for -- functions is very important when using (...). Relying on type -- inference will lead to the situation when all optimizations disappear -- due to very general inferred type. However, functions without type -- specification but with applied INLINE pragma are fast again. (...) :: SuperComposition a b c => a -> b -> c infixl 8 ... -- | Infix application. -- --
--   f :: Either String $ Maybe Int
--   =
--   f :: Either String (Maybe Int)
--   
type (f :: k1 -> k) $ (a :: k1) = f a infixr 2 $ -- | Map several constraints over several variables. -- --
--   f :: Each [Show, Read] [a, b] => a -> b -> String
--   =
--   f :: (Show a, Show b, Read a, Read b) => a -> b -> String
--   
-- -- To specify list with single constraint / variable, don't forget to -- prefix it with ': -- --
--   f :: Each '[Show] [a, b] => a -> b -> String
--   
type family Each (c :: [k -> Constraint]) (as :: [k]) -- | Map several constraints over a single variable. Note, that With a -- b ≡ Each a '[b] -- --
--   a :: With [Show, Read] a => a -> a
--   =
--   a :: (Show a, Read a) => a -> a
--   
type With (a :: [k -> Constraint]) (b :: k) = a <+> b -- | Generalized version of show. show :: forall b a. (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 -- | undefined that leaves a warning in code on every usage. undefined :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => a -- | Version of traceId that leaves a warning. traceId :: Text -> Text -- | Version of traceM that leaves a warning and takes Text. traceM :: Monad m => Text -> m () -- | Version of traceShowM that leaves a warning. traceShowM :: (Show a, Monad m) => a -> m () -- | Version of traceShowId that leaves a warning. Useful to tag -- printed data, for instance: -- --
--   traceShowIdWith ("My data: ", ) (veryLargeExpression)
--   
traceShowIdWith :: Show s => (a -> s) -> a -> a -- | Version of traceId that leaves a warning. Useful to tag printed -- data, for instance: -- --
--   traceIdWith (x -> "My data: " <> show x) (veryLargeExpression)
--   
-- -- This is especially useful with custom formatters: -- --
--   traceIdWith (x -> "My data: " <> pretty x) (veryLargeExpression)
--   
traceIdWith :: (a -> Text) -> a -> a -- | Version of traceShowId that leaves a warning. traceShowId :: Show a => a -> a -- | Version of traceShow that leaves a warning. traceShow :: Show a => a -> b -> b -- | error that takes Text as an argument. error :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => Text -> a -- | Version of trace that leaves a warning and takes Text. trace :: Text -> a -> a -- | Similar to undefined but data type. data Undefined Undefined :: Undefined -- | 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 hPrint hPrint :: (MonadIO m, Show a) => Handle -> a -> m () -- | Lifted version of print. print :: forall a m. (MonadIO m, Show a) => a -> m () -- | Write a string like value to stdout appending a newline -- character. putStrLn :: (Print a, MonadIO m) => a -> m () -- | Write a string like value to stdout/. putStr :: (Print a, MonadIO m) => a -> m () -- | Write a string like value a to a supplied Handle, -- appending a newline character. hPutStrLn :: (Print a, MonadIO m) => Handle -> a -> m () -- | Write a string like value a to a supplied Handle. hPutStr :: (Print a, MonadIO m) => Handle -> a -> m () -- | Support class to overload writing of string like values. class Print a -- | 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] -- | 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 -- | Throws error for Maybe if Nothing is given. Operates -- over MonadError. note :: MonadError e m => e -> Maybe 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 e
--       | Just (_ :: NodeAttackedError) <- fromException e = True
--       | Just DialogUnexpected{} <- fromException e = True
--       | otherwise = False
--   
-- -- you can use Exc pattern synonym: -- --
--   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 :: 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]) -- | Monadic and constrained to Container 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 :: (Container f, Monad m) => (Element f -> m Bool) -> f -> m Bool -- | Monadic and constrained to Container 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 :: (Container f, Monad m) => (Element f -> m Bool) -> f -> m Bool -- | Monadic and constrained to Container version of or. -- --
--   >>> orM [Just True, Just False]
--   Just True
--   
--   >>> orM [Just True, Nothing]
--   Just True
--   
--   >>> orM [Nothing, Just True]
--   Nothing
--   
orM :: (Container f, Element f ~ m Bool, Monad m) => f -> m Bool -- | Monadic and constrained to Container 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 :: (Container f, Element f ~ m Bool, Monad m) => f -> m Bool -- | Like concatMapM, but has its arguments flipped, so can be used -- instead of the common fmap concat $ forM pattern. concatForM :: (Applicative f, Monoid m, Container (l m), Element (l m) ~ m, Traversable l) => l a -> (a -> f m) -> f m -- | Lifting bind into a monad. Generalized version of concatMap -- that works with a monadic predicate. Old and simpler specialized to -- list version had next type: -- --
--   concatMapM :: Monad m => (a -> m [b]) -> [a] -> m [b]
--   
-- -- Side note: previously it had type -- --
--   concatMapM :: (Applicative q, Monad m, Traversable m)
--              => (a -> q (m b)) -> m a -> q (m b)
--   
-- -- Such signature didn't allow to use this function when traversed -- container type and type of returned by function-argument differed. Now -- you can use it like e.g. -- --
--   concatMapM readFile files >>= putTextLn
--   
concatMapM :: (Applicative f, Monoid m, Container (l m), Element (l m) ~ m, Traversable l) => (a -> f m) -> l a -> f m -- | Constrained to Container version of asum. -- --
--   >>> asum [Nothing, Just [False, True], Nothing, Just [True]]
--   Just [False,True]
--   
asum :: (Container t, Alternative f, Element t ~ f a) => t -> f a -- | Constrained to Container version of sequence_. -- --
--   >>> sequence_ [putTextLn "foo", print True]
--   foo
--   True
--   
sequence_ :: (Container t, Monad m, Element t ~ m a) => t -> m () -- | Constrained to Container version of sequenceA_. -- --
--   >>> sequenceA_ [putTextLn "foo", print True]
--   foo
--   True
--   
sequenceA_ :: (Container t, Applicative f, Element t ~ f a) => t -> f () -- | Constrained to Container version of forM_. -- --
--   >>> forM_ [True, False] print
--   True
--   False
--   
forM_ :: (Container t, Monad m) => t -> (Element t -> m b) -> m () -- | Constrained to Container version of mapM_. -- --
--   >>> mapM_ print [True, False]
--   True
--   False
--   
mapM_ :: (Container t, Monad m) => (Element t -> m b) -> t -> m () -- | Constrained to Container version of for_. -- --
--   >>> for_ [1 .. 5 :: Int] $ \i -> when (even i) (print i)
--   2
--   4
--   
for_ :: (Container t, Applicative f) => t -> (Element t -> f b) -> f () -- | Constrained to Container version of traverse_. -- --
--   >>> traverse_ putTextLn ["foo", "bar"]
--   foo
--   bar
--   
traverse_ :: (Container t, Applicative f) => (Element t -> f b) -> t -> f () -- | Stricter version of product. -- --
--   >>> product [1..10]
--   3628800
--   
--   >>> product (Right 3)
--   ...
--       • Do not use 'Foldable' methods on Either
--         Suggestions:
--             Instead of
--                 for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f ()
--             use
--                 whenJust  :: Applicative f => Maybe a    -> (a -> f ()) -> f ()
--                 whenRight :: Applicative f => Either l r -> (r -> f ()) -> f ()
--   ...
--             Instead of
--                 fold :: (Foldable t, Monoid m) => t m -> m
--             use
--                 maybeToMonoid :: Monoid m => Maybe m -> m
--   ...
--   
product :: (Container t, Num (Element t)) => t -> Element t -- | Stricter version of sum. -- --
--   >>> sum [1..10]
--   55
--   
--   >>> sum (Just 3)
--   ...
--       • Do not use 'Foldable' methods on Maybe
--         Suggestions:
--             Instead of
--                 for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f ()
--             use
--                 whenJust  :: Applicative f => Maybe a    -> (a -> f ()) -> f ()
--                 whenRight :: Applicative f => Either l r -> (r -> f ()) -> f ()
--   ...
--             Instead of
--                 fold :: (Foldable t, Monoid m) => t m -> m
--             use
--                 maybeToMonoid :: Monoid m => Maybe m -> m
--   ...
--   
sum :: (Container t, Num (Element t)) => t -> Element t -- | Similar to foldl' but takes a function with its arguments -- flipped. -- --
--   >>> flipfoldl' (/) 5 [2,3] :: Rational
--   15 % 2
--   
flipfoldl' :: (Container t, Element t ~ a) => (a -> b -> b) -> b -> t -> b -- | Type class for data types that can be converted to List of Pairs. You -- can define ToPairs by just defining toPairs function. -- -- But the following laws should be met: -- --
--   toPairs m ≡ zip (keys m) (elems m)
--   keysmap fst . toPairs
--   elemsmap snd . toPairs
--   
class ToPairs t -- | Converts the structure to the list of the key-value pairs. -- >>> toPairs (HashMap.fromList [(a, "xxx"), -- (b, "yyy")]) [(a,"xxx"),(b,"yyy")] toPairs :: ToPairs t => t -> [(Key t, Val t)] -- | Converts the structure to the list of the keys. -- --
--   >>> keys (HashMap.fromList [('a', "xxx"), ('b', "yyy")])
--   "ab"
--   
keys :: ToPairs t => t -> [Key t] -- | Converts the structure to the list of the values. -- --
--   >>> elems (HashMap.fromList [('a', "xxx"), ('b', "yyy")])
--   ["xxx","yyy"]
--   
elems :: ToPairs t => t -> [Val t] -- | Type of element for some container. Implemented as an asscociated type -- family because some containers are monomorphic over element type (like -- Text, IntSet, etc.) so we can't implement nice interface -- using old higher-kinded types approach. Implementing this as an -- associated type family instead of top-level family gives you more -- control over element types. type family Element t -- | Very similar to Foldable but also allows instances for -- monomorphic types like Text but forbids instances for -- Maybe and similar. This class is used as a replacement for -- Foldable type class. It solves the following problems: -- --
    --
  1. length, foldr and other functions work on more types -- for which it makes sense.
  2. --
  3. You can't accidentally use length on polymorphic -- Foldable (like list), replace list with Maybe and then -- debug error for two days.
  4. --
  5. More efficient implementaions of functions for polymorphic types -- (like elem for Set).
  6. --
-- -- The drawbacks: -- --
    --
  1. Type signatures of polymorphic functions look more scary.
  2. --
  3. Orphan instances are involved if you want to use foldr (and -- similar) on types from libraries.
  4. --
class Container t where { -- | Type of element for some container. Implemented as an asscociated type -- family because some containers are monomorphic over element type (like -- Text, IntSet, etc.) so we can't implement nice interface -- using old higher-kinded types approach. Implementing this as an -- associated type family instead of top-level family gives you more -- control over element types. type family Element t; type Element t = ElementDefault t; } -- | Convert container to list of elements. -- --
--   >>> toList @Text "aba"
--   "aba"
--   
--   >>> :t toList @Text "aba"
--   toList @Text "aba" :: [Char]
--   
toList :: Container t => t -> [Element t] -- | Checks whether container is empty. -- --
--   >>> null @Text ""
--   True
--   
--   >>> null @Text "aba"
--   False
--   
null :: Container t => t -> Bool foldr :: Container t => (Element t -> b -> b) -> b -> t -> b foldl :: Container t => (b -> Element t -> b) -> b -> t -> b foldl' :: Container t => (b -> Element t -> b) -> b -> t -> b length :: Container t => t -> Int elem :: Container t => Element t -> t -> Bool maximum :: Container t => t -> Element t minimum :: Container t => t -> Element t foldMap :: (Container t, Monoid m) => (Element t -> m) -> t -> m fold :: Container t => t -> Element t foldr' :: Container t => (Element t -> b -> b) -> b -> t -> b foldr1 :: Container t => (Element t -> Element t -> Element t) -> t -> Element t foldl1 :: Container t => (Element t -> Element t -> Element t) -> t -> Element t notElem :: Container t => Element t -> t -> Bool all :: Container t => (Element t -> Bool) -> t -> Bool any :: Container t => (Element t -> Bool) -> t -> Bool find :: Container t => (Element t -> Bool) -> t -> Maybe (Element t) safeHead :: Container t => t -> Maybe (Element t) type family OneItem x -- | Type class for types that can be created from one element. -- singleton is lone name for this function. Also constructions -- of different type differ: :[] for lists, two arguments for -- Maps. Also some data types are monomorphic. -- --
--   >>> one True :: [Bool]
--   [True]
--   
--   >>> one 'a' :: Text
--   "a"
--   
--   >>> one (3, "hello") :: HashMap Int String
--   fromList [(3,"hello")]
--   
class One x where { type family OneItem x; } -- | Create a list, map, Text, etc from a single element. one :: One x => OneItem x -> x -- | 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 whenRight. whenRightM :: Monad m => m (Either l r) -> (r -> m ()) -> m () -- | Monadic version of whenLeft. whenLeftM :: Monad m => m (Either l r) -> (l -> m ()) -> m () -- | 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 -- | Extracts value from Right or return given default value. -- --
--   >>> fromRight 0 (Left 3)
--   0
--   
--   >>> fromRight 0 (Right 5)
--   5
--   
fromRight :: b -> Either a b -> b -- | Extracts value from Left or return given default value. -- --
--   >>> fromLeft 0 (Left 3)
--   3
--   
--   >>> fromLeft 0 (Right 5)
--   0
--   
fromLeft :: a -> Either a b -> 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 () -- | 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) -- | Opens a file, manipulates it with the provided function and closes the -- handle before returning. The Handle can be written to using the -- hPutStr and hPutStrLn functions. -- -- withFile is essentially the bracket pattern, specialized -- to files. This should be preferred over openFile + -- hClose as it properly deals with (asynchronous) exceptions. In -- cases where withFile is insufficient, for instance because the -- it is not statically known when manipulating the Handle has -- finished, one should consider other safe paradigms for resource usage, -- such as the ResourceT transformer from the resourcet -- package, before resorting to openFile and hClose. withFile :: (MonadIO m, MonadMask m) => FilePath -> IOMode -> (Handle -> m a) -> m a -- | Close a file handle -- -- See also withFile for more information. hClose :: MonadIO m => Handle -> m () -- | Lifted version of openFile. -- -- See also withFile for more information. openFile :: MonadIO m => FilePath -> IOMode -> m Handle -- | 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 a -- | 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 <<$>> -- | map generalized to Functor. -- --
--   >>> map not (Just True)
--   Just False
--   
--   >>> map not [True,False,True,True]
--   [False,True,False,False]
--   
map :: Functor f => (a -> b) -> f a -> f b -- | Stricter version of $ operator. Default Prelude defines this at -- the toplevel module, so we do as well. -- --
--   >>> const 3 $ Prelude.undefined
--   3
--   
--   >>> const 3 $! Prelude.undefined
--   *** Exception: Prelude.undefined
--   ...
--   
($!) :: (a -> b) -> a -> b infixr 0 $! -- | Shorter alias for pure (). -- --
--   >>> pass :: Maybe ()
--   Just ()
--   
pass :: Applicative f => f () module Indigo.Internal.SIS -- | IndigoState with hidden output stack, necessary to generate -- typed Lorentz code from untyped Indigo frontend. newtype SomeIndigoState inp SomeIndigoState :: (MetaData inp -> SomeGenCode inp) -> SomeIndigoState inp [unSIS] :: SomeIndigoState inp -> MetaData inp -> SomeGenCode inp -- | GenCode with hidden output stack data SomeGenCode inp [SomeGenCode] :: GenCode inp out -> SomeGenCode inp -- | Convert IndigoState to SomeIndigoState toSIS :: IndigoState inp out -> SomeIndigoState inp -- | To run SomeIndigoState you need to pass an handler of -- GenCode with any output stack and initial MetaData. runSIS :: SomeIndigoState inp -> MetaData inp -> (forall out. GenCode inp out -> r) -> r -- | Similar to a >> for SomeIndigoState. thenSIS :: SomeIndigoState inp -> (forall out. SomeIndigoState out) -> SomeIndigoState inp -- | Modify the GenCode inside a SomeIndigoState by passing -- an handler of GenCode that returns a SomeGenCode. Useful -- in some cases to "wrap" or update and exising SomeGenCode. overSIS :: (forall out. GenCode inp out -> SomeGenCode inp) -> SomeIndigoState inp -> SomeIndigoState inp -- | This module contains a datatype representing a lens to a field, -- helpers to compose new lens, and type class like StoreHasField -- returning a lens. module Indigo.Internal.Field -- | Constraint to access/assign field stored in Rec type AccessFieldC a name = RElem name (ConstructorFieldNames a) (RIndex name (ConstructorFieldNames a)) -- | Get a field from list of fields fetchField :: forall a name f proxy. AccessFieldC a name => proxy name -> Rec f (ConstructorFieldNames a) -> f name -- | Assign a field to a value assignField :: forall a name f proxy. AccessFieldC a name => proxy name -> f name -> Rec f (ConstructorFieldNames a) -> Rec f (ConstructorFieldNames a) -- | Lens to a field. obj.f1.f2.f3 is represented as list names of -- [f1, f2, f3]. -- -- dt is a type of source object (type of obj in example above) -- fname is a name of target field ("f3" in example -- above) ftype is a type of target field -- -- However, a lens contains not only name of field but for each field it -- contains operations to get and set target field. data FieldLens dt fname ftype [TargetField] :: (InstrGetFieldC dt fname, InstrSetFieldC dt fname, GetFieldType dt fname ~ targetFType, AccessFieldC dt fname) => Label fname -> StoreFieldOps dt targetFName targetFType -> FieldLens dt targetFName targetFType [DeeperField] :: (AccessFieldC dt fname, InstrSetFieldC dt fname, HasField (GetFieldType dt fname) targetFName targetFType) => Label fname -> StoreFieldOps dt targetFName targetFType -> FieldLens dt targetFName targetFType -- | Access to StoreFieldOps flSFO :: FieldLens dt fname ftype -> StoreFieldOps dt fname ftype -- | Class like StoreHasField type class but holding a lens to a -- field. class (KnownValue ftype, KnownValue dt) => HasField dt fname ftype | dt fname -> ftype fieldLens :: HasField dt fname ftype => FieldLens dt fname ftype -- | Build a lens to deeper field of an object. fieldLensDeeper :: forall dt targetName targetType fname. (AccessFieldC dt fname, HasFieldOfType dt fname (GetFieldType dt fname), HasField (GetFieldType dt fname) targetName targetType) => Label fname -> FieldLens dt targetName targetType -- | Build a lens to a direct field of an object. fieldLensADT :: forall dt targetFName targetFType fname. (InstrGetFieldC dt fname, InstrSetFieldC dt fname, GetFieldType dt fname ~ targetFType, AccessFieldC dt fname) => Label fname -> FieldLens dt targetFName targetFType instance (Michelson.Typed.Haskell.Instr.Product.InstrSetFieldC dt fname, Michelson.Typed.Haskell.Instr.Product.InstrGetFieldC dt fname, Michelson.Typed.Haskell.Instr.Product.GetFieldType dt fname GHC.Types.~ ftype, Indigo.Internal.Field.AccessFieldC dt fname, GHC.TypeLits.KnownSymbol fname, Lorentz.Constraints.Scopes.KnownValue ftype, Lorentz.Constraints.Scopes.KnownValue dt) => Indigo.Internal.Field.HasField dt fname ftype -- | Expr data type and its generalizations module Indigo.Internal.Expr.Types data Expr a [C] :: NiceConstant a => a -> Expr a [V] :: KnownValue a => Var a -> Expr a [ObjMan] :: ObjectManipulation a -> Expr a [Cast] :: KnownValue a => Expr a -> Expr a [Size] :: SizeOpHs c => Expr c -> Expr Natural [Update] :: (UpdOpHs c, KnownValue c) => Expr c -> Expr (UpdOpKeyHs c) -> Expr (UpdOpParamsHs c) -> Expr c [Add] :: (ArithOpHs Add n m, KnownValue (ArithResHs Add n m)) => Expr n -> Expr m -> Expr (ArithResHs Add n m) [Sub] :: (ArithOpHs Sub n m, KnownValue (ArithResHs Sub n m)) => Expr n -> Expr m -> Expr (ArithResHs Sub n m) [Mul] :: (ArithOpHs Mul n m, KnownValue (ArithResHs Mul n m)) => Expr n -> Expr m -> Expr (ArithResHs Mul n m) [Div] :: (EDivOpHs n m, KnownValue (EDivOpResHs n m)) => Expr n -> Expr m -> Expr (EDivOpResHs n m) [Mod] :: (EDivOpHs n m, KnownValue (EModOpResHs n m)) => Expr n -> Expr m -> Expr (EModOpResHs n m) [Abs] :: (UnaryArithOpHs Abs n, KnownValue (UnaryArithResHs Abs n)) => Expr n -> Expr (UnaryArithResHs Abs n) [Neg] :: (UnaryArithOpHs Neg n, KnownValue (UnaryArithResHs Neg n)) => Expr n -> Expr (UnaryArithResHs Neg n) [Lsl] :: (ArithOpHs Lsl n m, KnownValue (ArithResHs Lsl n m)) => Expr n -> Expr m -> Expr (ArithResHs Lsl n m) [Lsr] :: (ArithOpHs Lsr n m, KnownValue (ArithResHs Lsr n m)) => Expr n -> Expr m -> Expr (ArithResHs Lsr n m) [Eq'] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Neq] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Le] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Lt] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Ge] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Gt] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Or] :: (ArithOpHs Or n m, KnownValue (ArithResHs Or n m)) => Expr n -> Expr m -> Expr (ArithResHs Or n m) [Xor] :: (ArithOpHs Xor n m, KnownValue (ArithResHs Xor n m)) => Expr n -> Expr m -> Expr (ArithResHs Xor n m) [And] :: (ArithOpHs And n m, KnownValue (ArithResHs And n m)) => Expr n -> Expr m -> Expr (ArithResHs And n m) [Not] :: (UnaryArithOpHs Not n, KnownValue (UnaryArithResHs Not n)) => Expr n -> Expr (UnaryArithResHs Not n) [Int'] :: Expr Natural -> Expr Integer [IsNat] :: Expr Integer -> Expr (Maybe Natural) [Coerce] :: (Castable_ a b, KnownValue b) => Expr a -> Expr b [ForcedCoerce] :: (MichelsonCoercible a b, KnownValue b) => Expr a -> Expr b [Fst] :: KnownValue n => Expr (n, m) -> Expr n [Snd] :: KnownValue m => Expr (n, m) -> Expr m [Pair] :: KnownValue (n, m) => Expr n -> Expr m -> Expr (n, m) [Some] :: KnownValue (Maybe t) => Expr t -> Expr (Maybe t) [None] :: KnownValue t => Expr (Maybe t) [Right'] :: (KnownValue y, KnownValue (Either y x)) => Expr x -> Expr (Either y x) [Left'] :: (KnownValue x, KnownValue (Either y x)) => Expr y -> Expr (Either y x) [Mem] :: MemOpHs c => Expr (MemOpKeyHs c) -> Expr c -> Expr Bool [StGet] :: (StoreHasSubmap store name key value, KnownValue value) => Label name -> Expr key -> Expr store -> Expr (Maybe value) [StInsertNew] :: (StoreHasSubmap store name key value, KnownValue store, IsError err) => Label name -> err -> Expr key -> Expr value -> Expr store -> Expr store [StInsert] :: (StoreHasSubmap store name key value, KnownValue store) => Label name -> Expr key -> Expr value -> Expr store -> Expr store [StMem] :: (StoreHasSubmap store name key val, KnownValue val) => Label name -> Expr key -> Expr store -> Expr Bool [StUpdate] :: (StoreHasSubmap store name key val, KnownValue store) => Label name -> Expr key -> Expr (Maybe val) -> Expr store -> Expr store [StDelete] :: (StoreHasSubmap store name key val, KnownValue store, KnownValue val) => Label name -> Expr key -> Expr store -> Expr store [Wrap] :: (InstrWrapOneC dt name, KnownValue dt) => Label name -> Expr (CtorOnlyField name dt) -> Expr dt [Unwrap] :: (InstrUnwrapC dt name, KnownValue (CtorOnlyField name dt)) => Label name -> Expr dt -> Expr (CtorOnlyField name dt) [Construct] :: (InstrConstructC dt, RMap (ConstructorFieldTypes dt), KnownValue dt) => Rec Expr (ConstructorFieldTypes dt) -> Expr dt [ConstructWithoutNamed] :: ComplexObjectC dt => Rec Expr (FieldTypes dt) -> Expr dt [Name] :: KnownValue (name :! t) => Label name -> Expr t -> Expr (name :! t) [UnName] :: KnownValue t => Label name -> Expr (name :! t) -> Expr t [EmptySet] :: (NiceComparable key, KnownValue (Set key)) => Expr (Set key) [Get] :: (GetOpHs c, KnownValue (Maybe (GetOpValHs c)), KnownValue (GetOpValHs c)) => Expr (GetOpKeyHs c) -> Expr c -> Expr (Maybe (GetOpValHs c)) [EmptyMap] :: (KnownValue value, NiceComparable key, KnownValue (Map key value)) => Expr (Map key value) [EmptyBigMap] :: (KnownValue value, NiceComparable key, KnownValue (BigMap key value)) => Expr (BigMap key value) [Pack] :: NicePackedValue a => Expr a -> Expr ByteString [Unpack] :: NiceUnpackedValue a => Expr ByteString -> Expr (Maybe a) [Cons] :: KnownValue (List a) => Expr a -> Expr (List a) -> Expr (List a) [Nil] :: KnownValue a => Expr (List a) [Concat] :: (ConcatOpHs c, KnownValue c) => Expr c -> Expr c -> Expr c [Concat'] :: (ConcatOpHs c, KnownValue c) => Expr (List c) -> Expr c [Slice] :: (SliceOpHs c, KnownValue c) => Expr Natural -> Expr Natural -> Expr c -> Expr (Maybe c) [Contract] :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p, ToTAddress p addr, ToT addr ~ ToT Address) => Expr addr -> Expr (Maybe (ContractRef p)) [Self] :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p) => Expr (ContractRef p) [ContractAddress] :: Expr (ContractRef p) -> Expr Address [ContractCallingUnsafe] :: NiceParameter arg => EpName -> Expr Address -> Expr (Maybe (ContractRef arg)) [RunFutureContract] :: NiceParameter p => Expr (FutureContract p) -> Expr (Maybe (ContractRef p)) [ImplicitAccount] :: Expr KeyHash -> Expr (ContractRef ()) [ConvertEpAddressToContract] :: NiceParameter p => Expr EpAddress -> Expr (Maybe (ContractRef p)) [MakeView] :: KnownValue (View a r) => Expr a -> Expr (ContractRef r) -> Expr (View a r) [MakeVoid] :: KnownValue (Void_ a b) => Expr a -> Expr (Lambda b b) -> Expr (Void_ a b) [CheckSignature] :: Expr PublicKey -> Expr Signature -> Expr ByteString -> Expr Bool [Sha256] :: Expr ByteString -> Expr ByteString [Sha512] :: Expr ByteString -> Expr ByteString [Blake2b] :: Expr ByteString -> Expr ByteString [HashKey] :: Expr PublicKey -> Expr KeyHash [ChainId] :: Expr ChainId [Now] :: Expr Timestamp [Amount] :: Expr Mutez [Balance] :: Expr Mutez [Sender] :: Expr Address [Exec] :: KnownValue b => Expr a -> Expr (Lambda a b) -> Expr b [NonZero] :: (NonZero n, KnownValue (Maybe n)) => Expr n -> Expr (Maybe n) type IsExpr op n = (ToExpr op, ExprType op ~ n, KnownValue n) class ToExpr' (Decide x) x => ToExpr x type ExprType a = ExprType' (Decide a) a type (:~>) op n = IsExpr op n toExpr :: forall a. ToExpr a => a -> Expr (ExprType a) type IsArithExpr exN exM a n m = (exN :~> n, exM :~> m, ArithOpHs a n m, KnownValue (ArithResHs a n m)) type IsUnaryArithExpr exN a n = (exN :~> n, UnaryArithOpHs a n, KnownValue (UnaryArithResHs a n)) type IsConcatExpr exN1 exN2 n = (exN1 :~> n, exN2 :~> n, ConcatOpHs n) type IsConcatListExpr exN n = (exN :~> List n, ConcatOpHs n, KnownValue n) type IsDivExpr exN exM n m = (exN :~> n, exM :~> m, EDivOpHs n m, KnownValue (EDivOpResHs n m)) type IsModExpr exN exM n m = (exN :~> n, exM :~> m, EDivOpHs n m, KnownValue (EModOpResHs n m)) type IsGetExpr exKey exMap map = (exKey :~> GetOpKeyHs map, exMap :~> map, GetOpHs map, KnownValue (GetOpValHs map)) type IsMemExpr exKey exN n = (exKey :~> MemOpKeyHs n, exN :~> n, MemOpHs n) type IsSizeExpr exN n = (exN :~> n, SizeOpHs n) type IsSliceExpr exN n = (exN :~> n, SliceOpHs n) type IsUpdExpr exKey exVal exMap map = (exKey :~> UpdOpKeyHs map, exVal :~> UpdOpParamsHs map, exMap :~> map, UpdOpHs map) -- | Datatype describing access to an inner fields of object, like -- object !. field1 !. field2 ~. (field3, value3) ~. (field4, -- value4) data ObjectManipulation a [Object] :: Expr a -> ObjectManipulation a [ToField] :: HasField dt fname ftype => ObjectManipulation dt -> Label fname -> ObjectManipulation ftype [SetField] :: HasField dt fname ftype => ObjectManipulation dt -> Label fname -> Expr ftype -> ObjectManipulation dt type ObjectExpr a = IndigoObjectF (NamedFieldExpr a) a -- | Auxiliary datatype where each field refers to an expression the field -- equals to. It's not recursive one. data NamedFieldExpr a name [NamedFieldExpr] :: {unNamedFieldExpr :: Expr (GetFieldType a name)} -> NamedFieldExpr a name instance Indigo.Internal.Expr.Types.ToExpr' (Indigo.Internal.Expr.Types.Decide x) x => Indigo.Internal.Expr.Types.ToExpr x instance Lorentz.Constraints.Scopes.KnownValue a => Indigo.Internal.Expr.Types.ToExpr' 'Indigo.Internal.Expr.Types.VarD (Indigo.Internal.Var.Var a) instance Lorentz.Constraints.Scopes.NiceConstant a => Indigo.Internal.Expr.Types.ToExpr' 'Indigo.Internal.Expr.Types.ValD a instance Indigo.Internal.Expr.Types.ToExpr' 'Indigo.Internal.Expr.Types.ObjManD (Indigo.Internal.Expr.Types.ObjectManipulation a) instance Indigo.Internal.Expr.Types.ToExpr' 'Indigo.Internal.Expr.Types.ExprD (Indigo.Internal.Expr.Types.Expr a) -- | Expr compilation module Indigo.Internal.Expr.Compilation compileExpr :: forall a inp. Expr a -> IndigoState inp (a & inp) -- | ObjManipulationRes represents a postponed compilation of -- ObjectManipulation datatype. When ObjectManipulation is -- being compiled we are trying to put off the generation of code for -- work with an object because we can just go to a deeper field without -- its "materialization" onto stack. data ObjManipulationRes inp a [StillObject] :: ObjectExpr a -> ObjManipulationRes inp a [OnStack] :: IndigoState inp (a & inp) -> ObjManipulationRes inp a -- | This function might look cumbersome but basically it either goes -- deeper to an inner field or generates Lorentz code. runObjectManipulation :: DecomposedObjects -> ObjectManipulation x -> ObjManipulationRes inp x namedToExpr :: NamedFieldObj x name -> Expr (GetFieldType x name) nullaryOp :: KnownValue res => (inp :-> (res : inp)) -> IndigoState inp (res : inp) unaryOp :: KnownValue res => Expr n -> ((n & inp) :-> (res & inp)) -> IndigoState inp (res & inp) binaryOp :: KnownValue res => Expr n -> Expr m -> ((n & (m & inp)) :-> (res & inp)) -> IndigoState inp (res & inp) ternaryOp :: KnownValue res => Expr n -> Expr m -> Expr l -> ((n & (m & (l & inp))) :-> (res & inp)) -> IndigoState inp (res & inp) nullaryOpFlat :: (inp :-> inp) -> IndigoState inp inp unaryOpFlat :: Expr n -> ((n & inp) :-> inp) -> IndigoState inp inp binaryOpFlat :: Expr n -> Expr m -> ((n & (m & inp)) :-> inp) -> IndigoState inp inp ternaryOpFlat :: Expr n -> Expr m -> Expr l -> ((n & (m & (l & inp))) :-> inp) -> IndigoState inp inp -- | Decompose a complex value into its fields to be used in -- setVar. Also functionality to generate code to deconstruct -- storage into primitive fields the storage consists of and to construct -- it back. module Indigo.Internal.Expr.Decompose -- | Decompose (shallowly) an expression to list of its direct fields. decomposeExpr :: ComplexObjectC a => DecomposedObjects -> Expr a -> ExprDecomposition inp a -- | For given element on stack, generate code which decomposes it to list -- of its deep non-decomposable fields. Clean up code of -- SomeIndigoState composes the value back. deepDecomposeCompose :: forall a inp. IsObject a => SIS' (a & inp) (Object a) -- | Datatype representing decomposition of Expr. data ExprDecomposition inp a [ExprFields] :: Rec Expr (FieldTypes a) -> ExprDecomposition inp a [Deconstructed] :: IndigoState inp (FieldTypes a ++ inp) -> ExprDecomposition inp a class IsObject' (TypeDecision a) a => IsObject a -- | Backend failing statements of Indigo. module Indigo.Backend.Error failWith :: KnownValue a => Expr a -> IndigoState s t failUsing_ :: IsError x => x -> IndigoState s t failCustom :: forall tag err s t. (err ~ ErrorArg tag, CustomErrorHasDoc tag, NiceConstant err) => Label tag -> Expr err -> IndigoState s t failCustom_ :: forall tag s t notVoidErrorMsg. (RequireNoArgError tag notVoidErrorMsg, CustomErrorHasDoc tag) => Label tag -> IndigoState s t failUnexpected_ :: MText -> IndigoState s t -- | All the basic Expressions used in Indigo code. -- -- Note: infix operators acting on structure follow a naming convention: -- --
    --
  1. the last character identifies the structure -- type:
  2. --
  3. the preceding characters identify the action:
  4. --
-- -- The only exception to this convention is (.:) (for cons) module Indigo.Internal.Expr.Symbolic constExpr :: NiceConstant a => a -> Expr a -- | Create an expression holding a variable. varExpr :: KnownValue a => Var a -> Expr a cast :: ex :~> a => ex -> Expr a add :: IsArithExpr exN exM Add n m => exN -> exM -> Expr (ArithResHs Add n m) sub :: IsArithExpr exN exM Sub n m => exN -> exM -> Expr (ArithResHs Sub n m) mul :: IsArithExpr exN exM Mul n m => exN -> exM -> Expr (ArithResHs Mul n m) div :: IsDivExpr exN exM n m => exN -> exM -> Expr (EDivOpResHs n m) mod :: IsModExpr exN exM n m => exN -> exM -> Expr (EModOpResHs n m) neg :: IsUnaryArithExpr exN Neg n => exN -> Expr (UnaryArithResHs Neg n) abs :: IsUnaryArithExpr exN Abs n => exN -> Expr (UnaryArithResHs Abs n) (+) :: IsArithExpr exN exM Add n m => exN -> exM -> Expr (ArithResHs Add n m) infixl 6 + (-) :: IsArithExpr exN exM Sub n m => exN -> exM -> Expr (ArithResHs Sub n m) infixl 6 - (*) :: IsArithExpr exN exM Mul n m => exN -> exM -> Expr (ArithResHs Mul n m) infixl 7 * (/) :: IsDivExpr exN exM n m => exN -> exM -> Expr (EDivOpResHs n m) infixl 7 / (%) :: IsModExpr exN exM n m => exN -> exM -> Expr (EModOpResHs n m) infixl 7 % eq :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool neq :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool lt :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool gt :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool le :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool ge :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool (==) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 == (/=) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 /= (<) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 < (>) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 > (<=) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 <= (>=) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 >= isNat :: ex :~> Integer => ex -> Expr (Maybe Natural) toInt :: ex :~> Natural => ex -> Expr Integer nonZero :: (ex :~> n, NonZero n, KnownValue (Maybe n)) => ex -> Expr (Maybe n) -- | Convert between types that have the same Michelson representation and -- an explicit permission for that in the face of CanCastTo -- constraint. coerce :: forall b a ex. (Castable_ a b, KnownValue b, ex :~> a) => ex -> Expr b -- | Convert between expressions of types that have the same Michelson -- representation. forcedCoerce :: forall b a ex. (MichelsonCoercible a b, KnownValue b, ex :~> a) => ex -> Expr b lsl :: IsArithExpr exN exM Lsl n m => exN -> exM -> Expr (ArithResHs Lsl n m) lsr :: IsArithExpr exN exM Lsr n m => exN -> exM -> Expr (ArithResHs Lsr n m) and :: IsArithExpr exN exM And n m => exN -> exM -> Expr (ArithResHs And n m) or :: IsArithExpr exN exM Or n m => exN -> exM -> Expr (ArithResHs Or n m) xor :: IsArithExpr exN exM Xor n m => exN -> exM -> Expr (ArithResHs Xor n m) not :: IsUnaryArithExpr exN Not n => exN -> Expr (UnaryArithResHs Not n) (<<<) :: IsArithExpr exN exM Lsl n m => exN -> exM -> Expr (ArithResHs Lsl n m) infixl 8 <<< (>>>) :: IsArithExpr exN exM Lsr n m => exN -> exM -> Expr (ArithResHs Lsr n m) infixl 8 >>> (&&) :: IsArithExpr exN exM And n m => exN -> exM -> Expr (ArithResHs And n m) infixr 3 && (||) :: IsArithExpr exN exM Or n m => exN -> exM -> Expr (ArithResHs Or n m) infixr 2 || (^) :: IsArithExpr exN exM Xor n m => exN -> exM -> Expr (ArithResHs Xor n m) infixr 2 ^ pack :: (ex :~> a, NicePackedValue a) => ex -> Expr ByteString unpack :: (NiceUnpackedValue a, exb :~> ByteString) => exb -> Expr (Maybe a) pair :: (ex1 :~> n, ex2 :~> m, KnownValue (n, m)) => ex1 -> ex2 -> Expr (n, m) car :: (op :~> (n, m), KnownValue n) => op -> Expr n cdr :: (op :~> (n, m), KnownValue m) => op -> Expr m fst :: (op :~> (n, m), KnownValue n) => op -> Expr n snd :: (op :~> (n, m), KnownValue m) => op -> Expr m some :: (ex :~> t, KnownValue (Maybe t)) => ex -> Expr (Maybe t) none :: KnownValue t => Expr (Maybe t) right :: (ex :~> x, KnownValue y, KnownValue (Either y x)) => ex -> Expr (Either y x) left :: (ex :~> y, KnownValue x, KnownValue (Either y x)) => ex -> Expr (Either y x) slice :: (an :~> Natural, bn :~> Natural, IsSliceExpr ex c) => (an, bn) -> ex -> Expr (Maybe c) concat :: IsConcatExpr exN1 exN2 n => exN1 -> exN2 -> Expr n (<>) :: IsConcatExpr exN1 exN2 n => exN1 -> exN2 -> Expr n infixr 6 <> concatAll :: IsConcatListExpr exN n => exN -> Expr n nil :: KnownValue a => Expr (List a) cons :: (ex1 :~> a, ex2 :~> List a) => ex1 -> ex2 -> Expr (List a) (.:) :: (ex1 :~> a, ex2 :~> List a) => ex1 -> ex2 -> Expr (List a) infixr 5 .: get :: IsGetExpr exKey exMap map => exKey -> exMap -> Expr (Maybe (GetOpValHs map)) update :: IsUpdExpr exKey exVal exMap map => (exKey, exVal) -> exMap -> Expr map insert :: (ExprInsertable c insParam, ex :~> c) => insParam -> ex -> Expr c remove :: (ExprRemovable c, exStruct :~> c, exKey :~> UpdOpKeyHs c) => exKey -> exStruct -> Expr c mem :: IsMemExpr exKey exN n => exKey -> exN -> Expr Bool size :: IsSizeExpr exN n => exN -> Expr Natural (#:) :: IsGetExpr exKey exMap map => exMap -> exKey -> Expr (Maybe (GetOpValHs map)) infixl 8 #: (!:) :: IsUpdExpr exKey exVal exMap map => exMap -> (exKey, exVal) -> Expr map infixl 8 !: (+:) :: (ExprInsertable c exParam, exStructure :~> c) => exStructure -> exParam -> Expr c infixl 8 +: (-:) :: (ExprRemovable c, exStruct :~> c, exKey :~> UpdOpKeyHs c) => exStruct -> exKey -> Expr c infixl 8 -: (?:) :: IsMemExpr exKey exN n => exN -> exKey -> Expr Bool infixl 8 ?: empty :: (ExprMagma c, NiceComparable (UpdOpKeyHs c), KnownValue c) => Expr c emptyBigMap :: (KnownValue value, NiceComparable key, KnownValue (BigMap key value)) => Expr (BigMap key value) emptyMap :: (KnownValue value, NiceComparable key, KnownValue (Map key value)) => Expr (Map key value) emptySet :: (NiceComparable key, KnownValue (Set key)) => Expr (Set key) stGet :: (StoreHasSubmap store name key value, KnownValue value, exKey :~> key, exStore :~> store) => exStore -> (Label name, exKey) -> Expr (Maybe value) stUpdate :: (StoreHasSubmap store name key value, exKey :~> key, exVal :~> Maybe value, exStore :~> store) => exStore -> (Label name, exKey, exVal) -> Expr store stInsert :: (StoreHasSubmap store name key value, exKey :~> key, exVal :~> value, exStore :~> store) => exStore -> (Label name, exKey, exVal) -> Expr store stInsertNew :: (StoreHasSubmap store name key value, IsError err, exKey :~> key, exVal :~> value, exStore :~> store) => exStore -> (Label name, err, exKey, exVal) -> Expr store stDelete :: (StoreHasSubmap store name key value, KnownValue value, exKey :~> key, exStore :~> store) => exStore -> (Label name, exKey) -> Expr store stMem :: (StoreHasSubmap store name key value, KnownValue value, exKey :~> key, exStore :~> store) => exStore -> (Label name, exKey) -> Expr Bool (#@) :: (StoreHasSubmap store name key value, KnownValue value, exKey :~> key, exStore :~> store) => exStore -> (Label name, exKey) -> Expr (Maybe value) infixr 8 #@ (!@) :: (StoreHasSubmap store name key value, exKey :~> key, exVal :~> Maybe value, exStore :~> store) => exStore -> (Label name, exKey, exVal) -> Expr store infixl 8 !@ (+@) :: (StoreHasSubmap store name key value, exKey :~> key, exVal :~> value, exStore :~> store) => exStore -> (Label name, exKey, exVal) -> Expr store infixr 8 +@ (++@) :: (StoreHasSubmap store name key value, IsError err, exKey :~> key, exVal :~> value, exStore :~> store) => exStore -> (Label name, err, exKey, exVal) -> Expr store infixr 8 ++@ (-@) :: (StoreHasSubmap store name key value, KnownValue value, exKey :~> key, exStore :~> store) => exStore -> (Label name, exKey) -> Expr store infixl 8 -@ (?@) :: (StoreHasSubmap store name key value, KnownValue value, exKey :~> key, exStore :~> store) => exStore -> (Label name, exKey) -> Expr Bool infixl 8 ?@ wrap :: (InstrWrapOneC dt name, exField :~> CtorOnlyField name dt, KnownValue dt) => Label name -> exField -> Expr dt unwrap :: (InstrUnwrapC dt name, exDt :~> dt, KnownValue (CtorOnlyField name dt)) => Label name -> exDt -> Expr (CtorOnlyField name dt) (!!) :: (HasField dt name ftype, exDt :~> dt, exFld :~> ftype) => exDt -> (Label name, exFld) -> Expr dt infixl 8 !! (#!) :: (HasField dt name ftype, exDt :~> dt) => exDt -> Label name -> Expr ftype infixl 8 #! name :: (ex :~> t, KnownValue (name :! t)) => Label name -> ex -> Expr (name :! t) unName :: (ex :~> (name :! t), KnownValue t) => Label name -> ex -> Expr t (!~) :: (ex :~> t, KnownValue (name :! t)) => ex -> Label name -> Expr (name :! t) infixl 8 !~ (#~) :: (ex :~> (name :! t), KnownValue t) => ex -> Label name -> Expr t infixl 8 #~ construct :: (InstrConstructC dt, KnownValue dt, RMap (ConstructorFieldTypes dt), fields ~ Rec Expr (ConstructorFieldTypes dt), RecFromTuple fields) => IsoRecTuple fields -> Expr dt constructRec :: (InstrConstructC dt, RMap (ConstructorFieldTypes dt), KnownValue dt) => Rec Expr (ConstructorFieldTypes dt) -> Expr dt contract :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p, ToTAddress p addr, ToT addr ~ ToT Address, exAddr :~> addr) => exAddr -> Expr (Maybe (ContractRef p)) self :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p) => Expr (ContractRef p) contractAddress :: exc :~> ContractRef p => exc -> Expr Address contractCallingUnsafe :: (NiceParameter arg, exAddr :~> Address) => EpName -> exAddr -> Expr (Maybe (ContractRef arg)) contractCallingString :: (NiceParameter arg, exAddr :~> Address) => MText -> exAddr -> Expr (Maybe (ContractRef arg)) runFutureContract :: (NiceParameter p, conExpr :~> FutureContract p) => conExpr -> Expr (Maybe (ContractRef p)) implicitAccount :: exkh :~> KeyHash => exkh -> Expr (ContractRef ()) convertEpAddressToContract :: (NiceParameter p, epExpr :~> EpAddress) => epExpr -> Expr (Maybe (ContractRef p)) makeView :: (KnownValue (View a r), exa :~> a, exCRef :~> ContractRef r) => exa -> exCRef -> Expr (View a r) makeVoid :: (KnownValue (Void_ a b), exa :~> a, exCRef :~> Lambda b b) => exa -> exCRef -> Expr (Void_ a b) now :: Expr Timestamp amount :: Expr Mutez sender :: Expr Address blake2b :: hashExpr :~> ByteString => hashExpr -> Expr ByteString sha256 :: hashExpr :~> ByteString => hashExpr -> Expr ByteString sha512 :: hashExpr :~> ByteString => hashExpr -> Expr ByteString hashKey :: keyExpr :~> PublicKey => keyExpr -> Expr KeyHash chainId :: Expr ChainId balance :: Expr Mutez checkSignature :: (pkExpr :~> PublicKey, sigExpr :~> Signature, hashExpr :~> ByteString) => pkExpr -> sigExpr -> hashExpr -> Expr Bool instance (Lorentz.Constraints.Scopes.NiceComparable k, Lorentz.Constraints.Scopes.KnownValue v) => Indigo.Internal.Expr.Symbolic.ExprRemovable (Michelson.Typed.Haskell.Value.BigMap k v) instance (Lorentz.Constraints.Scopes.NiceComparable k, Lorentz.Constraints.Scopes.KnownValue v) => Indigo.Internal.Expr.Symbolic.ExprRemovable (Data.Map.Internal.Map k v) instance Lorentz.Constraints.Scopes.NiceComparable a => Indigo.Internal.Expr.Symbolic.ExprRemovable (Data.Set.Internal.Set a) instance (Lorentz.Constraints.Scopes.NiceComparable k, exKey Indigo.Internal.Expr.Types.:~> k, exValue Indigo.Internal.Expr.Types.:~> v) => Indigo.Internal.Expr.Symbolic.ExprInsertable (Michelson.Typed.Haskell.Value.BigMap k v) (exKey, exValue) instance (Lorentz.Constraints.Scopes.NiceComparable k, exKey Indigo.Internal.Expr.Types.:~> k, exValue Indigo.Internal.Expr.Types.:~> v) => Indigo.Internal.Expr.Symbolic.ExprInsertable (Data.Map.Internal.Map k v) (exKey, exValue) instance (Lorentz.Constraints.Scopes.NiceComparable a, exKey Indigo.Internal.Expr.Types.:~> a) => Indigo.Internal.Expr.Symbolic.ExprInsertable (Data.Set.Internal.Set a) exKey instance Lorentz.Constraints.Scopes.KnownValue v => Indigo.Internal.Expr.Symbolic.ExprMagma (Michelson.Typed.Haskell.Value.BigMap k v) instance Lorentz.Constraints.Scopes.KnownValue v => Indigo.Internal.Expr.Symbolic.ExprMagma (Data.Map.Internal.Map k v) instance Indigo.Internal.Expr.Symbolic.ExprMagma (Data.Set.Internal.Set k) -- | Expressions supported in Indigo language and their compilation -- to Lorentz code. module Indigo.Internal.Expr module Indigo.Internal -- | Backend statements for variable manipulation: assignment, replacement, -- update. module Indigo.Backend.Var -- | Assign the given variable to the value resulting from the given -- expression. assignVar :: KnownValue x => Var x -> Expr x -> IndigoState inp (x & inp) -- | Set the variable to a new value. -- -- If a variable is a cell on the stack, we just compile passed -- expression and replace variable cell on stack. If a variable is -- decomposed, we decompose passed expression and call setVar -- recursively from its fields. -- -- Pay attention that this function takes a next RefId but it doesn't -- return RefId because all allocated variables will be destroyed during -- execution of the function, so allocated ones won't affect next -- allocated ones. setVar :: forall a inp. KnownValue a => RefId -> Var a -> Expr a -> IndigoState inp inp -- | Set the field (direct or indirect) of a complex object. setField :: forall dt fname ftype inp. (IsObject dt, IsObject ftype, HasField dt fname ftype) => RefId -> Var dt -> Label fname -> Expr ftype -> IndigoState inp inp -- | Call binary operator with constant argument to update a variable -- in-place. updateVar :: forall x y inp. (IsObject x, KnownValue y) => RefId -> ([y, x] :-> '[x]) -> Var x -> Expr y -> IndigoState inp inp -- | Machinery that provides the ability to return values from Indigo -- statements (like if, case, while, etc). You -- are allowed to return unit, one expression or a tuple of expressions. -- For instance: -- --
--   (a, b) <- if flag
--             then do
--                    anotherFlag <- newVar True
--                    return (5 +. var, anotherFlag ||. True)
--             else return (0, anotherVar)
--   
-- -- is a valid construction. Pay attention to the fact that 5 +. -- var has the type Expr Integer, but 0 is just an -- Integer and anotherFlag ||. True has type Expr -- Bool, but anotherVar has type Var Bool; -- and this code will compile anyway. This is done intentionally to avoid -- the burden of manually converting values to expressions (or -- variables). So you can write the same constructions as in a regular -- language. module Indigo.Backend.Scope -- | To avoid overlapping instances we need to somehow distinguish single -- values from tuples, because the instances: -- --
--   instance Something a
--   instance Something (a, b)
--   
-- -- overlap and adding {-# OVERLAPPING #-} doesn't rescue in some -- cases, especially for type families defined in Something. data BranchRetKind -- | If value is unit (don't return anything) Unit :: BranchRetKind -- | If it's a single value (not tuple) SingleVal :: BranchRetKind -- | If it's tuple (we don't care how many elements are in) Tuple :: BranchRetKind type ScopeCodeGen ret = ScopeCodeGen' (ClassifyReturnValue ret) ret -- | Type class which unions all related management of computations in a -- scope, like in if branch, in case body, etc. -- -- Particularly, it takes care of the computation of expressions -- returning from a scope to leave it safely. Basically, this type class -- encapsulates the generation of Lorentz code that looks like: -- --
--   branch_code #
--     -- we get some arbitrary type of a stack here, lets call it xs
--   compute_returning_expressions #
--     -- we get type of stack [e1, e2, ... ek] ++ xs
--   cleanup_xs_to_inp
--     -- we get [e1, e2, e3, ..., ek] ++ inp
--   
class ReturnableValue' retKind ret => ScopeCodeGen' (retKind :: BranchRetKind) (ret :: Type) -- | Produces an Indigo computation that puts on the stack the evaluated -- returned expressions from the leaving scope. compileScopeReturn' :: ScopeCodeGen' retKind ret => ret -> IndigoState xs (RetOutStack' retKind ret ++ xs) -- | Drop the stack cells that were produced in the leaving scope, apart -- from ones corresponding to the returning expressions. liftClear' :: ScopeCodeGen' retKind ret => (xs :-> inp) -> (RetOutStack' retKind ret ++ xs) :-> (RetOutStack' retKind ret ++ inp) -- | Generate gcClear for the whole statement genGcClear' :: ScopeCodeGen' retKind ret => (RetOutStack' retKind ret ++ inp) :-> inp type ReturnableValue ret = ReturnableValue' (ClassifyReturnValue ret) ret -- | Class for values that can be returned from Indigo statements. They -- include () and tuples. class ReturnableValue' (retKind :: BranchRetKind) (ret :: Type) where { -- | Type family reflecting the top elements of stack produced by a -- statement returning the value. type family RetOutStack' retKind ret :: [Type]; -- | Type family reflecting the returning value from a statement. type family RetVars' retKind ret :: Type; -- | Tuple looking like (Expr x, Expr y, ..) that corresponds to -- expressions returning from the scope. 'RetVars'' and 'RetExprs'' are -- twin types because the former just adds Var over each -- expression of the latter. type family RetExprs' retKind ret :: Type; } -- | Allocate variables referring to result of the statement. Requires an -- allocator operating in a Monad. allocateVars' :: (ReturnableValue' retKind ret, Monad m) => (forall (x :: Type). m (Var x)) -> m (RetVars' retKind ret) -- | Push the variables referring to the result of the statement on top of -- the stack of the given StackVars. assignVars' :: ReturnableValue' retKind ret => RetVars' retKind ret -> StackVars inp -> StackVars (RetOutStack' retKind ret ++ inp) type RetOutStack ret = RetOutStack' (ClassifyReturnValue ret) ret type RetVars ret = RetVars' (ClassifyReturnValue ret) ret type RetExprs ret = RetExprs' (ClassifyReturnValue ret) ret -- | This type family returns a promoted value of type BranchRetKind -- or causes a compilation error if a tuple with too many elements is -- used. type family ClassifyReturnValue (ret :: Type) -- | Specific version of 'liftClear'' liftClear :: forall ret inp xs. ScopeCodeGen ret => (xs :-> inp) -> (RetOutStack ret ++ xs) :-> (RetOutStack ret ++ inp) -- | Concatenate a scoped code, generation of returning expressions, and -- clean up of redundant cells from the stack. compileScope :: forall ret inp xs. ScopeCodeGen ret => DecomposedObjects -> GenCode inp xs -> ret -> inp :-> (RetOutStack ret ++ inp) -- | Specific version of 'allocateVars'' allocateVars :: forall ret m. (ReturnableValue ret, Monad m) => (forall (x :: Type). m (Var x)) -> m (RetVars ret) -- | Push variables in the StackVars, referring to the generated -- expressions, and generate gcClear for the whole statement. finalizeStatement :: forall ret inp. ScopeCodeGen ret => StackVars inp -> RetVars ret -> (inp :-> (RetOutStack ret ++ inp)) -> GenCode inp (RetOutStack ret ++ inp) instance Indigo.Backend.Scope.KnownValueExpr single => Indigo.Backend.Scope.ReturnableValue' 'Indigo.Backend.Scope.SingleVal single instance Indigo.Backend.Scope.KnownValueExpr single => Indigo.Backend.Scope.ScopeCodeGen' 'Indigo.Backend.Scope.SingleVal single instance (Indigo.Backend.Scope.KnownValueExpr x, Indigo.Backend.Scope.KnownValueExpr y) => Indigo.Backend.Scope.ReturnableValue' 'Indigo.Backend.Scope.Tuple (x, y) instance (Indigo.Backend.Scope.KnownValueExpr x, Indigo.Backend.Scope.KnownValueExpr y) => Indigo.Backend.Scope.ScopeCodeGen' 'Indigo.Backend.Scope.Tuple (x, y) instance (Indigo.Backend.Scope.KnownValueExpr x, Indigo.Backend.Scope.KnownValueExpr y, Indigo.Backend.Scope.KnownValueExpr z) => Indigo.Backend.Scope.ReturnableValue' 'Indigo.Backend.Scope.Tuple (x, y, z) instance (Indigo.Backend.Scope.KnownValueExpr x, Indigo.Backend.Scope.KnownValueExpr y, Indigo.Backend.Scope.KnownValueExpr z) => Indigo.Backend.Scope.ScopeCodeGen' 'Indigo.Backend.Scope.Tuple (x, y, z) instance Indigo.Backend.Scope.ScopeCodeGen' 'Indigo.Backend.Scope.Unit () instance Indigo.Backend.Scope.ReturnableValue' 'Indigo.Backend.Scope.Unit () -- | This module implements the ability to put Indigo computations on the -- stack as a lambda and execute them. module Indigo.Backend.Lambda -- | Describes kind of lambda: pure, modifying storage, effectfull data LambdaKind st arg res extra [PureLambda] :: (ExecuteLambdaPure1C arg res, CreateLambda1CGeneric '[] arg res, Typeable res) => LambdaKind st arg res '[] [StorageLambda] :: (ExecuteLambda1C st arg res, CreateLambda1CGeneric '[st] arg res, Typeable res) => Proxy st -> LambdaKind st arg res '[st] [EffLambda] :: (ExecuteLambdaEff1C st arg res, CreateLambda1CGeneric '[st, Ops] arg res, Typeable res) => Proxy st -> LambdaKind st arg res '[st, Ops] -- | Provide common constraints that are presented in all constructors of -- LambdaKind withLambdaKind :: LambdaKind st arg res extra -> ((ScopeCodeGen res, KnownValue arg, Typeable res, CreateLambda1CGeneric extra arg res) => r) -> r -- | Execute lambda depending on its LambdaKind executeLambda1 :: forall res st arg extra inp. LambdaKind st arg res extra -> RefId -> RetVars res -> LambdaExecutor extra arg res inp -- | Create initial stack vars depending on LambdaKind initLambdaStackVars :: LambdaKind st arg res extra -> Var arg -> StackVars (arg & extra) type CreateLambdaPure1C arg res = CreateLambda1CGeneric '[] arg res type ExecuteLambdaPure1C arg res = ExecuteLambda1CGeneric '[] arg res type CreateLambda1C st arg res = (KnownValue st, CreateLambda1CGeneric '[st] arg res) type ExecuteLambda1C st arg res = (IsObject st, HasStorage st, ExecuteLambda1CGeneric '[st] arg res) type CreateLambdaEff1C st arg res = (KnownValue st, CreateLambda1CGeneric '[st, Ops] arg res) type ExecuteLambdaEff1C st arg res = (HasStorage st, HasSideEffects, IsObject st, ExecuteLambda1CGeneric '[st, Ops] arg res) type CreateLambda1CGeneric extra arg res = (ScopeCodeGen res, KnownValue arg, Typeable extra, ZipInstr (arg & extra), KnownValue (ZippedStack (arg : extra)), KnownValue (ZippedStack (RetOutStack res ++ extra)), ZipInstr (RetOutStack res ++ extra), Typeable (RetOutStack res ++ extra)) -- | Create a lambda, that takes only one argument, from the given -- computation, and return a variable referring to this lambda. createLambda1Generic :: forall arg res extra inp. CreateLambda1CGeneric extra arg res => Var (Lambda1Generic extra arg res) -> res -> StackVars (arg & extra) -> SomeIndigoState (arg & extra) -> IndigoState inp (Lambda1Generic extra arg res & inp) type Lambda1Generic extra arg res = (arg & extra) :-> (RetOutStack res ++ extra) -- | Backend conditional statements of Indigo module Indigo.Backend.Conditional -- | If statement. All variables created inside its branches will be -- released after the execution leaves the scope in which they were -- created. if_ :: forall inp a b. IfConstraint a b => Expr Bool -> SomeIndigoState inp -> a -> SomeIndigoState inp -> b -> RetVars a -> IndigoState inp (RetOutStack a ++ inp) -- | If which works like case for Maybe. ifSome :: forall inp x a b. (IfConstraint a b, KnownValue x) => Expr (Maybe x) -> Var x -> SomeIndigoState (x & inp) -> a -> SomeIndigoState inp -> b -> RetVars a -> IndigoState inp (RetOutStack a ++ inp) -- | If which works like case for Either. ifRight :: forall inp r l a b. (IfConstraint a b, KnownValue r, KnownValue l) => Expr (Either l r) -> Var r -> SomeIndigoState (r & inp) -> a -> Var l -> SomeIndigoState (l & inp) -> b -> RetVars a -> IndigoState inp (RetOutStack a ++ inp) -- | If which works like uncons for lists. ifCons :: forall inp x a b. (IfConstraint a b, KnownValue x) => Expr (List x) -> Var x -> Var (List x) -> SomeIndigoState (x & (List x & inp)) -> a -> SomeIndigoState inp -> b -> RetVars a -> IndigoState inp (RetOutStack a ++ inp) type IfConstraint a b = (ScopeCodeGen a, ScopeCodeGen b, CompareBranchesResults (RetExprs a) (RetExprs b), RetVars a ~ RetVars b, RetOutStack a ~ RetOutStack b) -- | Backend machinery for cases. module Indigo.Backend.Case -- | A case statement for indigo. See examples for a sample usage. caseRec :: forall dt inp ret clauses. CaseCommon dt ret clauses => Expr dt -> clauses -> RetVars ret -> IndigoState inp (RetOutStack ret ++ inp) -- | case_ for pattern-matching on parameter. entryCaseRec :: forall dt entrypointKind inp ret clauses. (CaseCommon dt ret clauses, DocumentEntrypoints entrypointKind dt) => Proxy entrypointKind -> Expr dt -> clauses -> RetVars ret -> IndigoState inp (RetOutStack ret ++ inp) -- | entryCase_ for contracts with flat parameter. entryCaseSimpleRec :: forall dt inp ret clauses. (CaseCommon dt ret clauses, DocumentEntrypoints PlainEntrypointsKind dt, NiceParameterFull dt, RequireFlatParamEps dt) => Expr dt -> clauses -> RetVars ret -> IndigoState inp (RetOutStack ret ++ inp) -- | This type is analogous to the CaseClauseL type but instead of -- wrapping a Lorentz instruction, this wraps an Indigo value with the -- same input/output types. data IndigoCaseClauseL ret (param :: CaseClauseParam) data IndigoClause x ret [IndigoClause] :: (KnownValue x, ScopeCodeGen retBr, ret ~ RetExprs retBr, RetOutStack ret ~ RetOutStack retBr) => Var x -> (forall inp. SomeIndigoState (x : inp)) -> retBr -> IndigoClause x ret -- | This constraint is shared by all case* functions. Including -- some outside this module. type CaseCommonF f dt ret clauses = (InstrCaseC dt, RMap (CaseClauses dt), clauses ~ Rec (f ret) (CaseClauses dt), ScopeCodeGen ret) instance (name GHC.Types.~ GHC.TypeLits.AppendSymbol "c" ctor, Lorentz.Constraints.Scopes.KnownValue x) => Lorentz.ADT.CaseArrow name (Indigo.Backend.Case.IndigoClause x ret) (Indigo.Backend.Case.IndigoCaseClauseL ret ('Michelson.Typed.Haskell.Instr.Sum.CaseClauseParam ctor ('Michelson.Typed.Haskell.Instr.Sum.OneField x))) -- | Strictly typed statements of Indigo language. module Indigo.Backend -- | For statements to iterate over a container. forEach :: (IterOpHs a, KnownValue (IterOpElHs a)) => Expr a -> Var (IterOpElHs a) -> SomeIndigoState (IterOpElHs a & inp) -> IndigoState inp inp -- | While statement. while :: Expr Bool -> SomeIndigoState inp -> IndigoState inp inp -- | While-left statement. Repeats a block of code as long as the control -- Either is Left, returns when it is Right. whileLeft :: (KnownValue l, KnownValue r) => Expr (Either l r) -> Var l -> SomeIndigoState (l & inp) -> Var r -> IndigoState inp (r & inp) selfCalling :: forall p inp mname. (NiceParameterFull p, KnownValue (GetEntrypointArgCustom p mname)) => EntrypointRef mname -> Var (ContractRef (GetEntrypointArgCustom p mname)) -> IndigoState inp (ContractRef (GetEntrypointArgCustom p mname) & inp) contractCalling :: forall cp inp epRef epArg addr. (HasEntrypointArg cp epRef epArg, ToTAddress cp addr, ToT addr ~ ToT Address, KnownValue epArg) => epRef -> Expr addr -> Var (Maybe (ContractRef epArg)) -> IndigoState inp (Maybe (ContractRef epArg) & inp) -- | Put a document item. doc :: DocItem di => di -> IndigoState s s -- | Group documentation built in the given piece of code into a block -- dedicated to one thing, e.g. to one entrypoint. docGroup :: DocGrouping -> SomeIndigoState i -> SomeIndigoState i -- | Insert documentation of the contract storage type. The type should be -- passed using type applications. docStorage :: forall storage s. TypeHasDoc storage => IndigoState s s -- | Give a name to the given contract. Apply it to the whole contract -- code. contractName :: Text -> SomeIndigoState i -> SomeIndigoState i -- | Indigo version for the function of the same name from Lorentz. finalizeParamCallingDoc :: (NiceParameterFull cp, RequireSumType cp, HasCallStack) => Var cp -> SomeIndigoState (cp & inp) -> Expr cp -> SomeIndigoState inp -- | Attach general info to the given contract. contractGeneral :: SomeIndigoState i -> SomeIndigoState i -- | Attach default general info to the contract documentation. contractGeneralDefault :: IndigoState s s transferTokens :: (NiceParameter p, HasSideEffects) => Expr p -> Expr Mutez -> Expr (ContractRef p) -> IndigoState inp inp setDelegate :: HasSideEffects => Expr (Maybe KeyHash) -> IndigoState inp inp createContract :: (HasSideEffects, NiceStorage s, NiceParameterFull p) => Contract p s -> Expr (Maybe KeyHash) -> Expr Mutez -> Expr s -> Var Address -> IndigoState inp (Address & inp) -- | Takes an arbitrary IndigoM and wraps it into an -- IndigoFunction producing a local scope for its execution. -- Once it executed, all non-returned variables are cleaned up so that -- the stack has only returned variables at the top. This also can be -- interpreted as if True then f else nop. -- -- Note, that by default we do not define scope inside indigo functions, -- meaning that once we want to create a new variable or return it from a -- function we need to do it inside scope $ instr construction, -- for example: -- --
--   f :: IndigoFunction s Natural
--   f = scope $ do
--     *[s]*
--     res <- newVar (0 :: Natural)
--     *[Natural, s]*
--     scope $ do
--       _n <- newVar (1 :: Integer)
--       *[Integer, Natural, s]
--       res += 4
--     *[Natural, s]*
--     return res
--     *[s]*
--   
scope :: forall ret inp. ScopeCodeGen ret => SomeIndigoState inp -> ret -> RetVars ret -> IndigoState inp (RetOutStack ret ++ inp) -- | Add a comment comment :: CommentType -> IndigoState i i -- | StatementF functor datatype for Freer monad module Indigo.Frontend.Statement -- | StatementF functor for Freer monad. -- -- The constructors correspond to every Indigo statement that has -- expressions (Expr x) in its signature. -- -- The ones that don't take expressions are compiled directly to -- IndigoState (and kept in LiftIndigoState), because they -- won't be taken into consideration by an optimizer anyway. -- -- One more detail about StatementF is that it takes a -- cont type parameter, which is basically IndigoM -- (freer monad), to avoid cyclic dependencies. cont is needed -- to support statements which have recursive structure (like: -- if, while, case, etc). data StatementF (freer :: Type -> Type) a -- | Direct injection of IndigoState of statements which are not going to -- be analyzed by optimizer. [LiftIndigoState] :: (forall inp. SomeIndigoState inp) -> StatementF freer () [NewVar] :: KnownValue x => Expr x -> StatementF freer (Var x) [SetVar] :: KnownValue x => Var x -> Expr x -> StatementF freer () [VarModification] :: (IsObject x, KnownValue y) => ([y, x] :-> '[x]) -> Var x -> Expr y -> StatementF freer () [SetField] :: (IsObject dt, IsObject ftype, HasField dt fname ftype) => Var dt -> Label fname -> Expr ftype -> StatementF cont () [LambdaCall1] :: LambdaKind st arg res extra -> String -> (Var arg -> freer res) -> Expr arg -> StatementF freer (RetVars res) [Scope] :: ScopeCodeGen a => freer a -> StatementF freer (RetVars a) [If] :: IfConstraint a b => Expr Bool -> freer a -> freer b -> StatementF freer (RetVars a) [IfSome] :: (IfConstraint a b, KnownValue x) => Expr (Maybe x) -> (Var x -> freer a) -> freer b -> StatementF freer (RetVars a) [IfRight] :: (IfConstraint a b, KnownValue x, KnownValue y) => Expr (Either y x) -> (Var x -> freer a) -> (Var y -> freer b) -> StatementF freer (RetVars a) [IfCons] :: (IfConstraint a b, KnownValue x) => Expr (List x) -> (Var x -> Var (List x) -> freer a) -> freer b -> StatementF freer (RetVars a) [Case] :: CaseCommonF (IndigoMCaseClauseL freer) dt ret clauses => Expr dt -> clauses -> StatementF freer (RetVars ret) [EntryCase] :: (CaseCommonF (IndigoMCaseClauseL freer) dt ret clauses, DocumentEntrypoints entrypointKind dt) => Proxy entrypointKind -> Expr dt -> clauses -> StatementF freer (RetVars ret) [EntryCaseSimple] :: (CaseCommonF (IndigoMCaseClauseL freer) cp ret clauses, DocumentEntrypoints PlainEntrypointsKind cp, NiceParameterFull cp, RequireFlatParamEps cp) => Expr cp -> clauses -> StatementF freer (RetVars ret) [While] :: Expr Bool -> freer () -> StatementF freer () [WhileLeft] :: (KnownValue x, KnownValue y) => Expr (Either y x) -> (Var y -> freer ()) -> StatementF freer (Var x) [ForEach] :: (IterOpHs a, KnownValue (IterOpElHs a)) => Expr a -> (Var (IterOpElHs a) -> freer ()) -> StatementF freer () [ContractName] :: Text -> freer () -> StatementF freer () [DocGroup] :: DocGrouping -> freer () -> StatementF freer () [ContractGeneral] :: freer () -> StatementF freer () [FinalizeParamCallingDoc] :: (NiceParameterFull cp, RequireSumType cp, HasCallStack) => (Var cp -> freer ()) -> Expr cp -> StatementF freer () [TransferTokens] :: (NiceParameter p, HasSideEffects) => Expr p -> Expr Mutez -> Expr (ContractRef p) -> StatementF freer () [SetDelegate] :: HasSideEffects => Expr (Maybe KeyHash) -> StatementF freer () [CreateContract] :: (IsObject st, NiceStorage st, NiceParameterFull param, HasSideEffects) => Contract param st -> Expr (Maybe KeyHash) -> Expr Mutez -> Expr st -> StatementF freer (Var Address) [SelfCalling] :: (NiceParameterFull p, KnownValue (GetEntrypointArgCustom p mname)) => Proxy p -> EntrypointRef mname -> StatementF freer (Var (ContractRef (GetEntrypointArgCustom p mname))) [ContractCalling] :: (HasEntrypointArg cp epRef epArg, ToTAddress cp addr, ToT addr ~ ToT Address, KnownValue epArg) => Proxy cp -> epRef -> Expr addr -> StatementF freer (Var (Maybe (ContractRef epArg))) [Fail] :: ReturnableValue ret => Proxy ret -> (forall inp. SomeIndigoState inp) -> StatementF freer (RetVars ret) [FailOver] :: ReturnableValue ret => Proxy ret -> (forall inp. Expr a -> SomeIndigoState inp) -> Expr a -> StatementF freer (RetVars ret) type IfConstraint a b = (ScopeCodeGen a, ScopeCodeGen b, CompareBranchesResults (RetExprs a) (RetExprs b), RetVars a ~ RetVars b, RetOutStack a ~ RetOutStack b) -- | Analogous datatype as IndigoCaseClauseL from Indigo.Backend.Case data IndigoMCaseClauseL freer ret (param :: CaseClauseParam) [OneFieldIndigoMCaseClauseL] :: (name ~ AppendSymbol "c" ctor, KnownValue x, ScopeCodeGen retBr, ret ~ RetExprs retBr, RetOutStack ret ~ RetOutStack retBr) => Label name -> (Var x -> freer retBr) -> IndigoMCaseClauseL freer ret ('CaseClauseParam ctor ('OneField x)) -- | Describes kind of lambda: pure, modifying storage, effectfull data LambdaKind st arg res extra [PureLambda] :: (ExecuteLambdaPure1C arg res, CreateLambda1CGeneric '[] arg res, Typeable res) => LambdaKind st arg res '[] [StorageLambda] :: (ExecuteLambda1C st arg res, CreateLambda1CGeneric '[st] arg res, Typeable res) => Proxy st -> LambdaKind st arg res '[st] [EffLambda] :: (ExecuteLambdaEff1C st arg res, CreateLambda1CGeneric '[st, Ops] arg res, Typeable res) => Proxy st -> LambdaKind st arg res '[st, Ops] -- | Provide common constraints that are presented in all constructors of -- LambdaKind withLambdaKind :: LambdaKind st arg res extra -> ((ScopeCodeGen res, KnownValue arg, Typeable res, CreateLambda1CGeneric extra arg res) => r) -> r module Indigo.Frontend.Program -- | Monad for writing your contracts in. newtype IndigoM a IndigoM :: Program (StatementF IndigoM) a -> IndigoM a [unIndigoM] :: IndigoM a -> Program (StatementF IndigoM) a -- | This is freer monad (in other words operational monad). -- -- It preserves the structure of the computation performed over it, -- including return and bind operations. This was -- introduced to be able to iterate over Indigo code and optimize/analyze -- it. -- -- You can read a clearer description of this construction in "The Book -- of Monads" by Alejandro Serrano. There is a chapter about free monads, -- specifically about Freer you can read at page 259. There is -- "operational" package which contains transformer of this monad and -- auxiliary functions but it's not used because we are using only some -- basics of it. data Program instr a [Done] :: a -> Program instr a [Instr] :: instr a -> Program instr a [Bind] :: Program instr a -> (a -> Program instr b) -> Program instr b -- | Traverse over Freer structure and interpret it interpretProgram :: Monad m => (forall x. instr x -> m x) -> Program instr a -> m a -- | Type of a contract that can be compiled to Lorentz with -- compileIndigoContract. type IndigoContract param st = (HasStorage st, HasSideEffects) => Var param -> IndigoM () instance GHC.Base.Monad Indigo.Frontend.Program.IndigoM instance GHC.Base.Applicative Indigo.Frontend.Program.IndigoM instance GHC.Base.Functor Indigo.Frontend.Program.IndigoM instance GHC.Base.Functor (Indigo.Frontend.Program.Program instr) instance GHC.Base.Applicative (Indigo.Frontend.Program.Program instr) instance GHC.Base.Monad (Indigo.Frontend.Program.Program instr) -- | Instruction datatype and its compilations. -- -- The idea behind this module is to provide an intermediate -- representation that can: -- -- -- -- This is meant to be the common ground for modular optimizations on the -- code before this is handed off to the backend and eventually -- translated to Michelson. module Indigo.Compilation.Sequential -- | Simple synonym for a list of Instruction type Block = [Instruction] -- | Data type representing an instruction. -- -- Differently from the frontend this is not used to build a Monad of -- some kind, it is instead based on having as argument the variable to -- associate with the resulting value (if any). -- -- This is combined in simple lists, named Block, and it is -- intended to be easily altered, this is because these are used as the -- intermediate representation between the frontend and the backend, -- where optimizations can occur. data Instruction [LiftIndigoState] :: (forall inp. SomeIndigoState inp) -> Instruction [AssignVar] :: KnownValue x => Var x -> Expr x -> Instruction [SetVar] :: KnownValue x => Var x -> Expr x -> Instruction [VarModification] :: (IsObject x, KnownValue y) => ([y, x] :-> '[x]) -> Var x -> Expr y -> Instruction [SetField] :: (HasField store fname ftype, IsObject store, IsObject ftype) => Var store -> Label fname -> Expr ftype -> Instruction [LambdaCall1] :: LambdaKind st arg ret extra -> String -> Expr arg -> Var arg -> Block -> ret -> RetVars ret -> Instruction [CreateLambda1] :: CreateLambda1CGeneric extra arg ret => StackVars (arg & extra) -> Var arg -> Block -> ret -> Var (Lambda1Generic extra arg ret) -> Instruction [ExecLambda1] :: LambdaKind st arg ret extra -> Proxy ret -> Expr arg -> Var (Lambda1Generic extra arg ret) -> RetVars ret -> Instruction [Scope] :: ScopeCodeGen ret => Block -> ret -> RetVars ret -> Instruction [If] :: IfConstraint a b => Expr Bool -> Block -> a -> Block -> b -> RetVars a -> Instruction [IfSome] :: (IfConstraint a b, KnownValue x) => Expr (Maybe x) -> Var x -> Block -> a -> Block -> b -> RetVars a -> Instruction [IfRight] :: (IfConstraint a b, KnownValue r, KnownValue l) => Expr (Either l r) -> Var r -> Block -> a -> Var l -> Block -> b -> RetVars a -> Instruction [IfCons] :: (IfConstraint a b, KnownValue x) => Expr (List x) -> Var x -> Var (List x) -> Block -> a -> Block -> b -> RetVars a -> Instruction [Case] :: CaseCommon dt ret clauses => Expr dt -> clauses -> RetVars ret -> Instruction [EntryCase] :: (CaseCommon dt ret clauses, DocumentEntrypoints entryPointKind dt) => Proxy entryPointKind -> Expr dt -> clauses -> RetVars ret -> Instruction [EntryCaseSimple] :: (CaseCommon dt ret clauses, DocumentEntrypoints PlainEntrypointsKind dt, NiceParameterFull dt, RequireFlatParamEps dt) => Expr dt -> clauses -> RetVars ret -> Instruction [While] :: Expr Bool -> Block -> Instruction [WhileLeft] :: (KnownValue l, KnownValue r) => Expr (Either l r) -> Var l -> Block -> Var r -> Instruction [ForEach] :: (IterOpHs a, KnownValue (IterOpElHs a)) => Expr a -> Var (IterOpElHs a) -> Block -> Instruction [ContractName] :: Text -> Block -> Instruction [DocGroup] :: DocGrouping -> Block -> Instruction [ContractGeneral] :: Block -> Instruction [FinalizeParamCallingDoc] :: (NiceParameterFull cp, RequireSumType cp) => Var cp -> Block -> Expr cp -> Instruction [TransferTokens] :: (NiceParameter p, HasSideEffects) => Expr p -> Expr Mutez -> Expr (ContractRef p) -> Instruction [SetDelegate] :: HasSideEffects => Expr (Maybe KeyHash) -> Instruction [CreateContract] :: (HasSideEffects, NiceStorage s, NiceParameterFull p) => Contract p s -> Expr (Maybe KeyHash) -> Expr Mutez -> Expr s -> Var Address -> Instruction [SelfCalling] :: (NiceParameterFull p, KnownValue (GetEntrypointArgCustom p mname)) => Proxy p -> EntrypointRef mname -> Var (ContractRef (GetEntrypointArgCustom p mname)) -> Instruction [ContractCalling] :: (HasEntrypointArg cp epRef epArg, ToTAddress cp addr, ToT addr ~ ToT Address, KnownValue epArg) => Proxy cp -> epRef -> Expr addr -> Var (Maybe (ContractRef epArg)) -> Instruction [Fail] :: (forall inp. SomeIndigoState inp) -> Instruction [FailOver] :: (forall inp. Expr a -> SomeIndigoState inp) -> Expr a -> Instruction -- | Analogous datatype as IndigoCaseClauseL and -- IndigoMCaseClauseL. data IndigoSeqCaseClause ret (param :: CaseClauseParam) [OneFieldIndigoSeqCaseClause] :: AppendSymbol "c" ctor ~ name => Label name -> CaseBranch x ret -> IndigoSeqCaseClause ret ('CaseClauseParam ctor ('OneField x)) -- | Representation of a branch of a generic case-like Instruction. data CaseBranch x ret [CaseBranch] :: (KnownValue x, ScopeCodeGen retBr, ret ~ RetExprs retBr, RetOutStack ret ~ RetOutStack retBr) => Var x -> Block -> retBr -> CaseBranch x ret -- | Transformation from IndigoM to a Block of -- Instructions. -- -- Requires the first non-used RefId and returns the next one. indigoMtoSequential :: RefId -> IndigoM a -> (Block, RefId) -- | Translation from a Block and an initial MetaData to -- Lorentz. sequentialToLorentz :: MetaData inp -> (Block, RefId) -> inp :-> inp -- | Applies the given Block to Block transformation to the -- inner code block of every case clause. updateClauses :: (Block -> Block) -> Rec (IndigoSeqCaseClause ret) dt -> Rec (IndigoSeqCaseClause ret) dt -- | Applies the given monadic function giving it the inner code block of -- each case clause, in order. mapMClauses :: Monad m => (Block -> m ()) -> Rec (IndigoSeqCaseClause ret) dt -> m () module Indigo.Compilation.Lambda -- | Collects named lambdas that are used more than once and separates them -- into a lambda creation and multiple lambda executions. Leaves the -- remaining lambdas untouched, to be compiled inline. compileLambdas :: (Block, RefId) -> (Block, RefId) instance GHC.Classes.Eq Indigo.Compilation.Lambda.Lambda1Def instance GHC.Classes.Ord Indigo.Compilation.Lambda.Lambda1Def module Indigo.Compilation.Field optimizeFields :: (Block, RefId) -> (Block, RefId) module Indigo.Compilation.Params -- | Type of a function with n Var arguments and -- IndigoM a result. -- -- Note that the arguments are the first n elements of the -- inp stack in inverse order, for example: IndigoWithParams -- 2 [a, b, c] x is the same as: Var b -> Var a -> IndigoM -- x type IndigoWithParams n inp a = IndigoWithPeanoParams (ToPeano n) inp a -- | Typeable and stack size constraints for the parameters of an -- IndigoWithParams and for converting to a Peano type AreIndigoParams n stk = (AreIndigoPeanoParams (ToPeano n) stk, SingI (ToPeano n)) -- | Converts an IndigoWithParams to its form without input -- Vars, alongside the StackVars to use it with and the -- first available (unassingned) RefId. fromIndigoWithParams :: forall n a inp. (AreIndigoParams n inp, KnownValue a, Default (StackVars inp)) => IndigoWithParams n inp a -> (IndigoM a, StackVars inp, RefId) -- | Converts an IndigoContract to the equivalent IndigoM -- with the storage, parameter and ops list as arguments. contractToIndigoWithParams :: forall param st. KnownValue st => IndigoContract param st -> IndigoWithParams 3 '[param, st, Ops] () -- | This module contains the high-level compilation of Indigo to Lorentz, -- including plain Indigo code, as well as Indigo contracts. module Indigo.Compilation -- | Specialiasation of compileIndigoImpl without var -- decompositions. compileIndigo :: forall n inp a. (AreIndigoParams n inp, KnownValue a, Default (StackVars inp)) => IndigoWithParams n inp a -> inp :-> inp -- | Compile Indigo code to Lorentz contract. Drop elements from the stack -- to return only [Operation] and storage. compileIndigoContract :: forall param st. (KnownValue param, IsObject st) => IndigoContract param st -> ContractCode param st -- | Frontend statements's functions of the Indigo Language. module Indigo.Frontend.Language -- | Create a new variable with the result of the given expression as its -- initial value. new :: IsExpr ex x => ex -> IndigoM (Var x) -- | Set the given variable to the result of the given expression. setVar :: IsExpr ex x => Var x -> ex -> IndigoM () setField :: (ex :~> ftype, IsObject dt, IsObject ftype, HasField dt fname ftype) => Var dt -> Label fname -> ex -> IndigoM () (+=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Add n m, ArithResHs Add n m ~ m) => Var m -> ex1 -> IndigoM () (-=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Sub n m, ArithResHs Sub n m ~ m) => Var m -> ex1 -> IndigoM () (*=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Mul n m, ArithResHs Mul n m ~ m) => Var m -> ex1 -> IndigoM () (<<<=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Lsl n m, ArithResHs Lsl n m ~ m) => Var m -> ex1 -> IndigoM () (>>>=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Lsr n m, ArithResHs Lsr n m ~ m) => Var m -> ex1 -> IndigoM () (&&=) :: (IsExpr ex1 n, IsObject m, ArithOpHs And n m, ArithResHs And n m ~ m) => Var m -> ex1 -> IndigoM () (||=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Or n m, ArithResHs Or n m ~ m) => Var m -> ex1 -> IndigoM () (^=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Xor n m, ArithResHs Xor n m ~ m) => Var m -> ex1 -> IndigoM () (=:) :: IsExpr ex x => Var x -> ex -> IndigoM () infixr 0 =: -- | Get a field from the storage, returns a variable. -- -- Note that the storage type almost always needs to be specified. getStorageField :: forall store ftype fname. (HasStorage store, HasField store fname ftype) => Label fname -> IndigoM (Var ftype) -- | Sets a storage field to a new value. setStorageField :: forall store name ftype ex. (HasStorage store, ex :~> ftype, IsObject store, IsObject ftype, HasField store name ftype) => Label name -> ex -> IndigoM () -- | Updates a storage field by using an updating IndigoM. updateStorageField :: forall store ftype fname fex. (HasStorage store, fex :~> ftype, HasField store fname ftype, IsObject store, IsObject ftype) => Label fname -> (Var ftype -> IndigoM fex) -> IndigoM () if_ :: forall a b ex. (IfConstraint a b, ex :~> Bool) => ex -> IndigoM a -> IndigoM b -> IndigoM (RetVars a) -- | Run the instruction when the condition is met, do nothing otherwise. when :: exc :~> Bool => exc -> IndigoM () -> IndigoM () -- | Reverse of when. unless :: exc :~> Bool => exc -> IndigoM () -> IndigoM () ifSome :: forall x a b ex. (KnownValue x, ex :~> Maybe x, IfConstraint a b) => ex -> (Var x -> IndigoM a) -> IndigoM b -> IndigoM (RetVars a) ifNone :: forall x a b ex. (KnownValue x, ex :~> Maybe x, IfConstraint a b) => ex -> IndigoM b -> (Var x -> IndigoM a) -> IndigoM (RetVars a) -- | Run the instruction when the given expression returns Just a -- value, do nothing otherwise. whenSome :: forall x exa. (KnownValue x, exa :~> Maybe x) => exa -> (Var x -> IndigoM ()) -> IndigoM () -- | Run the instruction when the given expression returns Nothing, -- do nothing otherwise. whenNone :: forall x exa. (KnownValue x, exa :~> Maybe x) => exa -> IndigoM () -> IndigoM () ifRight :: forall x y a b ex. (KnownValue x, KnownValue y, ex :~> Either y x, IfConstraint a b) => ex -> (Var x -> IndigoM a) -> (Var y -> IndigoM b) -> IndigoM (RetVars a) ifLeft :: forall x y a b ex. (KnownValue x, KnownValue y, ex :~> Either y x, IfConstraint a b) => ex -> (Var y -> IndigoM b) -> (Var x -> IndigoM a) -> IndigoM (RetVars a) whenRight :: forall x y ex. (KnownValue x, KnownValue y, ex :~> Either y x) => ex -> (Var x -> IndigoM ()) -> IndigoM () whenLeft :: forall x y ex. (KnownValue x, KnownValue y, ex :~> Either y x) => ex -> (Var y -> IndigoM ()) -> IndigoM () ifCons :: forall x a b ex. (KnownValue x, ex :~> List x, IfConstraint a b) => ex -> (Var x -> Var (List x) -> IndigoM a) -> IndigoM b -> IndigoM (RetVars a) -- | caseRec for tuples. case_ :: forall dt guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) dt ret clauses, RecFromTuple clauses, guard :~> dt) => guard -> IsoRecTuple clauses -> IndigoM (RetVars ret) -- | A case statement for indigo. See examples for a sample usage. caseRec :: forall dt guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) dt ret clauses, guard :~> dt) => guard -> clauses -> IndigoM (RetVars ret) -- | entryCaseRec for tuples. entryCase :: forall dt entrypointKind guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) dt ret clauses, RecFromTuple clauses, DocumentEntrypoints entrypointKind dt, guard :~> dt) => Proxy entrypointKind -> guard -> IsoRecTuple clauses -> IndigoM (RetVars ret) -- | caseRec for pattern-matching on parameter. entryCaseRec :: forall dt entrypointKind guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) dt ret clauses, DocumentEntrypoints entrypointKind dt, guard :~> dt) => Proxy entrypointKind -> guard -> clauses -> IndigoM (RetVars ret) entryCaseSimple :: forall cp guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) cp ret clauses, RecFromTuple clauses, DocumentEntrypoints PlainEntrypointsKind cp, NiceParameterFull cp, RequireFlatParamEps cp, guard :~> cp) => guard -> IsoRecTuple clauses -> IndigoM (RetVars ret) -- | An alias for #= kept only for backward compatibility. -- | Deprecated: use #= instead (//->) :: (name ~ AppendSymbol "c" ctor, KnownValue x, ScopeCodeGen retBr, ret ~ RetExprs retBr, RetOutStack ret ~ RetOutStack retBr) => Label name -> (Var x -> IndigoM retBr) -> IndigoMCaseClauseL IndigoM ret ('CaseClauseParam ctor ('OneField x)) infixr 0 //-> -- | Use this instead of /->. -- -- This operator is like /-> but wraps a body into -- IndigoAnyOut, which is needed for two reasons: to allow -- having any output stack and to allow returning not exactly the same -- values. -- -- It has the added benefit of not being an arrow, so in case the body of -- the clause is a lambda there won't be several. (#=) :: (name ~ AppendSymbol "c" ctor, KnownValue x, ScopeCodeGen retBr, ret ~ RetExprs retBr, RetOutStack ret ~ RetOutStack retBr) => Label name -> (Var x -> IndigoM retBr) -> IndigoMCaseClauseL IndigoM ret ('CaseClauseParam ctor ('OneField x)) infixr 0 #= scope :: forall a. ScopeCodeGen a => IndigoM a -> IndigoFunction a -- | Alias for scope we use in the tutorial. defFunction :: forall a. ScopeCodeGen a => IndigoM a -> IndigoFunction a -- | A more specific version of defFunction meant to more easily -- create IndigoContracts. -- -- Used in the tutorial. The HasSideEffects constraint is -- specified to avoid the warning for redundant constraints. defContract :: (HasSideEffects => IndigoM ()) -> HasSideEffects => IndigoProcedure -- | Like defNamedEffLambda1 but doesn't modify storage and doesn't make -- side effects. defNamedPureLambda1 :: forall argExpr res. (ToExpr argExpr, Typeable res, ExecuteLambdaPure1C (ExprType argExpr) res, CreateLambdaPure1C (ExprType argExpr) res) => String -> (Var (ExprType argExpr) -> IndigoM res) -> argExpr -> IndigoM (RetVars res) -- | Like defNamedEffLambda1 but doesn't make side effects. defNamedLambda1 :: forall st argExpr res. (ToExpr argExpr, Typeable res, ExecuteLambda1C st (ExprType argExpr) res, CreateLambda1C st (ExprType argExpr) res) => String -> (Var (ExprType argExpr) -> IndigoM res) -> argExpr -> IndigoM (RetVars res) -- | Like defNamedLambda1 but doesn't take an argument. defNamedLambda0 :: forall st res. (Typeable res, ExecuteLambda1C st () res, CreateLambda1C st () res) => String -> IndigoM res -> IndigoM (RetVars res) -- | Family of defNamed*LambdaN functions put an Indigo -- computation on the stack to later call it avoiding code duplication. -- defNamed*LambdaN takes a computation with N arguments. This -- family of functions add some overhead to contract byte size for every -- call of the function, therefore, DON'T use defNamed*LambdaN -- if: * Your computation is pretty small. It would be cheaper just to -- inline it, so use defFunction. * Your computation is called -- only once, in this case also use defFunction. -- -- Also, pay attention that defNamed*LambdaN accepts a string -- that is a name of the passed computation. Be careful and make sure -- that all declared computations have different names. Later the name -- will be removed. -- -- Pay attention, that lambda argument will be evaluated to variable -- before lambda calling. -- -- TODO Approach with lambda names has critical pitfall: in case if a -- function takes Label name, lambda body won't be regenerated -- for every different label. So be carefully, this will be fixed in a -- following issue. defNamedEffLambda1 :: forall st argExpr res. (ToExpr argExpr, Typeable res, ExecuteLambdaEff1C st (ExprType argExpr) res, CreateLambdaEff1C st (ExprType argExpr) res) => String -> (Var (ExprType argExpr) -> IndigoM res) -> argExpr -> IndigoM (RetVars res) -- | While statement. while :: forall ex. ex :~> Bool => ex -> IndigoM () -> IndigoM () whileLeft :: forall x y ex. (ex :~> Either y x, KnownValue y, KnownValue x) => ex -> (Var y -> IndigoM ()) -> IndigoM (Var x) -- | For statements to iterate over a container. forEach :: forall a e. (IterOpHs a, KnownValue (IterOpElHs a), e :~> a) => e -> (Var (IterOpElHs a) -> IndigoM ()) -> IndigoM () selfCalling :: forall p mname. (NiceParameterFull p, KnownValue (GetEntrypointArgCustom p mname)) => EntrypointRef mname -> IndigoM (Var (ContractRef (GetEntrypointArgCustom p mname))) contractCalling :: forall cp epRef epArg addr exAddr. (HasEntrypointArg cp epRef epArg, ToTAddress cp addr, ToT addr ~ ToT Address, exAddr :~> addr, KnownValue epArg) => epRef -> exAddr -> IndigoM (Var (Maybe (ContractRef epArg))) -- | Put a document item. doc :: DocItem di => di -> IndigoM () -- | Group documentation built in the given piece of code into a block -- dedicated to one thing, e.g. to one entrypoint. docGroup :: DocGrouping -> IndigoM () -> IndigoM () -- | Insert documentation of the contract's storage type. The type should -- be passed using type applications. docStorage :: forall storage. TypeHasDoc storage => IndigoM () -- | Give a name to the given contract. Apply it to the whole contract -- code. contractName :: Text -> IndigoM () -> IndigoM () -- | Attach general info to the given contract. contractGeneral :: IndigoM () -> IndigoM () -- | Attach default general info to the contract documentation. contractGeneralDefault :: IndigoM () -- | Indigo version for the homonym Lorentz function. finalizeParamCallingDoc :: forall param. (ToExpr param, NiceParameterFull (ExprType param), RequireSumType (ExprType param), HasCallStack) => (Var (ExprType param) -> IndigoM ()) -> param -> IndigoM () -- | Put a DAnchor doc item. anchor :: Text -> IndigoM () -- | Put a DDescription doc item. description :: Markdown -> IndigoM () -- | Put a DEntrypointExample doc item. example :: forall a. NiceParameter a => a -> IndigoM () transferTokens :: (IsExpr exp p, IsExpr exm Mutez, IsExpr exc (ContractRef p), NiceParameter p, HasSideEffects) => exp -> exm -> exc -> IndigoM () setDelegate :: (HasSideEffects, IsExpr ex (Maybe KeyHash)) => ex -> IndigoM () -- | Create contract using default compilation options for Lorentz -- compiler. -- -- See Lorentz.Run. createContract :: (IsObject st, IsExpr exk (Maybe KeyHash), IsExpr exm Mutez, IsExpr exs st, NiceStorage st, NiceParameterFull param, HasSideEffects) => (HasStorage st => Var param -> IndigoM ()) -> exk -> exm -> exs -> IndigoM (Var Address) -- | Create contract from raw Lorentz Contract. createLorentzContract :: (IsObject st, IsExpr exk (Maybe KeyHash), IsExpr exm Mutez, IsExpr exs st, NiceStorage st, NiceParameterFull param, HasSideEffects) => Contract param st -> exk -> exm -> exs -> IndigoM (Var Address) failWith :: forall ret a ex. (IsExpr ex a, ReturnableValue ret) => ex -> IndigoM (RetVars ret) assert :: forall x ex. (IsError x, IsExpr ex Bool) => x -> ex -> IndigoM () failCustom :: forall ret tag err ex. (ReturnableValue ret, err ~ ErrorArg tag, CustomErrorHasDoc tag, NiceConstant err, ex :~> err) => Label tag -> ex -> IndigoM (RetVars ret) failCustom_ :: forall ret tag notVoidErrorMsg. (ReturnableValue ret, RequireNoArgError tag notVoidErrorMsg, CustomErrorHasDoc tag) => Label tag -> IndigoM (RetVars ret) failUnexpected_ :: forall ret. ReturnableValue ret => MText -> IndigoM (RetVars ret) assertCustom :: forall tag err errEx ex. (err ~ ErrorArg tag, CustomErrorHasDoc tag, NiceConstant err, IsExpr errEx err, IsExpr ex Bool) => Label tag -> errEx -> ex -> IndigoM () assertCustom_ :: forall tag notVoidErrorMsg ex. (RequireNoArgError tag notVoidErrorMsg, CustomErrorHasDoc tag, IsExpr ex Bool) => Label tag -> ex -> IndigoM () assertSome :: forall x err ex. (IsError err, KnownValue x, ex :~> Maybe x) => err -> ex -> IndigoM () assertNone :: forall x err ex. (IsError err, KnownValue x, ex :~> Maybe x) => err -> ex -> IndigoM () assertRight :: forall x y err ex. (IsError err, KnownValue x, KnownValue y, ex :~> Either y x) => err -> ex -> IndigoM () assertLeft :: forall x y err ex. (IsError err, KnownValue x, KnownValue y, ex :~> Either y x) => err -> ex -> IndigoM () type ReturnableValue ret = ReturnableValue' (ClassifyReturnValue ret) ret type RetVars ret = RetVars' (ClassifyReturnValue ret) ret -- | Add a comment in a generated Michelson code comment :: CommentType -> IndigoM () -- | Add a comment in a generated Michelson code justComment :: Text -> IndigoM () -- | Add a comment before and after the given Indigo function code. The -- first argument is the name of the function. commentAroundFun :: Text -> IndigoM a -> IndigoM a -- | Add a comment before and after the given Indigo statement code. The -- first argument is the name of the statement. commentAroundStmt :: Text -> IndigoM a -> IndigoM a -- | Utility type for an IndigoM that adds one element to the stack -- and returns a variable pointing at it. type IndigoFunction ret = IndigoM (RetVars ret) -- | Utility type for an IndigoM that does not modify the stack -- (only the values in it) and returns nothing. type IndigoProcedure = IndigoM () type IndigoEntrypoint param = param -> IndigoProcedure liftIndigoState :: (forall inp. SomeIndigoState inp) -> IndigoM () module Indigo.Frontend -- | Module containing pretty-printing of Indigo contracts module Indigo.Print -- | Pretty-print an Indigo contract into Michelson code. printIndigoContract :: forall param st. (IsObject st, NiceParameterFull param, NiceStorage st) => Bool -> IndigoContract param st -> LText -- | Generate an Indigo contract documentation. renderIndigoDoc :: forall param st. (IsObject st, NiceParameterFull param) => IndigoContract param st -> LText -- | Prints the pretty-printed Michelson code of an Indigo contract to the -- standard output. -- -- This is intended to be easy to use for newcomers. printAsMichelson :: forall param st m. (IsObject st, NiceParameterFull param, NiceStorage st, MonadIO m) => IndigoContract param st -> m () -- | Saves the pretty-printed Michelson code of an Indigo contract to the -- given file. -- -- This is intended to be easy to use for newcomers. saveAsMichelson :: forall param st m. (IsObject st, NiceParameterFull param, NiceStorage st, MonadIO m, MonadMask m) => IndigoContract param st -> FilePath -> m () -- | Print the generated documentation to the standard output. printDocumentation :: forall param st m. (IsObject st, NiceParameterFull param, MonadIO m) => IndigoContract param st -> m () -- | Save the generated documentation to the given file. saveDocumentation :: forall param st m. (IsObject st, NiceParameterFull param, MonadIO m, MonadMask m) => IndigoContract param st -> FilePath -> m () -- | Reimplementation of some syntax sugar -- -- You need the following module pragmas to make it work smoothly: -- --
--   {-# LANGUAGE NoApplicativeDo, RebindableSyntax #-}
--   {-# OPTIONS_GHC -Wno-unused-do-bind #-}
--   
module Indigo.Rebinded -- | Defines semantics of if ... then ... else ... construction -- for Indigo where the predicate is a generic exa for which -- IsExpr exa Bool holds ifThenElse :: (IfConstraint a b, IsExpr exa Bool) => exa -> IndigoM a -> IndigoM b -> IndigoM (RetVars a) -- | Defines numerical literals resolution for Indigo. -- -- It is implemented with an additional NumType argument that -- disambiguates the resulting type. This allows, for example, 1 -- int to be resolved to 1 :: Integer. fromInteger :: Integer -> NumType n t -> t -- | Numerical literal disambiguation value for a Natural, see -- fromInteger. nat :: NumType 'Nat Natural -- | Numerical literal disambiguation value for an Integer, see -- fromInteger. int :: NumType 'Int Integer -- | Numerical literal disambiguation value for a Mutez, see -- fromInteger. mutez :: NumType 'Mtz Mutez class IsLabel (x :: Symbol) a fromLabel :: IsLabel x a => a -- | Standard library for Indigo. -- -- As opposed to Expr and Language modules, this module contains quite -- standard things that are not present in vanilla Michelson and are not -- typically found in imperative high level languages. module Indigo.Lib -- | Indigo version of the view macro. It takes a function from -- view argument to view result and a View structure that -- typically comes from a top-level case. view_ :: forall arg r viewExpr exr. (KnownValue arg, NiceParameter r, viewExpr :~> View arg r, exr :~> r, HasSideEffects) => (Expr arg -> IndigoM exr) -> viewExpr -> IndigoM () -- | Indigo version of the void macro. void_ :: forall a b voidExpr exb. (KnownValue a, IsError (VoidResult b), NiceConstant b, voidExpr :~> Void_ a b, exb :~> b) => (Expr a -> IndigoM exb) -> voidExpr -> IndigoM () -- | Flipped version of view_ that is present due to the common -- appearance of flip view parameter $ instr construction. -- -- Semantically we "project" the given parameter inside the body of the -- View construction. project :: forall arg r viewExpr exr. (KnownValue arg, NiceParameter r, viewExpr :~> View arg r, exr :~> r, HasSideEffects) => viewExpr -> (Expr arg -> IndigoM exr) -> IndigoM () -- | Flipped version of void_ that is present due to the common -- appearance of flip void_ parameter $ instr construction. projectVoid :: forall a b voidExpr exb. (KnownValue a, IsError (VoidResult b), NiceConstant b, voidExpr :~> Void_ a b, exb :~> b) => voidExpr -> (Expr a -> IndigoM exb) -> IndigoM () -- | If the first value is greater than the second one, it returns their -- difference. If the values are equal, it returns Nothing. -- Otherwise it fails using the supplied function. subGt0 :: (ex1 :~> Natural, ex2 :~> Natural) => ex1 -> ex2 -> IndigoM () -> IndigoFunction (Maybe Natural) module Indigo -- | 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 infixr 0 `seq` -- | O(n). filter, applied to a predicate and a list, returns -- the list of those elements that satisfy the predicate; i.e., -- --
--   filter p xs = [ x | x <- xs, p x]
--   
-- --
--   >>> filter odd [1, 2, 3]
--   [1,3]
--   
filter :: (a -> Bool) -> [a] -> [a] -- | O(min(m,n)). 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 is capable of list fusion, but it is restricted to its -- first list argument and its resulting list. zip :: [a] -> [b] -> [(a, b)] -- | otherwise is defined as the value True. It helps to make -- guards more readable. eg. -- --
--   f x | x < 0     = ...
--       | otherwise = ...
--   
otherwise :: Bool -- | Application operator. This operator is redundant, since ordinary -- application (f x) means the same as (f $ x). -- However, $ has low, right-associative binding precedence, so it -- sometimes allows parentheses to be omitted; for example: -- --
--   f $ g $ h x  =  f (g (h x))
--   
-- -- It is also useful in higher-order situations, such as map -- ($ 0) xs, or zipWith ($) fs xs. -- -- Note that ($) is levity-polymorphic in its result -- type, so that foo $ True where foo :: Bool -> -- Int# is well-typed. ($) :: forall (r :: RuntimeRep) a (b :: TYPE r). (a -> b) -> a -> b infixr 0 $ -- | 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 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 -- | 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 -- | 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 -- | 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 -- | 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` -- | The Monad class defines the basic operations over a -- monad, a concept from a branch of mathematics known as -- category theory. From the perspective of a Haskell programmer, -- however, it is best to think of a monad as an abstract datatype -- of actions. Haskell's do expressions provide a convenient -- syntax for writing monadic expressions. -- -- Instances of Monad should satisfy the following: -- -- -- -- Furthermore, the Monad and Applicative operations should -- relate as follows: -- -- -- -- The above laws imply: -- -- -- -- and that pure and (<*>) satisfy the applicative -- functor laws. -- -- The instances of Monad for lists, Maybe and IO -- defined in the Prelude satisfy these laws. class Applicative m => Monad (m :: Type -> Type) -- | Sequentially compose two actions, passing any value produced by the -- first as an argument to the second. (>>=) :: 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 >> -- | A type f is a Functor if it provides a function fmap -- which, given any types a and b lets you apply any -- function from (a -> b) to turn an f a into an -- f b, preserving the structure of f. Furthermore -- f needs to adhere to the following: -- -- -- -- Note, that the second law follows from the free theorem of the type -- fmap and the first law, so you need only check that the former -- condition holds. class Functor (f :: Type -> Type) fmap :: 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 -- | Unary negation. negate :: Num a => a -> a -- | Sign of a number. The functions abs and signum should -- satisfy the law: -- --
--   abs x * signum x == x
--   
-- -- For real numbers, the signum is either -1 (negative), -- 0 (zero) or 1 (positive). signum :: Num a => a -> a -- | The 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 max :: Ord a => a -> a -> a min :: Ord a => a -> a -> a -- | 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) -- | 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. -- --
--   t (pure x) = pure x
--   t (f <*> x) = t f <*> t x
--   
-- -- and the identity functor Identity and composition functors -- Compose are from Data.Functor.Identity and -- Data.Functor.Compose. -- -- (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 following: -- -- class Semigroup 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 -- | The class of monoids (types with an associative binary operation that -- has an identity). Instances should satisfy the following: -- -- -- -- The method names refer to the monoid of lists under concatenation, but -- there are many other instances. -- -- Some types can be viewed as a monoid in more than one way, e.g. both -- addition and multiplication on numbers. In such cases we often define -- newtypes and make those instances of Monoid, e.g. -- Sum and Product. -- -- NOTE: Semigroup is a superclass of Monoid since -- base-4.11.0.0. class Semigroup a => Monoid a -- | Identity of mappend 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 (:%) :: !a -> !a -> 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 -- | A value of type Ptr a represents a pointer to an -- object, or an array of objects, which may be marshalled to or from -- Haskell values of type a. -- -- The type a will often be an instance of class Storable -- which provides the marshalling operations. However this is not -- essential, and you can provide your own operations to access the -- pointer. For example you might write small foreign functions to get or -- set the fields of a C struct. data Ptr a -- | A value of type FunPtr a is a pointer to a function -- callable from foreign code. The type a will normally be a -- foreign type, a function type with zero or more arguments where -- -- -- -- A value of type FunPtr a may be a pointer to a foreign -- function, either returned by another foreign function or imported with -- a a static address import like -- --
--   foreign import ccall "stdlib.h &free"
--     p_free :: FunPtr (Ptr a -> IO ())
--   
-- -- or a pointer to a Haskell function created using a wrapper stub -- declared to produce a FunPtr of the correct type. For example: -- --
--   type Compare = Int -> Int -> Bool
--   foreign import ccall "wrapper"
--     mkCompare :: Compare -> IO (FunPtr Compare)
--   
-- -- Calls to wrapper stubs like mkCompare allocate storage, which -- should be released with freeHaskellFunPtr when no longer -- required. -- -- To convert FunPtr values to corresponding Haskell functions, -- one can define a dynamic stub for the specific foreign type, -- e.g. -- --
--   type IntFunction = CInt -> IO ()
--   foreign import ccall "dynamic"
--     mkFun :: FunPtr IntFunction -> IntFunction
--   
data FunPtr a -- | The Either type represents values with two possibilities: a -- value of type Either a b is either Left -- a or Right b. -- -- The Either type is sometimes used to represent a value which is -- either correct or an error; by convention, the Left constructor -- is used to hold an error value and the Right constructor is -- used to hold a correct value (mnemonic: "right" also means "correct"). -- --

Examples

-- -- The type Either String Int is the type -- of values which can be either a String or an Int. The -- Left constructor can be used only on Strings, and the -- Right constructor can be used only on Ints: -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> s
--   Left "foo"
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> n
--   Right 3
--   
--   >>> :type s
--   s :: Either String Int
--   
--   >>> :type n
--   n :: Either String Int
--   
-- -- The fmap from our Functor instance will ignore -- Left values, but will apply the supplied function to values -- contained in a Right: -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> fmap (*2) s
--   Left "foo"
--   
--   >>> fmap (*2) n
--   Right 6
--   
-- -- The Monad instance for Either allows us to chain -- together multiple actions which may fail, and fail overall if any of -- the individual steps failed. First we'll write a function that can -- either parse an Int from a Char, or fail. -- --
--   >>> import Data.Char ( digitToInt, isDigit )
--   
--   >>> :{
--       let parseEither :: Char -> Either String Int
--           parseEither c
--             | isDigit c = Right (digitToInt c)
--             | otherwise = Left "parse error"
--   
--   >>> :}
--   
-- -- The following should work, since both '1' and '2' -- can be parsed as Ints. -- --
--   >>> :{
--       let parseMultiple :: Either String Int
--           parseMultiple = do
--             x <- parseEither '1'
--             y <- parseEither '2'
--             return (x + y)
--   
--   >>> :}
--   
-- --
--   >>> parseMultiple
--   Right 3
--   
-- -- But the following should fail overall, since the first operation where -- we attempt to parse 'm' as an Int will fail: -- --
--   >>> :{
--       let parseMultiple :: Either String Int
--           parseMultiple = do
--             x <- parseEither 'm'
--             y <- parseEither '2'
--             return (x + y)
--   
--   >>> :}
--   
-- --
--   >>> parseMultiple
--   Left "parse error"
--   
data Either a b Left :: a -> Either a b Right :: b -> Either a b -- | The kind of constraints, like Show a data Constraint -- | 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 :: k) (b :: k) -- | 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 -- | Identity function. -- --
--   id x = x
--   
id :: a -> 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 -- | See examples in Control.Monad.Reader. Note, the partially -- applied function type (->) r is a simple reader monad. See -- the instance declaration below. class Monad m => MonadReader r (m :: Type -> Type) | m -> r -- | Retrieves the monad environment. ask :: MonadReader r m => m r -- | Executes a computation in a modified environment. local :: MonadReader r m => (r -> r) -> m a -> m a -- | Retrieves a function of the current environment. reader :: MonadReader r m => (r -> a) -> m a -- | Minimal definition is either both of get and put or -- just state class Monad m => MonadState s (m :: Type -> Type) | m -> s -- | Replace the state inside the monad. put :: MonadState s m => s -> m () -- | Embed a simple state action into the monad. state :: MonadState s m => (s -> (a, s)) -> m a -- | 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 <$> -- | A String is a list of characters. String constants in Haskell -- are values of type String. type String = [Char] -- | 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 . -- | 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. -- -- The Semigroup operation for Map is union, which -- prefers values from the left operand. If m1 maps a key -- k to a value a1, and m2 maps the same key -- to a different value a2, then their union m1 <> -- m2 maps k to a1. data Map k a -- | A handle managing output to the Haskell program's standard output -- channel. stdout :: Handle -- | 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 monoid on applicative functors. -- -- If defined, some and many should be the least solutions -- of the equations: -- -- class Applicative f => Alternative (f :: Type -> Type) -- | An associative binary operation (<|>) :: Alternative f => f a -> 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 -- | Right-to-left composition of functors. The composition of applicative -- functors is always applicative, but the composition of monads is not -- always a monad. newtype Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) Compose :: f (g a) -> Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) [getCompose] :: Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) -> f (g a) infixr 9 `Compose` infixr 9 `Compose` -- | 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 <$!> -- | Like replicateM, but discards the result. replicateM_ :: Applicative m => Int -> m a -> m () -- | replicateM n act performs the action n times, -- gathering the results. replicateM :: Applicative m => Int -> m a -> m [a] -- | Like foldM, but discards the result. foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m () -- | The foldM function is analogous to foldl, except that -- its result is encapsulated in a monad. Note that foldM works -- from left-to-right over the list arguments. This could be an issue -- where (>>) and the `folded function' are not -- commutative. -- --
--   foldM f a1 [x1, x2, ..., xm]
--   
--   ==
--   
--   do
--     a2 <- f a1 x1
--     a3 <- f a2 x2
--     ...
--     f am xm
--   
-- -- If right-to-left evaluation is required, the input list should be -- reversed. -- -- Note: foldM is the same as foldlM foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | zipWithM_ is the extension of zipWithM which ignores the -- final result. zipWithM_ :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m () -- | The zipWithM function generalizes zipWith to arbitrary -- applicative functors. zipWithM :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m [c] -- | The mapAndUnzipM function maps its first argument over a list, -- returning the result as a pair of lists. This function is mainly used -- with complicated data structures or a state 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] -- | This function may be used as a value for foldMap in a -- Foldable instance. -- --
--   foldMapDefault f ≡ getConst . traverse (Const . f)
--   
foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m -- | This function may be used as a value for fmap in a -- Functor instance, provided that traverse is defined. -- (Using fmapDefault with a Traversable instance defined -- only by sequenceA will result in infinite recursion.) -- --
--   fmapDefault f ≡ runIdentity . traverse (Identity . f)
--   
fmapDefault :: Traversable t => (a -> b) -> t a -> t b -- | The mapAccumR function behaves like a combination of -- fmap and foldr; it applies a function to each element of -- a structure, passing an accumulating parameter from right to left, and -- returning a final value of this accumulator together with the new -- structure. mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) -- | The mapAccumL function behaves like a combination of -- fmap and foldl; it applies a function to each element of -- a structure, passing an accumulating parameter from left to right, and -- returning a final value of this accumulator together with the new -- structure. mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) -- | forM is mapM with its arguments flipped. For a version -- that ignores the results see forM_. forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b) -- | 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 -- | 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 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) Const :: a -> Const a (b :: k) [getConst] :: Const a (b :: k) -> a -- | The least element of a non-empty structure with respect to the given -- comparison function. minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a -- | The largest element of a non-empty structure with respect to the given -- comparison function. maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a -- | Map a function over all the elements of a container and concatenate -- the resulting lists. concatMap :: Foldable t => (a -> [b]) -> t a -> [b] -- | Monadic fold over the elements of a structure, associating to the -- left, i.e. from left to right. foldlM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | Monadic fold over the elements of a structure, associating to the -- right, i.e. from right to left. foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b -- | 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) Alt :: f a -> Alt (f :: k -> Type) (a :: k) [getAlt] :: Alt (f :: k -> Type) (a :: k) -> f a -- | Convert an integer into an unknown type-level natural. someNatVal :: Natural -> SomeNat natVal :: forall (n :: Nat) proxy. KnownNat n => proxy n -> Natural -- | This type represents unknown type-level natural numbers. data SomeNat SomeNat :: 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]] -- | O(n). 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] -- | O(n). The genericLength function is an overloaded -- version of length. In particular, instead of returning an -- Int, it returns any type which is an instance of Num. It -- is, however, less efficient than length. -- --
--   >>> genericLength [1, 2, 3] :: Int
--   3
--   
--   >>> genericLength [1, 2, 3] :: Float
--   3.0
--   
genericLength :: Num i => [a] -> i -- | The 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] -- | O(n). 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] -- | O(min(m,n)). 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 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] -- |
--   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) Proxy :: Proxy (t :: k) -- | 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 integralEnumFromThenTo :: Integral a => a -> a -> a -> [a] integralEnumFromTo :: Integral a => a -> a -> [a] integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a] integralEnumFrom :: (Integral a, Bounded a) => a -> [a] gcdWord' :: Word -> Word -> Word gcdInt' :: Int -> Int -> Int -- | 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 (^^%^^) :: Integral a => Rational -> a -> Rational (^%^) :: Integral a => Rational -> a -> Rational -- | raise a number to an integral power (^^) :: (Fractional a, Integral b) => a -> b -> a infixr 8 ^^ odd :: Integral a => a -> Bool even :: Integral a => a -> Bool numericEnumFromThenTo :: (Ord a, Fractional a) => a -> a -> a -> [a] numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a] numericEnumFromThen :: Fractional a => a -> a -> [a] numericEnumFrom :: Fractional a => a -> [a] -- | Extract the denominator of the ratio in reduced form: the numerator -- and denominator have no common factor and the denominator is positive. denominator :: 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 -- | reduce is a subsidiary function used only in this module. It -- normalises a ratio by dividing both numerator and denominator by their -- greatest common divisor. reduce :: Integral a => a -> a -> Ratio a notANumber :: Rational infinity :: Rational ratioPrec1 :: Int ratioPrec :: Int underflowError :: a overflowError :: a ratioZeroDenominatorError :: a divZeroError :: a boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a] boundedEnumFrom :: (Enum a, Bounded a) => 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]) -- | O(min(m,n)). 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 (+) [1, 2, 3] [4, 5, 6]
--   [5,7,9]
--   
-- -- zipWith is right-lazy: -- --
--   zipWith f [] _|_ = []
--   
-- -- zipWith is capable of list fusion, but it is restricted to its -- first list argument and its resulting list. zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] -- | zip3 takes three lists and returns a list of triples, analogous -- to zip. It is capable of list fusion, but it is restricted to -- its first list argument and its resulting list. zip3 :: [a] -> [b] -> [c] -> [(a, b, c)] -- | 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] -- | O(n). 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] -- | O(n). 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 given Just. -- --

Examples

-- -- Basic usage: -- --
--   >>> maybeToList (Just 7)
--   [7]
--   
-- --
--   >>> maybeToList Nothing
--   []
--   
-- -- One can use maybeToList to avoid pattern matching when combined -- with a function that (safely) works on lists: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> sum $ maybeToList (readMaybe "3")
--   3
--   
--   >>> sum $ maybeToList (readMaybe "")
--   0
--   
maybeToList :: Maybe a -> [a] -- | The 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 -- | 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 <&> -- | 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 -- | flip f takes its (first) two arguments in the reverse -- order of f. -- --
--   >>> flip (++) "hello" "world"
--   "worldhello"
--   
flip :: (a -> b -> c) -> b -> a -> c maxInt :: Int minInt :: Int -- | The fromEnum method restricted to the type Char. ord :: Char -> Int -- | In many situations, the liftM operations can be replaced by -- uses of ap, which promotes function application. -- --
--   return f `ap` x1 `ap` ... `ap` xn
--   
-- -- is equivalent to -- --
--   liftMn f x1 x2 ... xn
--   
ap :: Monad m => m (a -> b) -> m a -> m b -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM5 :: Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM4 :: Monad m => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM3 :: Monad m => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right. For example, -- --
--   liftM2 (+) [0,1] [0,2] = [0,2,1,3]
--   liftM2 (+) (Just 1) Nothing = Nothing
--   
liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r -- | 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 :: e -> SomeException -- | The trivial monad transformer, which maps a monad to an equivalent -- monad. data IdentityT (f :: k -> Type) (a :: k) -- | From a Dict, takes a value in an environment where the instance -- witnessed by the Dict is in scope, and evaluates it. -- -- Essentially a deconstruction of a Dict into its -- continuation-style form. -- -- Can also be used to deconstruct an entailment, a :- b, -- using a context a. -- --
--   withDict :: Dict c -> (c => r) -> r
--   withDict :: a => (a :- c) -> (c => r) -> r
--   
withDict :: HasDict c e => e -> (c => r) -> r -- | 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 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 -> () -- | A class for types with a default value. class Default a -- | The default value for this type. def :: Default a => 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 -- | The parameterizable maybe monad, obtained by composing an arbitrary -- monad with the Maybe monad. -- -- Computations are actions that may produce a value or exit. -- -- The return function yields a computation that produces that -- value, while >>= sequences two subcomputations, exiting -- if either computation does. newtype MaybeT (m :: Type -> Type) a MaybeT :: m (Maybe a) -> MaybeT (m :: Type -> Type) a [runMaybeT] :: MaybeT (m :: Type -> Type) 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 (m :: Type -> Type) a -- | A class for monads in which exceptions may be thrown. -- -- Instances should obey the following law: -- --
--   throwM e >> x = throwM e
--   
-- -- In other words, throwing an exception short-circuits the rest of the -- monadic computation. class Monad m => MonadThrow (m :: Type -> Type) -- | A class for monads which allow exceptions to be caught, in particular -- exceptions which were thrown by throwM. -- -- Instances should obey the following law: -- --
--   catch (throwM e) f = f e
--   
-- -- Note that the ability to catch an exception does not guarantee -- that we can deal with all possible exit points from a computation. -- Some monads, such as continuation-based stacks, allow for more than -- just a success/failure strategy, and therefore catch -- cannot be used by those monads to properly implement a function -- such as finally. For more information, see MonadMask. class MonadThrow m => MonadCatch (m :: Type -> Type) -- | A class for monads which provide for the ability to account for all -- possible exit points from a computation, and to mask asynchronous -- exceptions. Continuation-based monads are invalid instances of this -- class. -- -- Instances should ensure that, in the following code: -- --
--   fg = f `finally` g
--   
-- -- The action g is called regardless of what occurs within -- f, including async exceptions. Some monads allow f -- to abort the computation via other effects than throwing an exception. -- For simplicity, we will consider aborting and throwing an exception to -- be two forms of "throwing an error". -- -- If f and g both throw an error, the error thrown by -- fg depends on which errors we're talking about. In a monad -- transformer stack, the deeper layers override the effects of the inner -- layers; for example, ExceptT e1 (Except e2) a represents a -- value of type Either e2 (Either e1 a), so throwing both an -- e1 and an e2 will result in Left e2. If -- f and g both throw an error from the same layer, -- instances should ensure that the error from g wins. -- -- Effects other than throwing an error are also overriden by the deeper -- layers. For example, StateT s Maybe a represents a value of -- type s -> Maybe (a, s), so if an error thrown from -- f causes this function to return Nothing, any -- changes to the state which f also performed will be erased. -- As a result, g will see the state as it was before -- f. Once g completes, f's error will be -- rethrown, so g' state changes will be erased as well. This is -- the normal interaction between effects in a monad transformer stack. -- -- By contrast, lifted-base's version of finally always -- discards all of g's non-IO effects, and g never sees -- any of f's non-IO effects, regardless of the layer ordering -- and regardless of whether f throws an error. This is not the -- result of interacting effects, but a consequence of -- MonadBaseControl's approach. class MonadCatch m => MonadMask (m :: Type -> Type) -- | Runs an action with asynchronous exceptions disabled. The action is -- provided a method for restoring the async. environment to what it was -- at the mask call. See Control.Exception's mask. mask :: MonadMask m => ((forall a. () => m a -> m a) -> m b) -> m b -- | Like mask, but the masked computation is not interruptible (see -- Control.Exception's uninterruptibleMask. WARNING: Only -- use if you need to mask exceptions around an interruptible operation -- AND you can guarantee the interruptible operation will only block for -- a short period of time. Otherwise you render the program/thread -- unresponsive and/or unkillable. uninterruptibleMask :: MonadMask m => ((forall a. () => m a -> m a) -> m b) -> m b -- | A generalized version of bracket which uses ExitCase to -- distinguish the different exit cases, and returns the values of both -- the use and release actions. In practice, this extra -- information is rarely needed, so it is often more convenient to use -- one of the simpler functions which are defined in terms of this one, -- such as bracket, finally, onError, and -- bracketOnError. -- -- This function exists because in order to thread their effects through -- the execution of bracket, monad transformers need values to be -- threaded from use to release and from -- release to the output value. -- -- NOTE This method was added in version 0.9.0 of this library. -- Previously, implementation of functions like bracket and -- finally in this module were based on the mask and -- uninterruptibleMask functions only, disallowing some classes of -- tranformers from having MonadMask instances (notably -- multi-exit-point transformers like ExceptT). If you are a -- library author, you'll now need to provide an implementation for this -- method. The StateT implementation demonstrates most of the -- subtleties: -- --
--   generalBracket acquire release use = StateT $ s0 -> do
--     ((b, _s2), (c, s3)) <- generalBracket
--       (runStateT acquire s0)
--       ((resource, s1) exitCase -> case exitCase of
--         ExitCaseSuccess (b, s2) -> runStateT (release resource (ExitCaseSuccess b)) s2
--   
--         -- In the two other cases, the base monad overrides use's state
--         -- changes and the state reverts to s1.
--         ExitCaseException e     -> runStateT (release resource (ExitCaseException e)) s1
--         ExitCaseAbort           -> runStateT (release resource ExitCaseAbort) s1
--       )
--       ((resource, s1) -> runStateT (use resource) s1)
--     return ((b, c), s3)
--   
-- -- The StateT s m implementation of generalBracket -- delegates to the m implementation of generalBracket. -- The acquire, use, and release arguments -- given to StateT's implementation produce actions of type -- StateT s m a, StateT s m b, and StateT s m -- c. In order to run those actions in the base monad, we need to -- call runStateT, from which we obtain actions of type m -- (a, s), m (b, s), and m (c, s). Since each -- action produces the next state, it is important to feed the state -- produced by the previous action to the next action. -- -- In the ExitCaseSuccess case, the state starts at s0, -- flows through acquire to become s1, flows through -- use to become s2, and finally flows through -- release to become s3. In the other two cases, -- release does not receive the value s2, so its action -- cannot see the state changes performed by use. This is fine, -- because in those two cases, an error was thrown in the base monad, so -- as per the usual interaction between effects in a monad transformer -- stack, those state changes get reverted. So we start from s1 -- instead. -- -- Finally, the m implementation of generalBracket -- returns the pairs (b, s) and (c, s). For monad -- transformers other than StateT, this will be some other type -- representing the effects and values performed and returned by the -- use and release actions. The effect part of the -- use result, in this case _s2, usually needs to be -- discarded, since those effects have already been incorporated in the -- release action. -- -- The only effect which is intentionally not incorporated in the -- release action is the effect of throwing an error. In that -- case, the error must be re-thrown. One subtlety which is easy to miss -- is that in the case in which use and release both -- throw an error, the error from release should take priority. -- Here is an implementation for ExceptT which demonstrates how -- to do this. -- --
--   generalBracket acquire release use = ExceptT $ do
--     (eb, ec) <- generalBracket
--       (runExceptT acquire)
--       (eresource exitCase -> case eresource of
--         Left e -> return (Left e) -- nothing to release, acquire didn't succeed
--         Right resource -> case exitCase of
--           ExitCaseSuccess (Right b) -> runExceptT (release resource (ExitCaseSuccess b))
--           ExitCaseException e       -> runExceptT (release resource (ExitCaseException e))
--           _                         -> runExceptT (release resource ExitCaseAbort))
--       (either (return . Left) (runExceptT . use))
--     return $ do
--       -- The order in which we perform those two Either effects determines
--       -- which error will win if they are both Lefts. We want the error from
--       -- release to win.
--       c <- ec
--       b <- eb
--       return (b, c)
--   
generalBracket :: MonadMask m => m a -> (a -> ExitCase b -> m c) -> (a -> m b) -> m (b, c) -- | O(n) Convert a lazy Text into a strict Text. toStrict :: Text -> Text -- | A set of values. A set cannot contain duplicate values. data HashSet a -- | A state transformer monad parameterized by: -- -- -- -- The return function leaves the state unchanged, while -- >>= uses the final state of the first computation as -- the initial state of the second. newtype StateT s (m :: Type -> Type) a StateT :: (s -> m (a, s)) -> StateT s (m :: Type -> Type) a [runStateT] :: StateT s (m :: Type -> Type) a -> s -> m (a, s) -- | 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 -- | Boxed vectors, supporting efficient slicing. data Vector 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 -- | Gets specific component of the state, using a projection function -- supplied. gets :: MonadState s m => (s -> a) -> m a -- | s ^.. t returns the list of all values that t gets -- from s. -- -- A Maybe contains either 0 or 1 values: -- --
--   >>> Just 3 ^.. _Just
--   [3]
--   
-- -- Gathering all values in a list of tuples: -- --
--   >>> [(1,2),(3,4)] ^.. each.each
--   [1,2,3,4]
--   
(^..) :: s -> Getting (Endo [a]) s a -> [a] infixl 8 ^.. -- | set is a synonym for (.~). -- -- Setting the 1st component of a pair: -- --
--   set _1 :: x -> (a, b) -> (x, b)
--   set _1 = \x t -> (x, snd t)
--   
-- -- Using it to rewrite (<$): -- --
--   set mapped :: Functor f => a -> f b -> f a
--   set mapped = (<$)
--   
set :: ASetter s t a b -> b -> s -> t -- | (.~) assigns a value to the target. It's the same thing as -- using (%~) with const: -- --
--   l .~ x = l %~ const x
--   
-- -- See set if you want a non-operator synonym. -- -- Here it is used to change 2 fields of a 3-tuple: -- --
--   >>> (0,0,0) & _1 .~ 1 & _3 .~ 3
--   (1,0,3)
--   
(.~) :: ASetter s t a b -> b -> s -> t infixr 4 .~ -- | over is a synonym for (%~). -- -- Getting fmap in a roundabout way: -- --
--   over mapped :: Functor f => (a -> b) -> f a -> f b
--   over mapped = fmap
--   
-- -- Applying a function to both components of a pair: -- --
--   over both :: (a -> b) -> (a, a) -> (b, b)
--   over both = \f t -> (f (fst t), f (snd t))
--   
-- -- Using over _2 as a replacement for -- second: -- --
--   >>> over _2 show (10,20)
--   (10,"20")
--   
over :: ASetter s t a b -> (a -> b) -> s -> t -- | Gives access to the 1st field of a tuple (up to 5-tuples). -- -- Getting the 1st component: -- --
--   >>> (1,2,3,4,5) ^. _1
--   1
--   
-- -- Setting the 1st component: -- --
--   >>> (1,2,3) & _1 .~ 10
--   (10,2,3)
--   
-- -- Note that this lens is lazy, and can set fields even of -- undefined: -- --
--   >>> set _1 10 undefined :: (Int, Int)
--   (10,*** Exception: Prelude.undefined
--   
-- -- This is done to avoid violating a lens law stating that you can get -- back what you put: -- --
--   >>> view _1 . set _1 10 $ (undefined :: (Int, Int))
--   10
--   
-- -- The implementation (for 2-tuples) is: -- --
--   _1 f t = (,) <$> f    (fst t)
--                <*> pure (snd t)
--   
-- -- or, alternatively, -- --
--   _1 f ~(a,b) = (\a' -> (a',b)) <$> f a
--   
-- -- (where ~ means a lazy pattern). -- -- _2, _3, _4, and _5 are also available (see -- below). _1 :: Field1 s t a b => Lens s t a b _2 :: Field2 s t a b => Lens s t a b _3 :: Field3 s t a b => Lens s t a b _4 :: Field4 s t a b => Lens s t a b _5 :: Field5 s t a b => Lens s t a b -- | Lens s t a b is the lowest common denominator of a setter and -- a getter, something that has the power of both; it has a -- Functor constraint, and since both Const and -- Identity are functors, it can be used whenever a getter or a -- setter is needed. -- -- type Lens s t a b = forall (f :: Type -> Type). Functor f => a -> f b -> s -> f t -- | This is a type alias for monomorphic lenses which don't change the -- type of the container (or of the value inside). type Lens' s a = Lens s s a a -- | Traversal s t a b is a generalisation of Lens which -- allows many targets (possibly 0). It's achieved by changing the -- constraint to Applicative instead of Functor – indeed, -- the point of Applicative is that you can combine effects, which -- is just what we need to have many targets. -- -- Ultimately, traversals should follow 2 laws: -- --
--   t pure ≡ pure
--   fmap (t f) . t g ≡ getCompose . t (Compose . fmap f . g)
--   
-- -- The 1st law states that you can't change the shape of the structure or -- do anything funny with elements (traverse elements which aren't in the -- structure, create new elements out of thin air, etc.). The 2nd law -- states that you should be able to fuse 2 identical traversals into -- one. For a more detailed explanation of the laws, see this blog -- post (if you prefer rambling blog posts), or The Essence Of The -- Iterator Pattern (if you prefer papers). -- -- Traversing any value twice is a violation of traversal laws. You can, -- however, traverse values in any order. type Traversal s t a b = forall (f :: Type -> Type). Applicative f => a -> f b -> s -> f t -- | This is a type alias for monomorphic traversals which don't change the -- type of the container (or of the values inside). type Traversal' s a = Traversal s s a a -- | 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 () -- | Retrieves a function of the current environment. asks :: MonadReader r m => (r -> a) -> m a -- | The reader monad transformer, which adds a read-only environment to -- the given monad. -- -- The return function ignores the environment, while -- >>= passes the inherited environment to both -- subcomputations. newtype ReaderT r (m :: Type -> Type) a ReaderT :: (r -> m a) -> ReaderT r (m :: Type -> Type) a [runReaderT] :: ReaderT r (m :: Type -> Type) a -> r -> m a -- | preuse is (^?) (or preview) which implicitly -- operates on the state – it takes the state and applies a traversal (or -- fold) to it to extract the 1st element the traversal points at. -- --
--   preuse l = gets (preview l)
--   
preuse :: MonadState s m => Getting (First a) s a -> m (Maybe a) -- | use is (^.) (or view) which implicitly operates -- on the state; for instance, if your state is a record containing a -- field foo, you can write -- --
--   x <- use foo
--   
-- -- to extract foo from the state. In other words, use is -- the same as gets, but for getters instead of functions. -- -- The implementation of use is straightforward: -- --
--   use l = gets (view l)
--   
-- -- If you need to extract something with a fold or traversal, you need -- preuse. use :: MonadState s m => Getting a s a -> m a -- | preview is a synonym for (^?), generalised for -- MonadReader (just like view, which is a synonym for -- (^.)). -- --
--   >>> preview each [1..5]
--   Just 1
--   
preview :: MonadReader s m => Getting (First a) s a -> m (Maybe a) -- | view is a synonym for (^.), generalised for -- MonadReader (we are able to use it instead of (^.) since -- functions are instances of the MonadReader class): -- --
--   >>> view _1 (1, 2)
--   1
--   
-- -- When you're using Reader for config and your config type has -- lenses generated for it, most of the time you'll be using view -- instead of asks: -- --
--   doSomething :: (MonadReader Config m) => m Int
--   doSomething = do
--     thingy        <- view setting1  -- same as “asks (^. setting1)”
--     anotherThingy <- view setting2
--     ...
--   
view :: MonadReader s m => Getting a s 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 variant of modify in which the computation is strict in the -- new state. modify' :: MonadState s m => (s -> s) -> m () -- | The inverse of ExceptT. runExceptT :: ExceptT e m a -> m (Either e a) -- | Runs a Reader and extracts the final value from it. (The -- inverse of reader.) runReader :: Reader r a -> r -> a -- | 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 -- | A variation of arg for optional arguments. Requires a default -- value to handle the case when the optional argument was omitted: -- --
--   fn (argDef #answer 42 -> ans) = ...
--   
-- -- In case you want to get a value wrapped in Maybe instead, use -- argF or ArgF. argDef :: forall (name :: Symbol) a. Name name -> a -> (name :? a) -> a -- | argF is similar to arg: it unwraps a named parameter -- with the specified name. The difference is that the result of -- argF is inside an arity wrapper, which is Identity for -- normal parameters and Maybe for optional parameters. argF :: forall (name :: Symbol) f a. Name name -> NamedF f a name -> f a -- | arg unwraps a named parameter with the specified name. One way -- to use it is to match on arguments with -XViewPatterns: -- --
--   fn (arg #t -> t) (arg #f -> f) = ...
--   
-- -- This way, the names of parameters can be inferred from the patterns: -- no type signature for fn is required. In case a type -- signature for fn is provided, the parameters must come in the -- same order: -- --
--   fn :: "t" :! Integer -> "f" :! Integer -> ...
--   fn (arg #t -> t) (arg #f -> f) = ... -- ok
--   fn (arg #f -> f) (arg #t -> t) = ... -- does not typecheck
--   
arg :: forall (name :: Symbol) a. Name name -> (name :! a) -> a -- | Infix notation for the type of a named parameter. type (name :: Symbol) :! a = NamedF Identity a name -- | Infix notation for the type of an optional named parameter. type (name :: Symbol) :? a = NamedF Maybe a name -- | Async safe version of bracketOnError bracketOnError :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c -- | Async safe version of finally finally :: MonadMask m => m a -> m b -> m a -- | Async safe version of bracket_ bracket_ :: MonadMask m => m a -> m b -> m c -> m c -- | Async safe version of bracket bracket :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c -- | Async safe version of onException onException :: MonadMask m => m a -> m b -> m a -- | try specialized to catch all synchronous exceptions tryAny :: MonadCatch m => m a -> m (Either SomeException a) -- | Same as upstream try, but will not catch asynchronous -- exceptions try :: (MonadCatch m, Exception e) => m a -> m (Either e a) -- | Flipped version of catchAny handleAny :: MonadCatch m => (SomeException -> m a) -> m a -> m a -- | catch specialized to catch all synchronous exception catchAny :: MonadCatch m => m a -> (SomeException -> m a) -> m a -- | Same as upstream catch, but will not catch asynchronous -- exceptions catch :: (MonadCatch m, Exception e) => m a -> (e -> m a) -> m a -- | Synonym for throw throwM :: (MonadThrow m, Exception e) => e -> m a -- | Strict version of modifyTVar. modifyTVar' :: TVar a -> (a -> a) -> STM () -- | O(c) Convert a strict Text into a lazy Text. fromStrict :: Text -> Text -- | O(n) Joins words using single space characters. unwords :: [Text] -> Text -- | O(n) Joins lines, after appending a terminating newline to -- each. unlines :: [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) Breaks a Text up into a list of words, delimited by -- Chars representing white space. words :: Text -> [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 -- | 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 -- | Replace an invalid input byte with the Unicode replacement character -- U+FFFD. lenientDecode :: OnDecodeError -- | Throw a UnicodeException if decoding fails. strictDecode :: OnDecodeError -- | 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 -- | A handler for a decoding error. type OnDecodeError = OnError Word8 Char -- | An exception type for representing Unicode encoding errors. data UnicodeException -- | Convert a ExceptT computation to MaybeT, discarding the -- value of any exception. exceptToMaybeT :: forall (m :: Type -> Type) e a. Functor m => ExceptT e m a -> MaybeT m a -- | Convert a MaybeT computation to ExceptT, with a default -- exception value. maybeToExceptT :: forall (m :: Type -> Type) e a. Functor m => e -> MaybeT m a -> ExceptT e m a -- | This type class allows to implement variadic composition operator. class SuperComposition a b c | a b -> c -- | Allows to apply function to result of another function with multiple -- arguments. -- --
--   >>> (show ... (+)) 1 2
--   "3"
--   
--   >>> show ... 5
--   "5"
--   
--   >>> (null ... zip5) [1] [2] [3] [] [5]
--   True
--   
-- -- Inspired by -- http://stackoverflow.com/questions/9656797/variadic-compose-function. -- --

Performance

-- -- To check the performance there was done a bunch of benchmarks. -- Benchmarks were made on examples given above and also on the functions -- of many arguments. The results are showing that the operator -- (...) performs as fast as plain applications of the operator -- (.) on almost all the tests, but (...) leads to the -- performance draw-down if ghc fails to inline it. Slow -- behavior was noticed on functions without type specifications. That's -- why keep in mind that providing explicit type declarations for -- functions is very important when using (...). Relying on type -- inference will lead to the situation when all optimizations disappear -- due to very general inferred type. However, functions without type -- specification but with applied INLINE pragma are fast again. (...) :: SuperComposition a b c => a -> b -> c infixl 8 ... -- | Infix application. -- --
--   f :: Either String $ Maybe Int
--   =
--   f :: Either String (Maybe Int)
--   
type (f :: k1 -> k) $ (a :: k1) = f a infixr 2 $ -- | Map several constraints over several variables. -- --
--   f :: Each [Show, Read] [a, b] => a -> b -> String
--   =
--   f :: (Show a, Show b, Read a, Read b) => a -> b -> String
--   
-- -- To specify list with single constraint / variable, don't forget to -- prefix it with ': -- --
--   f :: Each '[Show] [a, b] => a -> b -> String
--   
type family Each (c :: [k -> Constraint]) (as :: [k]) -- | Map several constraints over a single variable. Note, that With a -- b ≡ Each a '[b] -- --
--   a :: With [Show, Read] a => a -> a
--   =
--   a :: (Show a, Read a) => a -> a
--   
type With (a :: [k -> Constraint]) (b :: k) = a <+> b -- | Generalized version of show. show :: forall b a. (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 -- | undefined that leaves a warning in code on every usage. undefined :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => a -- | Version of traceId that leaves a warning. traceId :: Text -> Text -- | Version of traceM that leaves a warning and takes Text. traceM :: Monad m => Text -> m () -- | Version of traceShowM that leaves a warning. traceShowM :: (Show a, Monad m) => a -> m () -- | Version of traceShowId that leaves a warning. Useful to tag -- printed data, for instance: -- --
--   traceShowIdWith ("My data: ", ) (veryLargeExpression)
--   
traceShowIdWith :: Show s => (a -> s) -> a -> a -- | Version of traceId that leaves a warning. Useful to tag printed -- data, for instance: -- --
--   traceIdWith (x -> "My data: " <> show x) (veryLargeExpression)
--   
-- -- This is especially useful with custom formatters: -- --
--   traceIdWith (x -> "My data: " <> pretty x) (veryLargeExpression)
--   
traceIdWith :: (a -> Text) -> a -> a -- | Version of traceShowId that leaves a warning. traceShowId :: Show a => a -> a -- | Version of traceShow that leaves a warning. traceShow :: Show a => a -> b -> b -- | error that takes Text as an argument. error :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => Text -> a -- | Version of trace that leaves a warning and takes Text. trace :: Text -> a -> a -- | Similar to undefined but data type. data Undefined Undefined :: Undefined -- | 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 hPrint hPrint :: (MonadIO m, Show a) => Handle -> a -> m () -- | Lifted version of print. print :: forall a m. (MonadIO m, Show a) => a -> m () -- | Write a string like value to stdout appending a newline -- character. putStrLn :: (Print a, MonadIO m) => a -> m () -- | Write a string like value to stdout/. putStr :: (Print a, MonadIO m) => a -> m () -- | Write a string like value a to a supplied Handle, -- appending a newline character. hPutStrLn :: (Print a, MonadIO m) => Handle -> a -> m () -- | Write a string like value a to a supplied Handle. hPutStr :: (Print a, MonadIO m) => Handle -> a -> m () -- | Support class to overload writing of string like values. class Print a -- | 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] -- | 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 -- | Throws error for Maybe if Nothing is given. Operates -- over MonadError. note :: MonadError e m => e -> Maybe 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 e
--       | Just (_ :: NodeAttackedError) <- fromException e = True
--       | Just DialogUnexpected{} <- fromException e = True
--       | otherwise = False
--   
-- -- you can use Exc pattern synonym: -- --
--   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 :: 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]) -- | Monadic and constrained to Container 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 :: (Container f, Monad m) => (Element f -> m Bool) -> f -> m Bool -- | Monadic and constrained to Container 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 :: (Container f, Monad m) => (Element f -> m Bool) -> f -> m Bool -- | Monadic and constrained to Container version of or. -- --
--   >>> orM [Just True, Just False]
--   Just True
--   
--   >>> orM [Just True, Nothing]
--   Just True
--   
--   >>> orM [Nothing, Just True]
--   Nothing
--   
orM :: (Container f, Element f ~ m Bool, Monad m) => f -> m Bool -- | Monadic and constrained to Container 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 :: (Container f, Element f ~ m Bool, Monad m) => f -> m Bool -- | Like concatMapM, but has its arguments flipped, so can be used -- instead of the common fmap concat $ forM pattern. concatForM :: (Applicative f, Monoid m, Container (l m), Element (l m) ~ m, Traversable l) => l a -> (a -> f m) -> f m -- | Lifting bind into a monad. Generalized version of concatMap -- that works with a monadic predicate. Old and simpler specialized to -- list version had next type: -- --
--   concatMapM :: Monad m => (a -> m [b]) -> [a] -> m [b]
--   
-- -- Side note: previously it had type -- --
--   concatMapM :: (Applicative q, Monad m, Traversable m)
--              => (a -> q (m b)) -> m a -> q (m b)
--   
-- -- Such signature didn't allow to use this function when traversed -- container type and type of returned by function-argument differed. Now -- you can use it like e.g. -- --
--   concatMapM readFile files >>= putTextLn
--   
concatMapM :: (Applicative f, Monoid m, Container (l m), Element (l m) ~ m, Traversable l) => (a -> f m) -> l a -> f m -- | Constrained to Container version of asum. -- --
--   >>> asum [Nothing, Just [False, True], Nothing, Just [True]]
--   Just [False,True]
--   
asum :: (Container t, Alternative f, Element t ~ f a) => t -> f a -- | Constrained to Container version of sequence_. -- --
--   >>> sequence_ [putTextLn "foo", print True]
--   foo
--   True
--   
sequence_ :: (Container t, Monad m, Element t ~ m a) => t -> m () -- | Constrained to Container version of sequenceA_. -- --
--   >>> sequenceA_ [putTextLn "foo", print True]
--   foo
--   True
--   
sequenceA_ :: (Container t, Applicative f, Element t ~ f a) => t -> f () -- | Constrained to Container version of forM_. -- --
--   >>> forM_ [True, False] print
--   True
--   False
--   
forM_ :: (Container t, Monad m) => t -> (Element t -> m b) -> m () -- | Constrained to Container version of mapM_. -- --
--   >>> mapM_ print [True, False]
--   True
--   False
--   
mapM_ :: (Container t, Monad m) => (Element t -> m b) -> t -> m () -- | Constrained to Container version of for_. -- --
--   >>> for_ [1 .. 5 :: Int] $ \i -> when (even i) (print i)
--   2
--   4
--   
for_ :: (Container t, Applicative f) => t -> (Element t -> f b) -> f () -- | Constrained to Container version of traverse_. -- --
--   >>> traverse_ putTextLn ["foo", "bar"]
--   foo
--   bar
--   
traverse_ :: (Container t, Applicative f) => (Element t -> f b) -> t -> f () -- | Stricter version of product. -- --
--   >>> product [1..10]
--   3628800
--   
--   >>> product (Right 3)
--   ...
--       • Do not use 'Foldable' methods on Either
--         Suggestions:
--             Instead of
--                 for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f ()
--             use
--                 whenJust  :: Applicative f => Maybe a    -> (a -> f ()) -> f ()
--                 whenRight :: Applicative f => Either l r -> (r -> f ()) -> f ()
--   ...
--             Instead of
--                 fold :: (Foldable t, Monoid m) => t m -> m
--             use
--                 maybeToMonoid :: Monoid m => Maybe m -> m
--   ...
--   
product :: (Container t, Num (Element t)) => t -> Element t -- | Stricter version of sum. -- --
--   >>> sum [1..10]
--   55
--   
--   >>> sum (Just 3)
--   ...
--       • Do not use 'Foldable' methods on Maybe
--         Suggestions:
--             Instead of
--                 for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f ()
--             use
--                 whenJust  :: Applicative f => Maybe a    -> (a -> f ()) -> f ()
--                 whenRight :: Applicative f => Either l r -> (r -> f ()) -> f ()
--   ...
--             Instead of
--                 fold :: (Foldable t, Monoid m) => t m -> m
--             use
--                 maybeToMonoid :: Monoid m => Maybe m -> m
--   ...
--   
sum :: (Container t, Num (Element t)) => t -> Element t -- | Similar to foldl' but takes a function with its arguments -- flipped. -- --
--   >>> flipfoldl' (/) 5 [2,3] :: Rational
--   15 % 2
--   
flipfoldl' :: (Container t, Element t ~ a) => (a -> b -> b) -> b -> t -> b -- | Type class for data types that can be converted to List of Pairs. You -- can define ToPairs by just defining toPairs function. -- -- But the following laws should be met: -- --
--   toPairs m ≡ zip (keys m) (elems m)
--   keysmap fst . toPairs
--   elemsmap snd . toPairs
--   
class ToPairs t -- | Converts the structure to the list of the key-value pairs. -- >>> toPairs (HashMap.fromList [(a, "xxx"), -- (b, "yyy")]) [(a,"xxx"),(b,"yyy")] toPairs :: ToPairs t => t -> [(Key t, Val t)] -- | Converts the structure to the list of the keys. -- --
--   >>> keys (HashMap.fromList [('a', "xxx"), ('b', "yyy")])
--   "ab"
--   
keys :: ToPairs t => t -> [Key t] -- | Converts the structure to the list of the values. -- --
--   >>> elems (HashMap.fromList [('a', "xxx"), ('b', "yyy")])
--   ["xxx","yyy"]
--   
elems :: ToPairs t => t -> [Val t] -- | Type of element for some container. Implemented as an asscociated type -- family because some containers are monomorphic over element type (like -- Text, IntSet, etc.) so we can't implement nice interface -- using old higher-kinded types approach. Implementing this as an -- associated type family instead of top-level family gives you more -- control over element types. type family Element t -- | Very similar to Foldable but also allows instances for -- monomorphic types like Text but forbids instances for -- Maybe and similar. This class is used as a replacement for -- Foldable type class. It solves the following problems: -- --
    --
  1. length, foldr and other functions work on more types -- for which it makes sense.
  2. --
  3. You can't accidentally use length on polymorphic -- Foldable (like list), replace list with Maybe and then -- debug error for two days.
  4. --
  5. More efficient implementaions of functions for polymorphic types -- (like elem for Set).
  6. --
-- -- The drawbacks: -- --
    --
  1. Type signatures of polymorphic functions look more scary.
  2. --
  3. Orphan instances are involved if you want to use foldr (and -- similar) on types from libraries.
  4. --
class Container t where { -- | Type of element for some container. Implemented as an asscociated type -- family because some containers are monomorphic over element type (like -- Text, IntSet, etc.) so we can't implement nice interface -- using old higher-kinded types approach. Implementing this as an -- associated type family instead of top-level family gives you more -- control over element types. type family Element t; type Element t = ElementDefault t; } -- | Convert container to list of elements. -- --
--   >>> toList @Text "aba"
--   "aba"
--   
--   >>> :t toList @Text "aba"
--   toList @Text "aba" :: [Char]
--   
toList :: Container t => t -> [Element t] -- | Checks whether container is empty. -- --
--   >>> null @Text ""
--   True
--   
--   >>> null @Text "aba"
--   False
--   
null :: Container t => t -> Bool foldr :: Container t => (Element t -> b -> b) -> b -> t -> b foldl :: Container t => (b -> Element t -> b) -> b -> t -> b foldl' :: Container t => (b -> Element t -> b) -> b -> t -> b length :: Container t => t -> Int elem :: Container t => Element t -> t -> Bool maximum :: Container t => t -> Element t minimum :: Container t => t -> Element t foldMap :: (Container t, Monoid m) => (Element t -> m) -> t -> m fold :: Container t => t -> Element t foldr' :: Container t => (Element t -> b -> b) -> b -> t -> b foldr1 :: Container t => (Element t -> Element t -> Element t) -> t -> Element t foldl1 :: Container t => (Element t -> Element t -> Element t) -> t -> Element t notElem :: Container t => Element t -> t -> Bool all :: Container t => (Element t -> Bool) -> t -> Bool any :: Container t => (Element t -> Bool) -> t -> Bool find :: Container t => (Element t -> Bool) -> t -> Maybe (Element t) safeHead :: Container t => t -> Maybe (Element t) type family OneItem x -- | Type class for types that can be created from one element. -- singleton is lone name for this function. Also constructions -- of different type differ: :[] for lists, two arguments for -- Maps. Also some data types are monomorphic. -- --
--   >>> one True :: [Bool]
--   [True]
--   
--   >>> one 'a' :: Text
--   "a"
--   
--   >>> one (3, "hello") :: HashMap Int String
--   fromList [(3,"hello")]
--   
class One x where { type family OneItem x; } -- | Create a list, map, Text, etc from a single element. one :: One x => OneItem x -> x -- | 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 whenRight. whenRightM :: Monad m => m (Either l r) -> (r -> m ()) -> m () -- | Monadic version of whenLeft. whenLeftM :: Monad m => m (Either l r) -> (l -> m ()) -> m () -- | 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 -- | Extracts value from Right or return given default value. -- --
--   >>> fromRight 0 (Left 3)
--   0
--   
--   >>> fromRight 0 (Right 5)
--   5
--   
fromRight :: b -> Either a b -> b -- | Extracts value from Left or return given default value. -- --
--   >>> fromLeft 0 (Left 3)
--   3
--   
--   >>> fromLeft 0 (Right 5)
--   0
--   
fromLeft :: a -> Either a b -> 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 () -- | 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) -- | Opens a file, manipulates it with the provided function and closes the -- handle before returning. The Handle can be written to using the -- hPutStr and hPutStrLn functions. -- -- withFile is essentially the bracket pattern, specialized -- to files. This should be preferred over openFile + -- hClose as it properly deals with (asynchronous) exceptions. In -- cases where withFile is insufficient, for instance because the -- it is not statically known when manipulating the Handle has -- finished, one should consider other safe paradigms for resource usage, -- such as the ResourceT transformer from the resourcet -- package, before resorting to openFile and hClose. withFile :: (MonadIO m, MonadMask m) => FilePath -> IOMode -> (Handle -> m a) -> m a -- | Close a file handle -- -- See also withFile for more information. hClose :: MonadIO m => Handle -> m () -- | Lifted version of openFile. -- -- See also withFile for more information. openFile :: MonadIO m => FilePath -> IOMode -> m Handle -- | 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 a -- | 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 <<$>> -- | map generalized to Functor. -- --
--   >>> map not (Just True)
--   Just False
--   
--   >>> map not [True,False,True,True]
--   [False,True,False,False]
--   
map :: Functor f => (a -> b) -> f a -> f b -- | Stricter version of $ operator. Default Prelude defines this at -- the toplevel module, so we do as well. -- --
--   >>> const 3 $ Prelude.undefined
--   3
--   
--   >>> const 3 $! Prelude.undefined
--   *** Exception: Prelude.undefined
--   ...
--   
($!) :: (a -> b) -> a -> b infixr 0 $! -- | Shorter alias for pure (). -- --
--   >>> pass :: Maybe ()
--   Just ()
--   
pass :: Applicative f => f () -- | A record is parameterized by a universe u, an interpretation -- f and a list of rows rs. The labels or indices of -- the record are given by inhabitants of the kind u; the type -- of values at any label r :: u is given by its interpretation -- f r :: *. data Rec (a :: u -> Type) (b :: [u]) [RNil] :: forall u (a :: u -> Type). Rec a ('[] :: [u]) [:&] :: forall u (a :: u -> Type) (r :: u) (rs :: [u]). !a r -> !Rec a rs -> Rec a (r : rs) infixr 7 :& constructStack :: forall dt (fields :: [Type]) (st :: [Type]). (InstrConstructC dt, ToTs fields ~ ToTs (ConstructorFieldTypes dt), KnownList fields) => (fields ++ st) :-> (dt & st) deconstruct :: forall dt (fields :: [Type]) (st :: [Type]). (InstrDeconstructC dt, KnownList fields, ToTs fields ~ ToTs (ConstructorFieldTypes dt)) => (dt & st) :-> (fields ++ st) fieldCtor :: forall (st :: [Type]) f. HasCallStack => (st :-> (f & st)) -> FieldConstructor st f getField :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt & st) :-> (GetFieldType dt name & (dt : st)) getFieldNamed :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt & st) :-> ((name :! GetFieldType dt name) & (dt : st)) modifyField :: forall dt (name :: Symbol) (st :: [Type]). (InstrGetFieldC dt name, InstrSetFieldC dt name) => Label name -> (forall (st0 :: [Type]). () => (GetFieldType dt name : st0) :-> (GetFieldType dt name : st0)) -> (dt & st) :-> (dt & st) toField :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt & st) :-> (GetFieldType dt name & st) toFieldNamed :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt & st) :-> ((name :! GetFieldType dt name) & st) unwrapUnsafe_ :: forall dt (name :: Symbol) (st :: [Type]). InstrUnwrapC dt name => Label name -> (dt & st) :-> (CtorOnlyField name dt : st) wrapOne :: forall dt (name :: Symbol) (st :: [Type]). InstrWrapOneC dt name => Label name -> (CtorOnlyField name dt : st) :-> (dt & st) wrap_ :: forall dt (name :: Symbol) (st :: [Type]). InstrWrapC dt name => Label name -> AppendCtorField (GetCtorField dt name) st :-> (dt & st) type (n :: Symbol) := ty = 'NamedField n ty class CaseArrow (name :: Symbol) body clause | clause -> name, clause -> body (/->) :: CaseArrow name body clause => Label name -> body -> clause data CaseClauseL (inp :: [Type]) (out :: [Type]) (param :: CaseClauseParam) [CaseClauseL] :: forall (x :: CtorField) (inp :: [Type]) (out :: [Type]) (ctor :: Symbol). (AppendCtorField x inp :-> out) -> CaseClauseL inp out ('CaseClauseParam ctor x) type CaseTC dt (out :: [Type]) (inp :: [Type]) clauses = (InstrCaseC dt, RMap CaseClauses dt, RecFromTuple clauses, clauses ~ Rec CaseClauseL inp out CaseClauses dt) type HasFieldOfType dt (fname :: Symbol) fieldTy = (HasField dt fname, GetFieldType dt fname ~ fieldTy) type family HasFieldsOfType dt (fs :: [NamedField]) data NamedField NamedField :: Symbol -> Type -> NamedField type ConstructorFieldTypes dt = GFieldTypes Rep dt type InstrConstructC dt = (GenericIsoValue dt, GInstrConstruct Rep dt) newtype (inp :: [Type]) :-> (out :: [Type]) LorentzInstr :: RemFail Instr (ToTs inp) (ToTs out) -> (:->) (inp :: [Type]) (out :: [Type]) [unLorentzInstr] :: (:->) (inp :: [Type]) (out :: [Type]) -> RemFail Instr (ToTs inp) (ToTs out) data Label (name :: Symbol) [Label] :: forall (name :: Symbol). KnownSymbol name => Label name type a & (b :: [Type]) = a : b class HasAnnotation a type family ToT a :: T data Address newtype BigMap k v BigMap :: Map k v -> BigMap k v [unBigMap] :: BigMap k v -> Map k v data ChainId data ContractRef arg ContractRef :: Address -> SomeEntrypointCall arg -> ContractRef arg [crAddress] :: ContractRef arg -> Address [crEntrypoint] :: ContractRef arg -> SomeEntrypointCall arg data EpAddress EpAddress :: Address -> EpName -> EpAddress [eaAddress] :: EpAddress -> Address [eaEntrypoint] :: EpAddress -> EpName data KeyHash data MText data Mutez type Operation = Operation' Instr data PublicKey data Signature data Timestamp class (ArithOp aop ToT n ToT m, NiceComparable n, NiceComparable m, ToT ArithResHs aop n m ~ ArithRes aop ToT n ToT m) => ArithOpHs aop n m where { type family ArithResHs aop n m; } type family ArithResHs aop n m class (UnaryArithOp aop ToT n, NiceComparable n, ToT UnaryArithResHs aop n ~ UnaryArithRes aop ToT n) => UnaryArithOpHs aop n where { type family UnaryArithResHs aop n; } type family UnaryArithResHs aop n type NiceComparable n = (KnownValue n, Comparable ToT n) (#) :: forall (a :: [Type]) (b :: [Type]) (c :: [Type]). (a :-> b) -> (b :-> c) -> a :-> c (##) :: forall (a :: [Type]) (b :: [Type]) (c :: [Type]). (a :-> b) -> (b :-> c) -> a :-> c pattern FI :: (forall (out' :: [T]). () => Instr (ToTs inp) out') -> inp :-> out pattern I :: Instr (ToTs inp) (ToTs out) -> inp :-> out iAnyCode :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> Instr (ToTs inp) (ToTs out) iForceNotFail :: forall (i :: [Type]) (o :: [Type]). (i :-> o) -> i :-> o iGenericIf :: forall (a :: [Type]) (b :: [Type]) (c :: [Type]) (s :: [Type]). (forall (s' :: [T]). () => Instr (ToTs a) s' -> Instr (ToTs b) s' -> Instr (ToTs c) s') -> (a :-> s) -> (b :-> s) -> c :-> s iMapAnyCode :: forall (i1 :: [Type]) (i2 :: [Type]) (o :: [Type]). (forall (o' :: [T]). () => Instr (ToTs i1) o' -> Instr (ToTs i2) o') -> (i1 :-> o) -> i2 :-> o iNonFailingCode :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => (inp :-> out) -> Instr (ToTs inp) (ToTs out) iWithVarAnnotations :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => [Text] -> (inp :-> out) -> inp :-> out optimizeLorentz :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> inp :-> out optimizeLorentzWithConf :: forall (inp :: [Type]) (out :: [Type]). OptimizerConf -> (inp :-> out) -> inp :-> out parseLorentzValue :: KnownValue v => Text -> Either ParseLorentzError v transformBytesLorentz :: forall (inp :: [Type]) (out :: [Type]). Bool -> (ByteString -> ByteString) -> (inp :-> out) -> inp :-> out transformStringsLorentz :: forall (inp :: [Type]) (out :: [Type]). Bool -> (MText -> MText) -> (inp :-> out) -> inp :-> out type (%>) = (:->) type ContractCode cp st = '[(cp, st)] :-> ContractOut st type ContractOut st = '[([Operation], st)] type Lambda i o = '[i] :-> '[o] class MapLorentzInstr instr mapLorentzInstr :: MapLorentzInstr instr => (forall (i :: [Type]) (o :: [Type]). () => (i :-> o) -> i :-> o) -> instr -> instr data SomeContractCode [SomeContractCode] :: forall cp st. (NiceParameterFull cp, NiceStorage st) => ContractCode cp st -> SomeContractCode type NiceParameterFull cp = (Typeable cp, ParameterDeclaresEntrypoints cp) type NiceStorage a = (HasAnnotation a, KnownValue a, ProperStorageBetterErrors ToT a) class (IsoValue a, Typeable a) => KnownValue a allowCheckedCoerce :: forall k1 k2 (a :: k1) (b :: k2). Dict (CanCastTo a b, CanCastTo b a) allowCheckedCoerceTo :: forall k1 k2 (b :: k1) (a :: k2). Dict (CanCastTo a b) castDummyG :: (Generic a, Generic b, GCanCastTo (Rep a) (Rep b)) => Proxy a -> Proxy b -> () checkedCoerce :: (CanCastTo a b, Coercible a b) => a -> b checkedCoerce_ :: forall a b (s :: [Type]). Castable_ a b => (a : s) :-> (b : s) checkedCoercing_ :: forall a b (s :: [Type]). Coercible_ a b => ((b : s) :-> (b : s)) -> (a : s) :-> (a : s) coerceUnwrap :: forall a (s :: [Type]). Wrappable a => (a : s) :-> (Unwrappable a : s) coerceWrap :: forall a (s :: [Type]). Wrappable a => (Unwrappable a : s) :-> (a : s) fakeCoerce :: forall (s1 :: [Type]) (s2 :: [Type]). s1 :-> s2 fakeCoercing :: forall (s1 :: [Type]) (s2 :: [Type]) (s1' :: [Type]) (s2' :: [Type]). (s1 :-> s2) -> s1' :-> s2' forcedCoerce_ :: forall a b (s :: [Type]). MichelsonCoercible a b => (a & s) :-> (b & s) fromNamed :: forall (name :: Symbol) a (s :: [Type]). Label name -> (NamedF Identity a name : s) :-> (a : s) gForcedCoerce_ :: forall k t (a :: k) (b :: k) (s :: [Type]). MichelsonCoercible (t a) (t b) => (t a : s) :-> (t b : s) toNamed :: forall (name :: Symbol) a (s :: [Type]). Label name -> (a : s) :-> (NamedF Identity a name : s) class CanCastTo (a :: k) (b :: k1) castDummy :: CanCastTo a b => Proxy a -> Proxy b -> () type Castable_ a b = (MichelsonCoercible a b, CanCastTo a b) type Coercible_ a b = (MichelsonCoercible a b, CanCastTo a b, CanCastTo b a) type MichelsonCoercible a b = ToT a ~ ToT b class ToT s ~ ToT Unwrappable s => Wrappable s where { type family Unwrappable s; type Unwrappable s = GUnwrappable Rep s; } type family Unwrappable s newtype TAddress (p :: k) TAddress :: Address -> TAddress (p :: k) [unTAddress] :: TAddress (p :: k) -> Address newtype FutureContract arg FutureContract :: ContractRef arg -> FutureContract arg [unFutureContract] :: FutureContract arg -> ContractRef arg type Entrypoint param store = '[param, store] :-> ContractOut store type Entrypoint_ store = '[store] :-> ContractOut store niceConstantEvi :: NiceConstant a :- ConstantScope (ToT a) nicePackedValueEvi :: NicePackedValue a :- PackedValScope (ToT a) niceParameterEvi :: NiceParameter a :- ParameterScope (ToT a) nicePrintedValueEvi :: NicePrintedValue a :- PrintedValScope (ToT a) niceStorageEvi :: NiceStorage a :- StorageScope (ToT a) niceUnpackedValueEvi :: NiceUnpackedValue a :- UnpackedValScope (ToT a) class (IsoValue a, HasNoNestedBigMaps ToT a) => CanHaveBigMap a type NiceConstant a = (KnownValue a, ProperConstantBetterErrors ToT a) type NiceFullPackedValue a = (NicePackedValue a, NiceUnpackedValue a) type NicePackedValue a = (KnownValue a, ProperPackedValBetterErrors ToT a) type NiceParameter a = (KnownValue a, ProperParameterBetterErrors ToT a) type NicePrintedValue a = (KnownValue a, ProperPrintedValBetterErrors ToT a) type NiceUnpackedValue a = (KnownValue a, ProperUnpackedValBetterErrors ToT a) class (IsoValue a, ForbidBigMap ToT a) => NoBigMap a class (IsoValue a, ForbidContract ToT a) => NoContractType a class (IsoValue a, ForbidOp ToT a) => NoOperation a buildLorentzDoc :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> ContractDoc buildLorentzDocWithGitRev :: forall (inp :: [Type]) (out :: [Type]). DGitRevision -> (inp :-> out) -> ContractDoc cutLorentzNonDoc :: forall (inp :: [Type]) (out :: [Type]) (s :: [Type]). (inp :-> out) -> s :-> s mkDEntrypointExample :: NiceParameter a => a -> DEntrypointExample renderLorentzDoc :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> LText renderLorentzDocWithGitRev :: forall (inp :: [Type]) (out :: [Type]). DGitRevision -> (inp :-> out) -> LText contractDocToMarkdown :: ContractDoc -> LText docDefinitionRef :: (DocItem d, DocItemPlacement d ~ 'DocItemInDefinitions) => Markdown -> d -> Markdown docItemPosition :: DocItem d => DocItemPos mdTocFromRef :: (DocItem d, DocItemReferenced d ~ 'True) => HeaderLevel -> Markdown -> d -> Markdown mkDGitRevision :: ExpQ morleyRepoSettings :: GitRepoSettings subDocToMarkdown :: HeaderLevel -> SubDoc -> Markdown concreteTypeDocHaskellRep :: (Typeable a, GenericIsoValue a, GTypeHasDoc (Rep a), HaveCommonTypeCtor b a) => TypeDocHaskellRep b concreteTypeDocHaskellRepUnsafe :: (Typeable a, GenericIsoValue a, GTypeHasDoc (Rep a)) => TypeDocHaskellRep b concreteTypeDocMichelsonRep :: forall k a (b :: k). (Typeable a, SingI (ToT a), HaveCommonTypeCtor b a) => TypeDocMichelsonRep b concreteTypeDocMichelsonRepUnsafe :: forall k a (b :: k). (Typeable a, SingI (ToT a)) => TypeDocMichelsonRep b customTypeDocMdReference :: (Text, DType) -> [DType] -> WithinParens -> Markdown dTypeDep :: TypeHasDoc t => SomeDocDefinitionItem genericTypeDocDependencies :: (Generic a, GTypeHasDoc (Rep a)) => Proxy a -> [SomeDocDefinitionItem] haskellAddNewtypeField :: Text -> TypeDocHaskellRep a -> TypeDocHaskellRep a haskellRepNoFields :: TypeDocHaskellRep a -> TypeDocHaskellRep a haskellRepStripFieldPrefix :: HasCallStack => TypeDocHaskellRep a -> TypeDocHaskellRep a homomorphicTypeDocHaskellRep :: (Generic a, GTypeHasDoc (Rep a)) => TypeDocHaskellRep a homomorphicTypeDocMdReference :: (Typeable t, TypeHasDoc t, IsHomomorphic t) => Proxy t -> WithinParens -> Markdown homomorphicTypeDocMichelsonRep :: SingI (ToT a) => TypeDocMichelsonRep a poly1TypeDocMdReference :: forall (t :: Type -> Type) r a. (r ~ t a, Typeable t, Each '[TypeHasDoc] '[r, a], IsHomomorphic t) => Proxy r -> WithinParens -> Markdown poly2TypeDocMdReference :: forall (t :: Type -> Type -> Type) r a b. (r ~ t a b, Typeable t, Each '[TypeHasDoc] '[r, a, b], IsHomomorphic t) => Proxy r -> WithinParens -> Markdown data DEntrypointExample DEntrypointExample :: Value t -> DEntrypointExample data ContractDoc ContractDoc :: DocBlock -> DocBlock -> Set SomeDocDefinitionItem -> Set DocItemId -> ContractDoc [cdContents] :: ContractDoc -> DocBlock [cdDefinitions] :: ContractDoc -> DocBlock [cdDefinitionsSet] :: ContractDoc -> Set SomeDocDefinitionItem [cdDefinitionIds] :: ContractDoc -> Set DocItemId data DAnchor DAnchor :: Anchor -> DAnchor data DComment DComment :: Text -> DComment data DDescription DDescription :: Markdown -> DDescription data DGitRevision DGitRevisionKnown :: DGitRevisionInfo -> DGitRevision DGitRevisionUnknown :: DGitRevision data DocElem d DocElem :: d -> Maybe SubDoc -> DocElem d [deItem] :: DocElem d -> d [deSub] :: DocElem d -> Maybe SubDoc type DocGrouping = SubDoc -> SomeDocItem class (Typeable d, DOrd d) => DocItem d where { type family DocItemPlacement d :: DocItemPlacementKind; type family DocItemReferenced d :: DocItemReferencedKind; type DocItemPlacement d = 'DocItemInlined; type DocItemReferenced d = 'False; } docItemPos :: DocItem d => Natural docItemSectionName :: DocItem d => Maybe Text docItemSectionDescription :: DocItem d => Maybe Markdown docItemSectionNameStyle :: DocItem d => DocSectionNameStyle docItemRef :: DocItem d => d -> DocItemRef (DocItemPlacement d) (DocItemReferenced d) docItemToMarkdown :: DocItem d => HeaderLevel -> d -> Markdown docItemToToc :: DocItem d => HeaderLevel -> d -> Markdown docItemDependencies :: DocItem d => d -> [SomeDocDefinitionItem] docItemsOrder :: DocItem d => [d] -> [d] type family DocItemPlacement d :: DocItemPlacementKind type family DocItemReferenced d :: DocItemReferencedKind newtype DocItemId DocItemId :: Text -> DocItemId data DocItemPlacementKind DocItemInlined :: DocItemPlacementKind DocItemInDefinitions :: DocItemPlacementKind newtype DocItemPos DocItemPos :: (Natural, Text) -> DocItemPos data DocItemRef (p :: DocItemPlacementKind) (r :: DocItemReferencedKind) [DocItemRef] :: DocItemId -> DocItemRef 'DocItemInDefinitions 'True [DocItemRefInlined] :: DocItemId -> DocItemRef 'DocItemInlined 'True [DocItemNoRef] :: DocItemRef 'DocItemInlined 'False data DocSection DocSection :: (NonEmpty $ DocElem d) -> DocSection data DocSectionNameStyle DocSectionNameBig :: DocSectionNameStyle DocSectionNameSmall :: DocSectionNameStyle newtype GitRepoSettings GitRepoSettings :: (Text -> Text) -> GitRepoSettings [grsMkGitRevision] :: GitRepoSettings -> Text -> Text data SomeDocDefinitionItem [SomeDocDefinitionItem] :: forall d. (DocItem d, DocItemPlacement d ~ 'DocItemInDefinitions) => d -> SomeDocDefinitionItem data SomeDocItem [SomeDocItem] :: forall d. DocItem d => d -> SomeDocItem newtype SubDoc SubDoc :: DocBlock -> SubDoc data DType [DType] :: forall a. TypeHasDoc a => Proxy a -> DType class HaveCommonTypeCtor (a :: k) (b :: k1) class IsHomomorphic (a :: k) data SomeTypeWithDoc [SomeTypeWithDoc] :: forall td. TypeHasDoc td => Proxy td -> SomeTypeWithDoc class (Typeable a, SingI TypeDocFieldDescriptions a, FieldDescriptionsValid TypeDocFieldDescriptions a a) => TypeHasDoc a where { type family TypeDocFieldDescriptions a :: FieldDescriptions; type TypeDocFieldDescriptions a = '[] :: [(Symbol, (Maybe Symbol, [(Symbol, Symbol)]))]; } typeDocName :: TypeHasDoc a => Proxy a -> Text typeDocMdDescription :: TypeHasDoc a => Markdown typeDocMdReference :: TypeHasDoc a => Proxy a -> WithinParens -> Markdown typeDocDependencies :: TypeHasDoc a => Proxy a -> [SomeDocDefinitionItem] typeDocHaskellRep :: TypeHasDoc a => TypeDocHaskellRep a typeDocMichelsonRep :: TypeHasDoc a => TypeDocMichelsonRep a type family TypeDocFieldDescriptions a :: FieldDescriptions type Markdown = Builder type Value = Value' Instr eprName :: forall (mname :: Maybe Symbol). EntrypointRef mname -> EpName parameterEntrypointCall :: forall cp (name :: Symbol). ParameterDeclaresEntrypoints cp => Label name -> EntrypointCall cp (GetEntrypointArg cp name) parameterEntrypointCallCustom :: forall cp (mname :: Maybe Symbol). ParameterDeclaresEntrypoints cp => EntrypointRef mname -> EntrypointCall cp (GetEntrypointArgCustom cp mname) parameterEntrypointCallDefault :: ParameterDeclaresEntrypoints cp => EntrypointCall cp (GetDefaultEntrypointArg cp) parameterEntrypointsToNotes :: ParameterDeclaresEntrypoints cp => ParamNotes (ToT cp) sepcCallRootChecked :: (NiceParameter cp, ForbidExplicitDefaultEntrypoint cp) => SomeEntrypointCall cp type (n :: Symbol) :> ty = 'NamedEp n ty type family AllParameterEntrypoints cp :: [(Symbol, Type)] data EntrypointRef (mname :: Maybe Symbol) [CallDefault] :: EntrypointRef ('Nothing :: Maybe Symbol) [Call] :: forall (name :: Symbol). NiceEntrypointName name => EntrypointRef ('Just name) class EntrypointsDerivation (deriv :: k) cp where { type family EpdAllEntrypoints (deriv :: k) cp :: [(Symbol, Type)]; type family EpdLookupEntrypoint (deriv :: k) cp :: Symbol -> Exp Maybe Type; } epdNotes :: EntrypointsDerivation deriv cp => (Notes (ToT cp), RootAnn) epdCall :: forall (name :: Symbol). (EntrypointsDerivation deriv cp, ParameterScope (ToT cp)) => Label name -> EpConstructionRes (ToT cp) (Eval (EpdLookupEntrypoint deriv cp name)) epdDescs :: EntrypointsDerivation deriv cp => Rec EpCallingDesc (EpdAllEntrypoints deriv cp) type family EpdAllEntrypoints (deriv :: k) cp :: [(Symbol, Type)] type family EpdLookupEntrypoint (deriv :: k) cp :: Symbol -> Exp Maybe Type data EpdNone type ForbidExplicitDefaultEntrypoint cp = Eval LiftM3 UnMaybe :: Exp Constraint -> Type -> Exp Constraint -> Maybe Type -> Constraint -> Type Pure Pure () TError 'Text "Parameter used here must have no explicit \"default\" entrypoint" :$$: 'Text "In parameter type `" :<>: 'ShowType cp :<>: 'Text "`" :: Type -> Exp Constraint -> Type LookupParameterEntrypoint cp DefaultEpName type GetDefaultEntrypointArg cp = Eval LiftM2 FromMaybe :: Type -> Maybe Type -> Type -> Type Pure cp LookupParameterEntrypoint cp DefaultEpName type GetEntrypointArg cp (name :: Symbol) = Eval LiftM2 FromMaybe :: Type -> Maybe Type -> Type -> Type TError 'Text "Entrypoint not found: " :<>: 'ShowType name :$$: 'Text "In contract parameter `" :<>: 'ShowType cp :<>: 'Text "`" :: Type -> Type LookupParameterEntrypoint cp name type family GetEntrypointArgCustom cp (mname :: Maybe Symbol) type HasDefEntrypointArg (cp :: k) defEpName defArg = (defEpName ~ EntrypointRef 'Nothing :: Maybe Symbol, HasEntrypointArg cp defEpName defArg) class HasEntrypointArg (cp :: k) name arg useHasEntrypointArg :: HasEntrypointArg cp name arg => name -> (Dict (ParameterScope (ToT arg)), EpName) type HasEntrypointOfType param (con :: Symbol) exp = (GetEntrypointArgCustom param 'Just con ~ exp, ParameterDeclaresEntrypoints param) type family LookupParameterEntrypoint cp :: Symbol -> Exp Maybe Type type NoExplicitDefaultEntrypoint cp = Eval LookupParameterEntrypoint cp DefaultEpName ~ 'Nothing :: Maybe Type type family ParameterContainsEntrypoints param (fields :: [NamedEp]) type ParameterDeclaresEntrypoints cp = (If CanHaveEntrypoints cp ParameterHasEntrypoints cp (), NiceParameter cp, EntrypointsDerivation GetParameterEpDerivation cp cp) class (EntrypointsDerivation ParameterEntrypointsDerivation cp cp, RequireAllUniqueEntrypoints cp) => ParameterHasEntrypoints cp where { type family ParameterEntrypointsDerivation cp; } type family ParameterEntrypointsDerivation cp type RequireAllUniqueEntrypoints cp = RequireAllUniqueEntrypoints' ParameterEntrypointsDerivation cp cp newtype TrustEpName TrustEpName :: EpName -> TrustEpName newtype ShouldHaveEntrypoints a ShouldHaveEntrypoints :: a -> ShouldHaveEntrypoints a [unHasEntrypoints] :: ShouldHaveEntrypoints a -> a data EpdDelegate data EpdPlain data EpdRecursive data EpdWithRoot (r :: Symbol) (epd :: k) newtype ParameterWrapper deriv cp ParameterWrapper :: cp -> ParameterWrapper deriv cp [unParameterWraper] :: ParameterWrapper deriv cp -> cp areFinalizedParamBuildingSteps :: [ParamBuildingStep] -> Bool clarifyParamBuildingSteps :: forall (inp :: [Type]) (out :: [Type]). ParamBuildingStep -> (inp :-> out) -> inp :-> out constructDEpArg :: (TypeHasDoc arg, HasAnnotation arg, KnownValue arg) => DEntrypointArg diEntrypointToMarkdown :: HeaderLevel -> DEntrypoint level -> Markdown documentEntrypoint :: forall kind (epName :: Symbol) param (s :: [Type]) (out :: [Type]). (KnownSymbol epName, DocItem (DEntrypoint kind), TypeHasDoc param, HasAnnotation param, KnownValue param) => ((param & s) :-> out) -> (param & s) :-> out emptyDEpArg :: DEntrypointArg entryCaseSimple_ :: forall cp (out :: [Type]) (inp :: [Type]). (InstrCaseC cp, RMap (CaseClauses cp), DocumentEntrypoints PlainEntrypointsKind cp, NiceParameterFull cp, RequireFlatParamEps cp) => Rec (CaseClauseL inp out) (CaseClauses cp) -> (cp & inp) :-> out mkDEntrypointArgSimple :: (KnownValue t, HasAnnotation t, TypeHasDoc t) => DEntrypointArg mkDEpUType :: (KnownValue t, HasAnnotation t) => Type mkPbsWrapIn :: Text -> ParamBuilder -> ParamBuildingStep mkUType :: forall (x :: T). SingI x => Notes x -> Type data DEntrypoint kind DEntrypoint :: Text -> SubDoc -> DEntrypoint kind [depName] :: DEntrypoint kind -> Text [depSub] :: DEntrypoint kind -> SubDoc data DEntrypointArg DEntrypointArg :: Maybe DType -> [ParamBuildingStep] -> Type -> DEntrypointArg [epaArg] :: DEntrypointArg -> Maybe DType [epaBuilding] :: DEntrypointArg -> [ParamBuildingStep] [epaType] :: DEntrypointArg -> Type data DEntrypointReference DEntrypointReference :: Text -> Anchor -> DEntrypointReference class KnownSymbol con => DeriveCtorFieldDoc (con :: Symbol) (cf :: CtorField) deriveCtorFieldDoc :: DeriveCtorFieldDoc con cf => DEntrypointArg type DocumentEntrypoints kind a = (Generic a, GDocumentEntrypoints kind Rep a) class EntryArrow (kind :: k) (name :: Symbol) body (#->) :: EntryArrow kind name body => (Label name, Proxy kind) -> body -> body newtype ParamBuilder ParamBuilder :: (Markdown -> Markdown) -> ParamBuilder [unParamBuilder] :: ParamBuilder -> Markdown -> Markdown data ParamBuildingDesc ParamBuildingDesc :: Markdown -> ParamBuilder -> ParamBuilder -> ParamBuildingDesc [pbdEnglish] :: ParamBuildingDesc -> Markdown [pbdHaskell] :: ParamBuildingDesc -> ParamBuilder [pbdMichelson] :: ParamBuildingDesc -> ParamBuilder data ParamBuildingStep PbsWrapIn :: Text -> ParamBuildingDesc -> ParamBuildingStep PbsCallEntrypoint :: EpName -> ParamBuildingStep PbsCustom :: ParamBuildingDesc -> ParamBuildingStep PbsUncallable :: [ParamBuildingStep] -> ParamBuildingStep data PlainEntrypointsKind type family RequireFlatEpDerivation (cp :: t) deriv type family RequireFlatParamEps cp data EpName customErrorDocHaskellRepGeneral :: forall (tag :: Symbol). (SingI (ToT (ErrorArg tag)), IsError (CustomError tag), TypeHasDoc (ErrorArg tag), CustomErrorHasDoc tag) => Text -> Proxy tag -> Markdown errorTagToMText :: forall (tag :: Symbol). Label tag -> MText errorTagToText :: forall (tag :: Symbol). KnownSymbol tag => Text failUnexpected :: forall (s :: [Type]) (t :: [Type]). MText -> s :-> t failUsing :: forall e (s :: [Type]) (t :: [Type]). IsError e => e -> s :-> t isoErrorFromVal :: forall (t :: T) e. (Typeable t, Typeable (ToT e), IsoValue e) => Value t -> Either Text e isoErrorToVal :: (KnownError e, IsoValue e) => e -> (forall (t :: T). ErrorScope t => Value t -> r) -> r typeDocMdDescriptionReferToError :: IsError e => Markdown data CustomError (tag :: Symbol) CustomError :: Label tag -> ErrorArg tag -> CustomError (tag :: Symbol) [ceTag] :: CustomError (tag :: Symbol) -> Label tag [ceArg] :: CustomError (tag :: Symbol) -> ErrorArg tag class (KnownSymbol tag, TypeHasDoc ErrorArg tag, IsError CustomError tag) => CustomErrorHasDoc (tag :: Symbol) customErrDocMdCause :: CustomErrorHasDoc tag => Markdown customErrDocMdCauseInEntrypoint :: CustomErrorHasDoc tag => Markdown customErrClass :: CustomErrorHasDoc tag => ErrorClass customErrArgumentSemantics :: CustomErrorHasDoc tag => Maybe Markdown data DError [DError] :: forall e. ErrorHasDoc e => Proxy e -> DError data DThrows [DThrows] :: forall e. ErrorHasDoc e => Proxy e -> DThrows type family ErrorArg (tag :: Symbol) data ErrorClass ErrClassActionException :: ErrorClass ErrClassBadArgument :: ErrorClass ErrClassContractInternal :: ErrorClass ErrClassUnknown :: ErrorClass class Typeable e => ErrorHasDoc e where { type family ErrorRequirements e; type ErrorRequirements e = (); } errorDocName :: ErrorHasDoc e => Text errorDocMdCause :: ErrorHasDoc e => Markdown errorDocMdCauseInEntrypoint :: ErrorHasDoc e => Markdown errorDocHaskellRep :: ErrorHasDoc e => Markdown errorDocClass :: ErrorHasDoc e => ErrorClass errorDocDependencies :: ErrorHasDoc e => [SomeDocDefinitionItem] errorDocRequirements :: ErrorHasDoc e => Dict (ErrorRequirements e) type family ErrorRequirements e type ErrorScope (t :: T) = (Typeable t, ConstantScope t) class (Typeable e, ErrorHasDoc e) => IsError e errorToVal :: IsError e => e -> (forall (t :: T). ErrorScope t => Value t -> r) -> r errorFromVal :: forall (t :: T). (IsError e, KnownT t) => Value t -> Either Text e type RequireNoArgError (tag :: Symbol) (msg :: ErrorMessage) = (TypeErrorUnless ErrorArg tag == () msg, msg ~ 'Text "Expected no-arg error, but given error requires argument of type " :<>: 'ShowType ErrorArg tag) data SomeError SomeError :: e -> SomeError data UnspecifiedError UnspecifiedError :: UnspecifiedError class WellTypedToT a => IsoValue a where { type family ToT a :: T; type ToT a = GValueType Rep a; } toVal :: IsoValue a => a -> Value (ToT a) fromVal :: IsoValue a => Value (ToT a) -> a type WellTypedIsoValue a = (WellTyped ToT a, IsoValue a) addNewErrorTags :: ErrorTagMap -> HashSet MText -> ErrorTagMap applyErrorTagMap :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => ErrorTagMap -> (inp :-> out) -> inp :-> out applyErrorTagMapWithExclusions :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => ErrorTagMap -> ErrorTagExclusions -> (inp :-> out) -> inp :-> out buildErrorTagMap :: HashSet MText -> ErrorTagMap errorFromValNumeric :: forall (t :: T) e. (KnownT t, IsError e) => ErrorTagMap -> Value t -> Either Text e errorToValNumeric :: IsError e => ErrorTagMap -> e -> (forall (t :: T). ErrorScope t => Value t -> r) -> r excludeErrorTags :: HasCallStack => ErrorTagExclusions -> ErrorTagMap -> ErrorTagMap gatherErrorTags :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> HashSet MText useNumericErrors :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => (inp :-> out) -> (inp :-> out, ErrorTagMap) applyErrorTagToErrorsDoc :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => ErrorTagMap -> (inp :-> out) -> inp :-> out applyErrorTagToErrorsDocWith :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => [NumericErrorDocHandler] -> ErrorTagMap -> (inp :-> out) -> inp :-> out baseErrorDocHandlers :: [NumericErrorDocHandler] customErrorDocHandler :: NumericErrorDocHandler voidResultDocHandler :: NumericErrorDocHandler type ErrorTagExclusions = HashSet MText type ErrorTagMap = Bimap Natural MText data DDescribeErrorTagMap DDescribeErrorTagMap :: Text -> DDescribeErrorTagMap [detmSrcLoc] :: DDescribeErrorTagMap -> Text data NumericErrorDocHandler data NumericErrorDocHandlerError data NumericErrorWrapper (numTag :: Nat) err printComment :: forall (s :: [Type]). PrintComment (ToTs s) -> s :-> s stackRef :: forall (gn :: Nat) (st :: [T]) (n :: Peano). (n ~ ToPeano gn, SingI n, KnownPeano n, RequireLongerThan st n) => PrintComment st stackType :: forall (s :: [Type]). s :-> s testAssert :: forall (out :: [Type]) (inp :: [Type]). (Typeable (ToTs out), HasCallStack) => Text -> PrintComment (ToTs inp) -> (inp :-> (Bool & out)) -> inp :-> inp class NonZero t class ConcatOp ToT c => ConcatOpHs c type List = [] class (EDivOp ToT n ToT m, NiceComparable n, NiceComparable m, ToT EDivOpResHs n m ~ EDivOpRes ToT n ToT m, ToT EModOpResHs n m ~ EModOpRes ToT n ToT m) => EDivOpHs n m where { type family EDivOpResHs n m; type family EModOpResHs n m; } type family EDivOpResHs n m type family EModOpResHs n m class (MemOp ToT c, ToT MemOpKeyHs c ~ MemOpKey ToT c) => MemOpHs c where { type family MemOpKeyHs c; } type family MemOpKeyHs c class (GetOp ToT c, ToT GetOpKeyHs c ~ GetOpKey ToT c, ToT GetOpValHs c ~ GetOpVal ToT c) => GetOpHs c where { type family GetOpKeyHs c; type family GetOpValHs c; } type family GetOpValHs c type family GetOpKeyHs c class (IterOp ToT c, ToT IterOpElHs c ~ IterOpEl ToT c) => IterOpHs c where { type family IterOpElHs c; } type family IterOpElHs c class (MapOp ToT c, ToT MapOpInpHs c ~ MapOpInp ToT c, ToT MapOpResHs c () ~ MapOpRes ToT c ToT ()) => MapOpHs c where { type family MapOpInpHs c; type family MapOpResHs c :: Type -> Type; } type family IsoMapOpRes c b type family MapOpInpHs c type family MapOpResHs c :: Type -> Type class SizeOp ToT c => SizeOpHs c class SliceOp ToT c => SliceOpHs c class (UpdOp ToT c, ToT UpdOpKeyHs c ~ UpdOpKey ToT c, ToT UpdOpParamsHs c ~ UpdOpParams ToT c) => UpdOpHs c where { type family UpdOpKeyHs c; type family UpdOpParamsHs c; } type family UpdOpKeyHs c type family UpdOpParamsHs c voidResultTag :: MText data View a r data VoidResult r data Void_ a b class ToContractRef cp contract toContractRef :: ToContractRef cp contract => contract -> ContractRef cp expressionToScriptExpr :: Expression -> ByteString lEncodeValue :: NicePrintedValue a => a -> ByteString lPackValue :: NicePackedValue a => a -> ByteString lUnpackValue :: NiceUnpackedValue a => ByteString -> Either UnpackError a valueToScriptExpr :: NicePackedValue t => t -> ByteString printLorentzContract :: (NiceParameterFull cp, NiceStorage st) => Bool -> Contract cp st -> LText printLorentzValue :: NicePrintedValue v => Bool -> v -> LText dipT :: forall a (inp :: [Type]) (dinp :: [Type]) (dout :: [Type]) (out :: [Type]). DipT inp a inp dinp dout out => (dinp :-> dout) -> inp :-> out dropT :: forall a (inp :: [Type]) (dinp :: [Type]) (dout :: [Type]) (out :: [Type]). (DipT inp a inp dinp dout out, dinp ~ (a : dout)) => inp :-> out dupT :: forall a (st :: [Type]). DupT st a st => st :-> (a : st) analyzeLorentz :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> AnalyzerRes compileLorentz :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> Instr (ToTs inp) (ToTs out) compileLorentzContract :: (NiceParameterFull cp, NiceStorage st) => Contract cp st -> Contract (ToT cp) (ToT st) compileLorentzWithOptions :: forall (inp :: [Type]) (out :: [Type]). CompilationOptions -> (inp :-> out) -> Instr (ToTs inp) (ToTs out) defaultCompilationOptions :: CompilationOptions defaultContract :: ContractCode cp st -> Contract cp st interpretLorentzInstr :: forall (inp :: [Type]) (out :: [Type]). (IsoValuesStack inp, IsoValuesStack out) => ContractEnv -> (inp :-> out) -> Rec Identity inp -> Either MichelsonFailed (Rec Identity out) interpretLorentzLambda :: (IsoValue inp, IsoValue out) => ContractEnv -> Lambda inp out -> inp -> Either MichelsonFailed out data CompilationOptions CompilationOptions :: Maybe OptimizerConf -> (Bool, MText -> MText) -> (Bool, ByteString -> ByteString) -> CompilationOptions [coOptimizerConf] :: CompilationOptions -> Maybe OptimizerConf [coStringTransformer] :: CompilationOptions -> (Bool, MText -> MText) [coBytesTransformer] :: CompilationOptions -> (Bool, ByteString -> ByteString) composeStoreEntrypointOps :: forall (nameInStore :: Symbol) store substore (epName :: Symbol) epParam epStore. Label nameInStore -> StoreFieldOps store nameInStore substore -> StoreEntrypointOps substore epName epParam epStore -> StoreEntrypointOps store epName epParam epStore composeStoreFieldOps :: forall (nameInStore :: Symbol) store substore (nameInSubstore :: Symbol) field. Label nameInStore -> StoreFieldOps store nameInStore substore -> StoreFieldOps substore nameInSubstore field -> StoreFieldOps store nameInSubstore field composeStoreSubmapOps :: forall (nameInStore :: Symbol) store substore (mname :: Symbol) key value. Label nameInStore -> StoreFieldOps store nameInStore substore -> StoreSubmapOps substore mname key value -> StoreSubmapOps store mname key value mkStoreEp :: forall (epName :: Symbol) epParam epStore. Label epName -> EntrypointLambda epParam epStore -> EntrypointsField epParam epStore stEntrypoint :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (epParam : (store : s)) :-> (([Operation], store) : s) stGetEpLambda :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : (store : s)) stGetEpStore :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (epStore : (store : s)) stGetField :: forall store (fname :: Symbol) ftype (s :: [Type]). StoreHasField store fname ftype => Label fname -> (store : s) :-> (ftype : (store : s)) stSetEpLambda :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (EntrypointLambda epParam epStore : (store : s)) :-> (store : s) stSetEpStore :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (epStore : (store : s)) :-> (store : s) stSetField :: forall store (fname :: Symbol) ftype (s :: [Type]). StoreHasField store fname ftype => Label fname -> (ftype : (store : s)) :-> (store : s) stToEpLambda :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : s) stToEpStore :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (epStore : s) stToField :: forall store (fname :: Symbol) ftype (s :: [Type]). StoreHasField store fname ftype => Label fname -> (store : s) :-> (ftype : s) storeEntrypointOpsADT :: forall store (epmName :: Symbol) epParam epStore (epsName :: Symbol) (epName :: Symbol). (HasFieldOfType store epmName (EntrypointsField epParam epStore), HasFieldOfType store epsName epStore, KnownValue epParam, KnownValue epStore) => Label epmName -> Label epsName -> StoreEntrypointOps store epName epParam epStore storeEntrypointOpsDeeper :: forall store (nameInStore :: Symbol) substore (epName :: Symbol) epParam epStore. (HasFieldOfType store nameInStore substore, StoreHasEntrypoint substore epName epParam epStore) => Label nameInStore -> StoreEntrypointOps store epName epParam epStore storeEntrypointOpsFields :: forall store (epmName :: Symbol) epParam epStore (epsName :: Symbol) (epName :: Symbol). (StoreHasField store epmName (EntrypointsField epParam epStore), StoreHasField store epsName epStore, KnownValue epParam, KnownValue epStore) => Label epmName -> Label epsName -> StoreEntrypointOps store epName epParam epStore storeEntrypointOpsReferTo :: forall (epName :: Symbol) store epParam epStore (desiredName :: Symbol). Label epName -> StoreEntrypointOps store epName epParam epStore -> StoreEntrypointOps store desiredName epParam epStore storeEntrypointOpsSubmapField :: forall store (epmName :: Symbol) epParam epStore (epsName :: Symbol) (epName :: Symbol). (StoreHasSubmap store epmName MText (EntrypointLambda epParam epStore), StoreHasField store epsName epStore, KnownValue epParam, KnownValue epStore) => Label epmName -> Label epsName -> StoreEntrypointOps store epName epParam epStore storeFieldOpsADT :: forall dt (fname :: Symbol) ftype. HasFieldOfType dt fname ftype => StoreFieldOps dt fname ftype storeFieldOpsDeeper :: forall storage (fieldsPartName :: Symbol) fields (fname :: Symbol) ftype. (HasFieldOfType storage fieldsPartName fields, StoreHasField fields fname ftype) => Label fieldsPartName -> StoreFieldOps storage fname ftype storeFieldOpsReferTo :: forall (name :: Symbol) storage field (desiredName :: Symbol). Label name -> StoreFieldOps storage name field -> StoreFieldOps storage desiredName field storeSubmapOpsDeeper :: forall storage (bigMapPartName :: Symbol) fields (mname :: Symbol) key value. (HasFieldOfType storage bigMapPartName fields, StoreHasSubmap fields mname key value) => Label bigMapPartName -> StoreSubmapOps storage mname key value storeSubmapOpsReferTo :: forall (name :: Symbol) storage key value (desiredName :: Symbol). Label name -> StoreSubmapOps storage name key value -> StoreSubmapOps storage desiredName key value data (param :: k) ::-> (store :: k1) type EntrypointLambda param store = Lambda (param, store) ([Operation], store) type EntrypointsField param store = BigMap MText EntrypointLambda param store type family StorageContains store (content :: [NamedField]) data StoreEntrypointOps store (epName :: Symbol) epParam epStore StoreEntrypointOps :: (forall (s :: [Type]). () => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : s)) -> (forall (s :: [Type]). () => Label epName -> (EntrypointLambda epParam epStore : (store : s)) :-> (store : s)) -> (forall (s :: [Type]). () => Label epName -> (store : s) :-> (epStore : s)) -> (forall (s :: [Type]). () => Label epName -> (epStore : (store : s)) :-> (store : s)) -> StoreEntrypointOps store (epName :: Symbol) epParam epStore [sopToEpLambda] :: StoreEntrypointOps store (epName :: Symbol) epParam epStore -> forall (s :: [Type]). () => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : s) [sopSetEpLambda] :: StoreEntrypointOps store (epName :: Symbol) epParam epStore -> forall (s :: [Type]). () => Label epName -> (EntrypointLambda epParam epStore : (store : s)) :-> (store : s) [sopToEpStore] :: StoreEntrypointOps store (epName :: Symbol) epParam epStore -> forall (s :: [Type]). () => Label epName -> (store : s) :-> (epStore : s) [sopSetEpStore] :: StoreEntrypointOps store (epName :: Symbol) epParam epStore -> forall (s :: [Type]). () => Label epName -> (epStore : (store : s)) :-> (store : s) data StoreFieldOps store (fname :: Symbol) ftype StoreFieldOps :: (forall (s :: [Type]). () => Label fname -> (store : s) :-> (ftype : s)) -> (forall (s :: [Type]). () => Label fname -> (ftype : (store : s)) :-> (store : s)) -> StoreFieldOps store (fname :: Symbol) ftype [sopToField] :: StoreFieldOps store (fname :: Symbol) ftype -> forall (s :: [Type]). () => Label fname -> (store : s) :-> (ftype : s) [sopSetField] :: StoreFieldOps store (fname :: Symbol) ftype -> forall (s :: [Type]). () => Label fname -> (ftype : (store : s)) :-> (store : s) class StoreHasEntrypoint store (epName :: Symbol) epParam epStore | store epName -> epParam epStore storeEpOps :: StoreHasEntrypoint store epName epParam epStore => StoreEntrypointOps store epName epParam epStore class StoreHasField store (fname :: Symbol) ftype | store fname -> ftype storeFieldOps :: StoreHasField store fname ftype => StoreFieldOps store fname ftype class StoreHasSubmap store (mname :: Symbol) key value | store mname -> key value storeSubmapOps :: StoreHasSubmap store mname key value => StoreSubmapOps store mname key value data StoreSubmapOps store (mname :: Symbol) key value StoreSubmapOps :: (forall (s :: [Type]). () => Label mname -> (key : (store : s)) :-> (Bool : s)) -> (forall (s :: [Type]). KnownValue value => Label mname -> (key : (store : s)) :-> (Maybe value : s)) -> (forall (s :: [Type]). () => Label mname -> (key : (Maybe value : (store : s))) :-> (store : s)) -> (forall (s :: [Type]). () => Maybe (Label mname -> (key : (store : s)) :-> (store : s))) -> (forall (s :: [Type]). () => Maybe (Label mname -> (key : (value : (store : s))) :-> (store : s))) -> StoreSubmapOps store (mname :: Symbol) key value [sopMem] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). () => Label mname -> (key : (store : s)) :-> (Bool : s) [sopGet] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). KnownValue value => Label mname -> (key : (store : s)) :-> (Maybe value : s) [sopUpdate] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). () => Label mname -> (key : (Maybe value : (store : s))) :-> (store : s) [sopDelete] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). () => Maybe (Label mname -> (key : (store : s)) :-> (store : s)) [sopInsert] :: StoreSubmapOps store (mname :: Symbol) key value -> forall (s :: [Type]). () => Maybe (Label mname -> (key : (value : (store : s))) :-> (store : s)) data (k2 :: k) ~> (v :: k1) caseUParam :: forall (entries :: [EntrypointKind]) (inp :: [Type]) (out :: [Type]). (CaseUParam entries, RequireUniqueEntrypoints entries) => Rec (CaseClauseU inp out) entries -> UParamFallback inp out -> (UParam entries : inp) :-> out caseUParamT :: forall (entries :: [EntrypointKind]) (inp :: [Type]) (out :: [Type]) clauses. (clauses ~ Rec (CaseClauseU inp out) entries, RecFromTuple clauses, CaseUParam entries) => IsoRecTuple clauses -> UParamFallback inp out -> (UParam entries : inp) :-> out mkUParam :: forall a (name :: Symbol) (entries :: [EntrypointKind]). (NicePackedValue a, LookupEntrypoint name entries ~ a, RequireUniqueEntrypoints entries) => Label name -> a -> UParam entries pbsUParam :: forall (ctorName :: Symbol). KnownSymbol ctorName => ParamBuildingStep unwrapUParam :: forall (entries :: [EntrypointKind]) (s :: [Type]). (UParam entries : s) :-> ((MText, ByteString) : s) uparamFallbackFail :: forall (inp :: [Type]) (out :: [Type]). UParamFallback inp out uparamFromAdt :: UParamLinearize up => up -> UParam (UParamLinearized up) type (n :: Symbol) ?: (a :: k) = '(n, a) class CaseUParam (entries :: [EntrypointKind]) data ConstrainedSome (c :: Type -> Constraint) [ConstrainedSome] :: forall (c :: Type -> Constraint) a. c a => a -> ConstrainedSome c type EntrypointKind = (Symbol, Type) data EntrypointLookupError NoSuchEntrypoint :: MText -> EntrypointLookupError ArgumentUnpackFailed :: EntrypointLookupError type EntrypointsImpl (inp :: [Type]) (out :: [Type]) (entries :: [EntrypointKind]) = Rec CaseClauseU inp out entries type family LookupEntrypoint (name :: Symbol) (entries :: [EntrypointKind]) type family RequireUniqueEntrypoints (entries :: [EntrypointKind]) type SomeInterface = '[ '("SomeEntrypoints", Void)] newtype UParam (entries :: [EntrypointKind]) UParamUnsafe :: (MText, ByteString) -> UParam (entries :: [EntrypointKind]) type UParamFallback (inp :: [Type]) (out :: [Type]) = (MText, ByteString) : inp :-> out type UParamLinearize p = (Generic p, GUParamLinearize Rep p) type UParamLinearized p = GUParamLinearized Rep p type UParam_ = UParam SomeInterface class UnpackUParam (c :: Type -> Constraint) (entries :: [EntrypointKind]) unpackUParam :: UnpackUParam c entries => UParam entries -> Either EntrypointLookupError (MText, ConstrainedSome c) entrypointDoc :: QuasiQuoter errorDoc :: QuasiQuoter typeDoc :: QuasiQuoter callingDefTAddress :: NiceParameterFull cp => TAddress cp -> ContractRef (GetDefaultEntrypointArg cp) callingTAddress :: forall cp (mname :: Maybe Symbol). NiceParameterFull cp => TAddress cp -> EntrypointRef mname -> ContractRef (GetEntrypointArgCustom cp mname) convertContractRef :: forall cp contract2 contract1. (ToContractRef cp contract1, FromContractRef cp contract2) => contract1 -> contract2 mt :: QuasiQuoter coerceContractRef :: ToT a ~ ToT b => ContractRef a -> ContractRef b pattern DefEpName :: EpName oneMutez :: Mutez timestampFromSeconds :: Integer -> Timestamp timestampFromUTCTime :: UTCTime -> Timestamp timestampQuote :: QuasiQuoter toMutez :: Word32 -> Mutez zeroMutez :: Mutez cstr :: forall (n :: Nat). KnownNat n => [Natural] -> CstrDepth customGeneric :: String -> GenericStrategy -> Q [Dec] fld :: forall (n :: Nat). KnownNat n => Natural leftBalanced :: GenericStrategy leftComb :: GenericStrategy rightBalanced :: GenericStrategy rightComb :: GenericStrategy withDepths :: [CstrDepth] -> GenericStrategy class FromContractRef cp contract fromContractRef :: FromContractRef cp contract => ContractRef cp -> contract class ToAddress a toAddress :: ToAddress a => a -> Address class ToTAddress cp a toTAddress :: ToTAddress cp a => a -> TAddress cp type EntrypointCall param arg = EntrypointCallT ToT param ToT arg type SomeEntrypointCall arg = SomeEntrypointCallT ToT arg -- | Allows to get a variable with storage type HasStorage st = (Given (Var st), KnownValue st) -- | Allows to get a variable with operations type HasSideEffects = Given (Var Ops) type Ops = [Operation] -- | A variable referring to an element in the stack. data Var a Var :: RefId -> Var a -- | Stack of the symbolic interpreter. type StackVars (stk :: [Type]) = Rec StkEl stk -- | Stack element of the symbolic interpreter. -- -- It holds either a reference index that refers to this element or just -- NoRef, indicating that there are no references to this element. data StkEl a [NoRef] :: KnownValue a => StkEl a [Ref] :: KnownValue a => RefId -> StkEl a -- | Reference id to a stack cell data RefId emptyStack :: StackVars '[] -- | Given a StackVars and a Peano singleton for a depth, -- it puts a new Var at that depth (0-indexed) and returns it with -- the updated StackVars. -- -- If there is a Var there already it is used and the -- StackVars not changed. assignVarAt :: (KnownValue a, a ~ At n inp, RequireLongerThan inp n) => Var a -> StackVars inp -> Sing n -> StackVars inp -- | Push a new stack element with a reference to it, given the variable. pushRef :: KnownValue a => Var a -> StackVars inp -> StackVars (a & inp) -- | Push a new stack element without a reference to it. pushNoRef :: KnownValue a => StackVars inp -> StackVars (a & inp) -- | Remove the top element of the stack. It's supposed that no variable -- refers to this element. popNoRef :: StackVars (a & inp) -> StackVars inp -- | Return a variable which refers to a stack cell with operations operationsVar :: HasSideEffects => Var Ops -- | Return a variable which refers to a stack cell with storage storageVar :: HasStorage st => Var st type ComplexObjectC a = (ToDeconstructC a, ToConstructC a, AllConstrained IsObject (FieldTypes a)) type FieldTypes a = MapGFT a (ConstructorFieldNames a) class IsObject' (TypeDecision a) a => IsObject a -- | Like NamedFieldObj, but this one doesn't keep name of a field data TypedFieldObj a [TypedFieldObj] :: IsObject a => Object a -> TypedFieldObj a data SomeObject [SomeObject] :: IsObject a => Object a -> SomeObject type Object a = IndigoObjectF (NamedFieldObj a) a -- | Auxiliary datatype to define a Objiable. Keeps field name as type -- param data NamedFieldObj a name [NamedFieldObj] :: IsObject (GetFieldType a name) => {unFieldObj :: Object (GetFieldType a name)} -> NamedFieldObj a name -- | A object that can be either stored in the single stack cell or split -- into fields. Fields are identified by their names. -- -- f is a functor to be applied to each of field names. data IndigoObjectF f a -- | Value stored on the stack, it might be either complex product type, -- like (a, b), Storage, etc, or sum type like Either, or -- primitive like Int, Operation, etc. [Cell] :: KnownValue a => RefId -> IndigoObjectF f a -- | Decomposed product type, which is NOT stored as one cell on the stack. [Decomposed] :: ComplexObjectC a => Rec f (ConstructorFieldNames a) -> IndigoObjectF f a -- | Convert a list of fields from name-based list to type-based one namedToTypedRec :: forall a f g. (forall name. f name -> g (GetFieldType a name)) -> Rec f (ConstructorFieldNames a) -> Rec g (FieldTypes a) -- | Convert a list of fields from type-based list to named-based one typedToNamedRec :: forall a f g. KnownList (ConstructorFieldNames a) => (forall name. f (GetFieldType a name) -> g name) -> Rec f (FieldTypes a) -> Rec g (ConstructorFieldNames a) castFieldConstructors :: forall a st. CastFieldConstructors (FieldTypes a) (ConstructorFieldTypes a) => Rec (FieldConstructor st) (FieldTypes a) -> Rec (FieldConstructor st) (ConstructorFieldTypes a) namedToTypedFieldObj :: forall a name. NamedFieldObj a name -> TypedFieldObj (GetFieldType a name) typedToNamedFieldObj :: forall a name. TypedFieldObj (GetFieldType a name) -> NamedFieldObj a name complexObjectDict :: forall a. IsObject a => Maybe (Dict (ComplexObjectC a)) -- | Resulting state of IndigoM. data GenCode inp out GenCode :: ~StackVars out -> (inp :-> out) -> (out :-> inp) -> GenCode inp out -- | Stack of the symbolic interpreter. [gcStack] :: GenCode inp out -> ~StackVars out -- | Generated Lorentz code. [gcCode] :: GenCode inp out -> inp :-> out -- | Clearing Lorentz code. [gcClear] :: GenCode inp out -> out :-> inp data MetaData inp MetaData :: StackVars inp -> DecomposedObjects -> MetaData inp [mdStack] :: MetaData inp -> StackVars inp [mdObjects] :: MetaData inp -> DecomposedObjects type DecomposedObjects = Map RefId SomeObject -- | IndigoState data type. -- -- It takes as input a StackVars (for the initial state) and -- returns a GenCode (for the resulting state and the generated -- Lorentz code). -- -- IndigoState has to be used to write backend typed Lorentz code from -- the corresponding frontend constructions. -- -- It has no return type, IndigoState instruction may take one or more -- "return variables", that they assign to values produced during their -- execution. newtype IndigoState inp out IndigoState :: (MetaData inp -> GenCode inp out) -> IndigoState inp out [runIndigoState] :: IndigoState inp out -> MetaData inp -> GenCode inp out -- | Inverse of runIndigoState for utility. usingIndigoState :: MetaData inp -> IndigoState inp out -> GenCode inp out -- | Put new GenCode. iput :: GenCode inp out -> IndigoState inp out -- | The simplest IndigoState, it does not modify the stack, nor the -- produced code. nopState :: IndigoState inp inp -- | Assigns a variable to reference the element on top of the stack. assignTopVar :: KnownValue x => Var x -> IndigoState (x & inp) (x & inp) withObject :: forall a r. KnownValue a => DecomposedObjects -> Var a -> (Object a -> r) -> r withObjectState :: forall a inp out. KnownValue a => Var a -> (Object a -> IndigoState inp out) -> IndigoState inp out -- | Utility function to create IndigoState that need access to the -- current StackVars. withStackVars :: (StackVars inp -> IndigoState inp out) -> IndigoState inp out replStkMd :: MetaData inp -> StackVars inp1 -> MetaData inp1 alterStkMd :: MetaData inp -> (StackVars inp -> StackVars inp1) -> MetaData inp1 -- | pushRef version for MetaData pushRefMd :: KnownValue a => Var a -> MetaData inp -> MetaData (a & inp) -- | pushNoRef version for MetaData pushNoRefMd :: KnownValue a => MetaData inp -> MetaData (a & inp) -- | popNoRef version for MetaData popNoRefMd :: MetaData (a & inp) -> MetaData inp -- | Produces the generated Lorentz code that cleans after itself, leaving -- the same stack as the input one cleanGenCode :: GenCode inp out -> inp :-> inp -- | Puts a copy of the value for the given Var on top of the stack varActionGet :: forall a stk. KnownValue a => RefId -> StackVars stk -> stk :-> (a & stk) -- | Sets the value for the given Var to the topmost value on the -- stack varActionSet :: forall a stk. KnownValue a => RefId -> StackVars stk -> (a & stk) :-> stk -- | Updates the value for the given Var with the topmost value on -- the stack using the given binary instruction. varActionUpdate :: forall a b stk. (KnownValue a, KnownValue b) => RefId -> StackVars stk -> ('[b, a] :-> '[a]) -> (b : stk) :-> stk -- | Given a stack with a list of Operations on its bottom, updates -- it by appending the Operation on the top. varActionOperation :: HasSideEffects => StackVars stk -> (Operation : stk) :-> stk rtake :: Sing n -> Rec any s -> Rec any (Take n s) rdrop :: Sing n -> Rec any s -> Rec any (Drop n s) -- | IndigoState with hidden output stack, necessary to generate -- typed Lorentz code from untyped Indigo frontend. newtype SomeIndigoState inp SomeIndigoState :: (MetaData inp -> SomeGenCode inp) -> SomeIndigoState inp [unSIS] :: SomeIndigoState inp -> MetaData inp -> SomeGenCode inp -- | GenCode with hidden output stack data SomeGenCode inp [SomeGenCode] :: GenCode inp out -> SomeGenCode inp -- | To run SomeIndigoState you need to pass an handler of -- GenCode with any output stack and initial MetaData. runSIS :: SomeIndigoState inp -> MetaData inp -> (forall out. GenCode inp out -> r) -> r -- | Convert IndigoState to SomeIndigoState toSIS :: IndigoState inp out -> SomeIndigoState inp -- | Similar to a >> for SomeIndigoState. thenSIS :: SomeIndigoState inp -> (forall out. SomeIndigoState out) -> SomeIndigoState inp -- | Modify the GenCode inside a SomeIndigoState by passing -- an handler of GenCode that returns a SomeGenCode. Useful -- in some cases to "wrap" or update and exising SomeGenCode. overSIS :: (forall out. GenCode inp out -> SomeGenCode inp) -> SomeIndigoState inp -> SomeIndigoState inp -- | Class like StoreHasField type class but holding a lens to a -- field. class (KnownValue ftype, KnownValue dt) => HasField dt fname ftype | dt fname -> ftype fieldLens :: HasField dt fname ftype => FieldLens dt fname ftype -- | Lens to a field. obj.f1.f2.f3 is represented as list names of -- [f1, f2, f3]. -- -- dt is a type of source object (type of obj in example above) -- fname is a name of target field ("f3" in example -- above) ftype is a type of target field -- -- However, a lens contains not only name of field but for each field it -- contains operations to get and set target field. data FieldLens dt fname ftype [TargetField] :: (InstrGetFieldC dt fname, InstrSetFieldC dt fname, GetFieldType dt fname ~ targetFType, AccessFieldC dt fname) => Label fname -> StoreFieldOps dt targetFName targetFType -> FieldLens dt targetFName targetFType [DeeperField] :: (AccessFieldC dt fname, InstrSetFieldC dt fname, HasField (GetFieldType dt fname) targetFName targetFType) => Label fname -> StoreFieldOps dt targetFName targetFType -> FieldLens dt targetFName targetFType -- | Constraint to access/assign field stored in Rec type AccessFieldC a name = RElem name (ConstructorFieldNames a) (RIndex name (ConstructorFieldNames a)) -- | Get a field from list of fields fetchField :: forall a name f proxy. AccessFieldC a name => proxy name -> Rec f (ConstructorFieldNames a) -> f name -- | Assign a field to a value assignField :: forall a name f proxy. AccessFieldC a name => proxy name -> f name -> Rec f (ConstructorFieldNames a) -> Rec f (ConstructorFieldNames a) -- | Access to StoreFieldOps flSFO :: FieldLens dt fname ftype -> StoreFieldOps dt fname ftype -- | Build a lens to a direct field of an object. fieldLensADT :: forall dt targetFName targetFType fname. (InstrGetFieldC dt fname, InstrSetFieldC dt fname, GetFieldType dt fname ~ targetFType, AccessFieldC dt fname) => Label fname -> FieldLens dt targetFName targetFType -- | Build a lens to deeper field of an object. fieldLensDeeper :: forall dt targetName targetType fname. (AccessFieldC dt fname, HasFieldOfType dt fname (GetFieldType dt fname), HasField (GetFieldType dt fname) targetName targetType) => Label fname -> FieldLens dt targetName targetType type IsSizeExpr exN n = (exN :~> n, SizeOpHs n) type IsMemExpr exKey exN n = (exKey :~> MemOpKeyHs n, exN :~> n, MemOpHs n) type IsUpdExpr exKey exVal exMap map = (exKey :~> UpdOpKeyHs map, exVal :~> UpdOpParamsHs map, exMap :~> map, UpdOpHs map) type IsGetExpr exKey exMap map = (exKey :~> GetOpKeyHs map, exMap :~> map, GetOpHs map, KnownValue (GetOpValHs map)) type IsSliceExpr exN n = (exN :~> n, SliceOpHs n) type IsConcatListExpr exN n = (exN :~> List n, ConcatOpHs n, KnownValue n) type IsConcatExpr exN1 exN2 n = (exN1 :~> n, exN2 :~> n, ConcatOpHs n) type IsModExpr exN exM n m = (exN :~> n, exM :~> m, EDivOpHs n m, KnownValue (EModOpResHs n m)) type IsDivExpr exN exM n m = (exN :~> n, exM :~> m, EDivOpHs n m, KnownValue (EDivOpResHs n m)) type IsArithExpr exN exM a n m = (exN :~> n, exM :~> m, ArithOpHs a n m, KnownValue (ArithResHs a n m)) type IsUnaryArithExpr exN a n = (exN :~> n, UnaryArithOpHs a n, KnownValue (UnaryArithResHs a n)) class ToExpr' (Decide x) x => ToExpr x type ExprType a = ExprType' (Decide a) a type (:~>) op n = IsExpr op n type IsExpr op n = (ToExpr op, ExprType op ~ n, KnownValue n) type ObjectExpr a = IndigoObjectF (NamedFieldExpr a) a -- | Auxiliary datatype where each field refers to an expression the field -- equals to. It's not recursive one. data NamedFieldExpr a name [NamedFieldExpr] :: {unNamedFieldExpr :: Expr (GetFieldType a name)} -> NamedFieldExpr a name -- | Datatype describing access to an inner fields of object, like -- object !. field1 !. field2 ~. (field3, value3) ~. (field4, -- value4) data ObjectManipulation a [Object] :: Expr a -> ObjectManipulation a [ToField] :: HasField dt fname ftype => ObjectManipulation dt -> Label fname -> ObjectManipulation ftype [SetField] :: HasField dt fname ftype => ObjectManipulation dt -> Label fname -> Expr ftype -> ObjectManipulation dt data Expr a [C] :: NiceConstant a => a -> Expr a [V] :: KnownValue a => Var a -> Expr a [ObjMan] :: ObjectManipulation a -> Expr a [Cast] :: KnownValue a => Expr a -> Expr a [Size] :: SizeOpHs c => Expr c -> Expr Natural [Update] :: (UpdOpHs c, KnownValue c) => Expr c -> Expr (UpdOpKeyHs c) -> Expr (UpdOpParamsHs c) -> Expr c [Add] :: (ArithOpHs Add n m, KnownValue (ArithResHs Add n m)) => Expr n -> Expr m -> Expr (ArithResHs Add n m) [Sub] :: (ArithOpHs Sub n m, KnownValue (ArithResHs Sub n m)) => Expr n -> Expr m -> Expr (ArithResHs Sub n m) [Mul] :: (ArithOpHs Mul n m, KnownValue (ArithResHs Mul n m)) => Expr n -> Expr m -> Expr (ArithResHs Mul n m) [Div] :: (EDivOpHs n m, KnownValue (EDivOpResHs n m)) => Expr n -> Expr m -> Expr (EDivOpResHs n m) [Mod] :: (EDivOpHs n m, KnownValue (EModOpResHs n m)) => Expr n -> Expr m -> Expr (EModOpResHs n m) [Abs] :: (UnaryArithOpHs Abs n, KnownValue (UnaryArithResHs Abs n)) => Expr n -> Expr (UnaryArithResHs Abs n) [Neg] :: (UnaryArithOpHs Neg n, KnownValue (UnaryArithResHs Neg n)) => Expr n -> Expr (UnaryArithResHs Neg n) [Lsl] :: (ArithOpHs Lsl n m, KnownValue (ArithResHs Lsl n m)) => Expr n -> Expr m -> Expr (ArithResHs Lsl n m) [Lsr] :: (ArithOpHs Lsr n m, KnownValue (ArithResHs Lsr n m)) => Expr n -> Expr m -> Expr (ArithResHs Lsr n m) [Eq'] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Neq] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Le] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Lt] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Ge] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Gt] :: NiceComparable n => Expr n -> Expr n -> Expr Bool [Or] :: (ArithOpHs Or n m, KnownValue (ArithResHs Or n m)) => Expr n -> Expr m -> Expr (ArithResHs Or n m) [Xor] :: (ArithOpHs Xor n m, KnownValue (ArithResHs Xor n m)) => Expr n -> Expr m -> Expr (ArithResHs Xor n m) [And] :: (ArithOpHs And n m, KnownValue (ArithResHs And n m)) => Expr n -> Expr m -> Expr (ArithResHs And n m) [Not] :: (UnaryArithOpHs Not n, KnownValue (UnaryArithResHs Not n)) => Expr n -> Expr (UnaryArithResHs Not n) [Int'] :: Expr Natural -> Expr Integer [IsNat] :: Expr Integer -> Expr (Maybe Natural) [Coerce] :: (Castable_ a b, KnownValue b) => Expr a -> Expr b [ForcedCoerce] :: (MichelsonCoercible a b, KnownValue b) => Expr a -> Expr b [Fst] :: KnownValue n => Expr (n, m) -> Expr n [Snd] :: KnownValue m => Expr (n, m) -> Expr m [Pair] :: KnownValue (n, m) => Expr n -> Expr m -> Expr (n, m) [Some] :: KnownValue (Maybe t) => Expr t -> Expr (Maybe t) [None] :: KnownValue t => Expr (Maybe t) [Right'] :: (KnownValue y, KnownValue (Either y x)) => Expr x -> Expr (Either y x) [Left'] :: (KnownValue x, KnownValue (Either y x)) => Expr y -> Expr (Either y x) [Mem] :: MemOpHs c => Expr (MemOpKeyHs c) -> Expr c -> Expr Bool [StGet] :: (StoreHasSubmap store name key value, KnownValue value) => Label name -> Expr key -> Expr store -> Expr (Maybe value) [StInsertNew] :: (StoreHasSubmap store name key value, KnownValue store, IsError err) => Label name -> err -> Expr key -> Expr value -> Expr store -> Expr store [StInsert] :: (StoreHasSubmap store name key value, KnownValue store) => Label name -> Expr key -> Expr value -> Expr store -> Expr store [StMem] :: (StoreHasSubmap store name key val, KnownValue val) => Label name -> Expr key -> Expr store -> Expr Bool [StUpdate] :: (StoreHasSubmap store name key val, KnownValue store) => Label name -> Expr key -> Expr (Maybe val) -> Expr store -> Expr store [StDelete] :: (StoreHasSubmap store name key val, KnownValue store, KnownValue val) => Label name -> Expr key -> Expr store -> Expr store [Wrap] :: (InstrWrapOneC dt name, KnownValue dt) => Label name -> Expr (CtorOnlyField name dt) -> Expr dt [Unwrap] :: (InstrUnwrapC dt name, KnownValue (CtorOnlyField name dt)) => Label name -> Expr dt -> Expr (CtorOnlyField name dt) [Construct] :: (InstrConstructC dt, RMap (ConstructorFieldTypes dt), KnownValue dt) => Rec Expr (ConstructorFieldTypes dt) -> Expr dt [ConstructWithoutNamed] :: ComplexObjectC dt => Rec Expr (FieldTypes dt) -> Expr dt [Name] :: KnownValue (name :! t) => Label name -> Expr t -> Expr (name :! t) [UnName] :: KnownValue t => Label name -> Expr (name :! t) -> Expr t [EmptySet] :: (NiceComparable key, KnownValue (Set key)) => Expr (Set key) [Get] :: (GetOpHs c, KnownValue (Maybe (GetOpValHs c)), KnownValue (GetOpValHs c)) => Expr (GetOpKeyHs c) -> Expr c -> Expr (Maybe (GetOpValHs c)) [EmptyMap] :: (KnownValue value, NiceComparable key, KnownValue (Map key value)) => Expr (Map key value) [EmptyBigMap] :: (KnownValue value, NiceComparable key, KnownValue (BigMap key value)) => Expr (BigMap key value) [Pack] :: NicePackedValue a => Expr a -> Expr ByteString [Unpack] :: NiceUnpackedValue a => Expr ByteString -> Expr (Maybe a) [Cons] :: KnownValue (List a) => Expr a -> Expr (List a) -> Expr (List a) [Nil] :: KnownValue a => Expr (List a) [Concat] :: (ConcatOpHs c, KnownValue c) => Expr c -> Expr c -> Expr c [Concat'] :: (ConcatOpHs c, KnownValue c) => Expr (List c) -> Expr c [Slice] :: (SliceOpHs c, KnownValue c) => Expr Natural -> Expr Natural -> Expr c -> Expr (Maybe c) [Contract] :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p, ToTAddress p addr, ToT addr ~ ToT Address) => Expr addr -> Expr (Maybe (ContractRef p)) [Self] :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p) => Expr (ContractRef p) [ContractAddress] :: Expr (ContractRef p) -> Expr Address [ContractCallingUnsafe] :: NiceParameter arg => EpName -> Expr Address -> Expr (Maybe (ContractRef arg)) [RunFutureContract] :: NiceParameter p => Expr (FutureContract p) -> Expr (Maybe (ContractRef p)) [ImplicitAccount] :: Expr KeyHash -> Expr (ContractRef ()) [ConvertEpAddressToContract] :: NiceParameter p => Expr EpAddress -> Expr (Maybe (ContractRef p)) [MakeView] :: KnownValue (View a r) => Expr a -> Expr (ContractRef r) -> Expr (View a r) [MakeVoid] :: KnownValue (Void_ a b) => Expr a -> Expr (Lambda b b) -> Expr (Void_ a b) [CheckSignature] :: Expr PublicKey -> Expr Signature -> Expr ByteString -> Expr Bool [Sha256] :: Expr ByteString -> Expr ByteString [Sha512] :: Expr ByteString -> Expr ByteString [Blake2b] :: Expr ByteString -> Expr ByteString [HashKey] :: Expr PublicKey -> Expr KeyHash [ChainId] :: Expr ChainId [Now] :: Expr Timestamp [Amount] :: Expr Mutez [Balance] :: Expr Mutez [Sender] :: Expr Address [Exec] :: KnownValue b => Expr a -> Expr (Lambda a b) -> Expr b [NonZero] :: (NonZero n, KnownValue (Maybe n)) => Expr n -> Expr (Maybe n) toExpr :: forall a. ToExpr a => a -> Expr (ExprType a) -- | ObjManipulationRes represents a postponed compilation of -- ObjectManipulation datatype. When ObjectManipulation is -- being compiled we are trying to put off the generation of code for -- work with an object because we can just go to a deeper field without -- its "materialization" onto stack. data ObjManipulationRes inp a [StillObject] :: ObjectExpr a -> ObjManipulationRes inp a [OnStack] :: IndigoState inp (a & inp) -> ObjManipulationRes inp a compileExpr :: forall a inp. Expr a -> IndigoState inp (a & inp) namedToExpr :: NamedFieldObj x name -> Expr (GetFieldType x name) -- | This function might look cumbersome but basically it either goes -- deeper to an inner field or generates Lorentz code. runObjectManipulation :: DecomposedObjects -> ObjectManipulation x -> ObjManipulationRes inp x ternaryOp :: KnownValue res => Expr n -> Expr m -> Expr l -> ((n & (m & (l & inp))) :-> (res & inp)) -> IndigoState inp (res & inp) binaryOp :: KnownValue res => Expr n -> Expr m -> ((n & (m & inp)) :-> (res & inp)) -> IndigoState inp (res & inp) unaryOp :: KnownValue res => Expr n -> ((n & inp) :-> (res & inp)) -> IndigoState inp (res & inp) nullaryOp :: KnownValue res => (inp :-> (res : inp)) -> IndigoState inp (res : inp) ternaryOpFlat :: Expr n -> Expr m -> Expr l -> ((n & (m & (l & inp))) :-> inp) -> IndigoState inp inp binaryOpFlat :: Expr n -> Expr m -> ((n & (m & inp)) :-> inp) -> IndigoState inp inp unaryOpFlat :: Expr n -> ((n & inp) :-> inp) -> IndigoState inp inp nullaryOpFlat :: (inp :-> inp) -> IndigoState inp inp -- | Datatype representing decomposition of Expr. data ExprDecomposition inp a [ExprFields] :: Rec Expr (FieldTypes a) -> ExprDecomposition inp a [Deconstructed] :: IndigoState inp (FieldTypes a ++ inp) -> ExprDecomposition inp a -- | For given element on stack, generate code which decomposes it to list -- of its deep non-decomposable fields. Clean up code of -- SomeIndigoState composes the value back. deepDecomposeCompose :: forall a inp. IsObject a => SIS' (a & inp) (Object a) -- | Decompose (shallowly) an expression to list of its direct fields. decomposeExpr :: ComplexObjectC a => DecomposedObjects -> Expr a -> ExprDecomposition inp a remove :: (ExprRemovable c, exStruct :~> c, exKey :~> UpdOpKeyHs c) => exKey -> exStruct -> Expr c insert :: (ExprInsertable c insParam, ex :~> c) => insParam -> ex -> Expr c empty :: (ExprMagma c, NiceComparable (UpdOpKeyHs c), KnownValue c) => Expr c constExpr :: NiceConstant a => a -> Expr a -- | Create an expression holding a variable. varExpr :: KnownValue a => Var a -> Expr a cast :: ex :~> a => ex -> Expr a add :: IsArithExpr exN exM Add n m => exN -> exM -> Expr (ArithResHs Add n m) (+) :: IsArithExpr exN exM Add n m => exN -> exM -> Expr (ArithResHs Add n m) infixl 6 + sub :: IsArithExpr exN exM Sub n m => exN -> exM -> Expr (ArithResHs Sub n m) (-) :: IsArithExpr exN exM Sub n m => exN -> exM -> Expr (ArithResHs Sub n m) infixl 6 - mul :: IsArithExpr exN exM Mul n m => exN -> exM -> Expr (ArithResHs Mul n m) (*) :: IsArithExpr exN exM Mul n m => exN -> exM -> Expr (ArithResHs Mul n m) infixl 7 * div :: IsDivExpr exN exM n m => exN -> exM -> Expr (EDivOpResHs n m) (/) :: IsDivExpr exN exM n m => exN -> exM -> Expr (EDivOpResHs n m) infixl 7 / mod :: IsModExpr exN exM n m => exN -> exM -> Expr (EModOpResHs n m) (%) :: IsModExpr exN exM n m => exN -> exM -> Expr (EModOpResHs n m) infixl 7 % abs :: IsUnaryArithExpr exN Abs n => exN -> Expr (UnaryArithResHs Abs n) neg :: IsUnaryArithExpr exN Neg n => exN -> Expr (UnaryArithResHs Neg n) eq :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool (==) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 == neq :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool (/=) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 /= lt :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool (<) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 < gt :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool (>) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 > le :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool (<=) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 <= ge :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool (>=) :: (NiceComparable n, c :~> n, c1 :~> n) => c -> c1 -> Expr Bool infix 4 >= isNat :: ex :~> Integer => ex -> Expr (Maybe Natural) toInt :: ex :~> Natural => ex -> Expr Integer nonZero :: (ex :~> n, NonZero n, KnownValue (Maybe n)) => ex -> Expr (Maybe n) -- | Convert between types that have the same Michelson representation and -- an explicit permission for that in the face of CanCastTo -- constraint. coerce :: forall b a ex. (Castable_ a b, KnownValue b, ex :~> a) => ex -> Expr b -- | Convert between expressions of types that have the same Michelson -- representation. forcedCoerce :: forall b a ex. (MichelsonCoercible a b, KnownValue b, ex :~> a) => ex -> Expr b lsl :: IsArithExpr exN exM Lsl n m => exN -> exM -> Expr (ArithResHs Lsl n m) (<<<) :: IsArithExpr exN exM Lsl n m => exN -> exM -> Expr (ArithResHs Lsl n m) infixl 8 <<< lsr :: IsArithExpr exN exM Lsr n m => exN -> exM -> Expr (ArithResHs Lsr n m) (>>>) :: IsArithExpr exN exM Lsr n m => exN -> exM -> Expr (ArithResHs Lsr n m) infixl 8 >>> or :: IsArithExpr exN exM Or n m => exN -> exM -> Expr (ArithResHs Or n m) (||) :: IsArithExpr exN exM Or n m => exN -> exM -> Expr (ArithResHs Or n m) infixr 2 || and :: IsArithExpr exN exM And n m => exN -> exM -> Expr (ArithResHs And n m) (&&) :: IsArithExpr exN exM And n m => exN -> exM -> Expr (ArithResHs And n m) infixr 3 && xor :: IsArithExpr exN exM Xor n m => exN -> exM -> Expr (ArithResHs Xor n m) (^) :: IsArithExpr exN exM Xor n m => exN -> exM -> Expr (ArithResHs Xor n m) infixr 2 ^ not :: IsUnaryArithExpr exN Not n => exN -> Expr (UnaryArithResHs Not n) pack :: (ex :~> a, NicePackedValue a) => ex -> Expr ByteString unpack :: (NiceUnpackedValue a, exb :~> ByteString) => exb -> Expr (Maybe a) pair :: (ex1 :~> n, ex2 :~> m, KnownValue (n, m)) => ex1 -> ex2 -> Expr (n, m) car :: (op :~> (n, m), KnownValue n) => op -> Expr n fst :: (op :~> (n, m), KnownValue n) => op -> Expr n cdr :: (op :~> (n, m), KnownValue m) => op -> Expr m snd :: (op :~> (n, m), KnownValue m) => op -> Expr m some :: (ex :~> t, KnownValue (Maybe t)) => ex -> Expr (Maybe t) none :: KnownValue t => Expr (Maybe t) right :: (ex :~> x, KnownValue y, KnownValue (Either y x)) => ex -> Expr (Either y x) left :: (ex :~> y, KnownValue x, KnownValue (Either y x)) => ex -> Expr (Either y x) slice :: (an :~> Natural, bn :~> Natural, IsSliceExpr ex c) => (an, bn) -> ex -> Expr (Maybe c) concat :: IsConcatExpr exN1 exN2 n => exN1 -> exN2 -> Expr n (<>) :: IsConcatExpr exN1 exN2 n => exN1 -> exN2 -> Expr n infixr 6 <> cons :: (ex1 :~> a, ex2 :~> List a) => ex1 -> ex2 -> Expr (List a) (.:) :: (ex1 :~> a, ex2 :~> List a) => ex1 -> ex2 -> Expr (List a) infixr 5 .: concatAll :: IsConcatListExpr exN n => exN -> Expr n nil :: KnownValue a => Expr (List a) get :: IsGetExpr exKey exMap map => exKey -> exMap -> Expr (Maybe (GetOpValHs map)) update :: IsUpdExpr exKey exVal exMap map => (exKey, exVal) -> exMap -> Expr map mem :: IsMemExpr exKey exN n => exKey -> exN -> Expr Bool size :: IsSizeExpr exN n => exN -> Expr Natural (#:) :: IsGetExpr exKey exMap map => exMap -> exKey -> Expr (Maybe (GetOpValHs map)) infixl 8 #: (!:) :: IsUpdExpr exKey exVal exMap map => exMap -> (exKey, exVal) -> Expr map infixl 8 !: (+:) :: (ExprInsertable c exParam, exStructure :~> c) => exStructure -> exParam -> Expr c infixl 8 +: (-:) :: (ExprRemovable c, exStruct :~> c, exKey :~> UpdOpKeyHs c) => exStruct -> exKey -> Expr c infixl 8 -: (?:) :: IsMemExpr exKey exN n => exN -> exKey -> Expr Bool infixl 8 ?: emptyBigMap :: (KnownValue value, NiceComparable key, KnownValue (BigMap key value)) => Expr (BigMap key value) emptyMap :: (KnownValue value, NiceComparable key, KnownValue (Map key value)) => Expr (Map key value) emptySet :: (NiceComparable key, KnownValue (Set key)) => Expr (Set key) stGet :: (StoreHasSubmap store name key value, KnownValue value, exKey :~> key, exStore :~> store) => exStore -> (Label name, exKey) -> Expr (Maybe value) (#@) :: (StoreHasSubmap store name key value, KnownValue value, exKey :~> key, exStore :~> store) => exStore -> (Label name, exKey) -> Expr (Maybe value) infixr 8 #@ stUpdate :: (StoreHasSubmap store name key value, exKey :~> key, exVal :~> Maybe value, exStore :~> store) => exStore -> (Label name, exKey, exVal) -> Expr store (!@) :: (StoreHasSubmap store name key value, exKey :~> key, exVal :~> Maybe value, exStore :~> store) => exStore -> (Label name, exKey, exVal) -> Expr store infixl 8 !@ stInsert :: (StoreHasSubmap store name key value, exKey :~> key, exVal :~> value, exStore :~> store) => exStore -> (Label name, exKey, exVal) -> Expr store (+@) :: (StoreHasSubmap store name key value, exKey :~> key, exVal :~> value, exStore :~> store) => exStore -> (Label name, exKey, exVal) -> Expr store infixr 8 +@ stInsertNew :: (StoreHasSubmap store name key value, IsError err, exKey :~> key, exVal :~> value, exStore :~> store) => exStore -> (Label name, err, exKey, exVal) -> Expr store (++@) :: (StoreHasSubmap store name key value, IsError err, exKey :~> key, exVal :~> value, exStore :~> store) => exStore -> (Label name, err, exKey, exVal) -> Expr store infixr 8 ++@ stDelete :: (StoreHasSubmap store name key value, KnownValue value, exKey :~> key, exStore :~> store) => exStore -> (Label name, exKey) -> Expr store (-@) :: (StoreHasSubmap store name key value, KnownValue value, exKey :~> key, exStore :~> store) => exStore -> (Label name, exKey) -> Expr store infixl 8 -@ stMem :: (StoreHasSubmap store name key value, KnownValue value, exKey :~> key, exStore :~> store) => exStore -> (Label name, exKey) -> Expr Bool (?@) :: (StoreHasSubmap store name key value, KnownValue value, exKey :~> key, exStore :~> store) => exStore -> (Label name, exKey) -> Expr Bool infixl 8 ?@ wrap :: (InstrWrapOneC dt name, exField :~> CtorOnlyField name dt, KnownValue dt) => Label name -> exField -> Expr dt unwrap :: (InstrUnwrapC dt name, exDt :~> dt, KnownValue (CtorOnlyField name dt)) => Label name -> exDt -> Expr (CtorOnlyField name dt) (#!) :: (HasField dt name ftype, exDt :~> dt) => exDt -> Label name -> Expr ftype infixl 8 #! (!!) :: (HasField dt name ftype, exDt :~> dt, exFld :~> ftype) => exDt -> (Label name, exFld) -> Expr dt infixl 8 !! name :: (ex :~> t, KnownValue (name :! t)) => Label name -> ex -> Expr (name :! t) unName :: (ex :~> (name :! t), KnownValue t) => Label name -> ex -> Expr t (!~) :: (ex :~> t, KnownValue (name :! t)) => ex -> Label name -> Expr (name :! t) infixl 8 !~ (#~) :: (ex :~> (name :! t), KnownValue t) => ex -> Label name -> Expr t infixl 8 #~ construct :: (InstrConstructC dt, KnownValue dt, RMap (ConstructorFieldTypes dt), fields ~ Rec Expr (ConstructorFieldTypes dt), RecFromTuple fields) => IsoRecTuple fields -> Expr dt constructRec :: (InstrConstructC dt, RMap (ConstructorFieldTypes dt), KnownValue dt) => Rec Expr (ConstructorFieldTypes dt) -> Expr dt contract :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p, ToTAddress p addr, ToT addr ~ ToT Address, exAddr :~> addr) => exAddr -> Expr (Maybe (ContractRef p)) self :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p) => Expr (ContractRef p) contractAddress :: exc :~> ContractRef p => exc -> Expr Address contractCallingUnsafe :: (NiceParameter arg, exAddr :~> Address) => EpName -> exAddr -> Expr (Maybe (ContractRef arg)) contractCallingString :: (NiceParameter arg, exAddr :~> Address) => MText -> exAddr -> Expr (Maybe (ContractRef arg)) runFutureContract :: (NiceParameter p, conExpr :~> FutureContract p) => conExpr -> Expr (Maybe (ContractRef p)) implicitAccount :: exkh :~> KeyHash => exkh -> Expr (ContractRef ()) convertEpAddressToContract :: (NiceParameter p, epExpr :~> EpAddress) => epExpr -> Expr (Maybe (ContractRef p)) makeView :: (KnownValue (View a r), exa :~> a, exCRef :~> ContractRef r) => exa -> exCRef -> Expr (View a r) makeVoid :: (KnownValue (Void_ a b), exa :~> a, exCRef :~> Lambda b b) => exa -> exCRef -> Expr (Void_ a b) now :: Expr Timestamp amount :: Expr Mutez sender :: Expr Address checkSignature :: (pkExpr :~> PublicKey, sigExpr :~> Signature, hashExpr :~> ByteString) => pkExpr -> sigExpr -> hashExpr -> Expr Bool sha256 :: hashExpr :~> ByteString => hashExpr -> Expr ByteString sha512 :: hashExpr :~> ByteString => hashExpr -> Expr ByteString blake2b :: hashExpr :~> ByteString => hashExpr -> Expr ByteString hashKey :: keyExpr :~> PublicKey => keyExpr -> Expr KeyHash chainId :: Expr ChainId balance :: Expr Mutez type ReturnableValue ret = ReturnableValue' (ClassifyReturnValue ret) ret type RetVars ret = RetVars' (ClassifyReturnValue ret) ret -- | Type of a contract that can be compiled to Lorentz with -- compileIndigoContract. type IndigoContract param st = (HasStorage st, HasSideEffects) => Var param -> IndigoM () -- | Monad for writing your contracts in. newtype IndigoM a IndigoM :: Program (StatementF IndigoM) a -> IndigoM a [unIndigoM] :: IndigoM a -> Program (StatementF IndigoM) a -- | This is freer monad (in other words operational monad). -- -- It preserves the structure of the computation performed over it, -- including return and bind operations. This was -- introduced to be able to iterate over Indigo code and optimize/analyze -- it. -- -- You can read a clearer description of this construction in "The Book -- of Monads" by Alejandro Serrano. There is a chapter about free monads, -- specifically about Freer you can read at page 259. There is -- "operational" package which contains transformer of this monad and -- auxiliary functions but it's not used because we are using only some -- basics of it. data Program instr a [Done] :: a -> Program instr a [Instr] :: instr a -> Program instr a [Bind] :: Program instr a -> (a -> Program instr b) -> Program instr b -- | Traverse over Freer structure and interpret it interpretProgram :: Monad m => (forall x. instr x -> m x) -> Program instr a -> m a -- | Specialiasation of compileIndigoImpl without var -- decompositions. compileIndigo :: forall n inp a. (AreIndigoParams n inp, KnownValue a, Default (StackVars inp)) => IndigoWithParams n inp a -> inp :-> inp -- | Compile Indigo code to Lorentz contract. Drop elements from the stack -- to return only [Operation] and storage. compileIndigoContract :: forall param st. (KnownValue param, IsObject st) => IndigoContract param st -> ContractCode param st type IndigoEntrypoint param = param -> IndigoProcedure -- | Utility type for an IndigoM that does not modify the stack -- (only the values in it) and returns nothing. type IndigoProcedure = IndigoM () -- | Utility type for an IndigoM that adds one element to the stack -- and returns a variable pointing at it. type IndigoFunction ret = IndigoM (RetVars ret) liftIndigoState :: (forall inp. SomeIndigoState inp) -> IndigoM () -- | Create a new variable with the result of the given expression as its -- initial value. new :: IsExpr ex x => ex -> IndigoM (Var x) -- | Set the given variable to the result of the given expression. setVar :: IsExpr ex x => Var x -> ex -> IndigoM () (=:) :: IsExpr ex x => Var x -> ex -> IndigoM () infixr 0 =: setField :: (ex :~> ftype, IsObject dt, IsObject ftype, HasField dt fname ftype) => Var dt -> Label fname -> ex -> IndigoM () (+=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Add n m, ArithResHs Add n m ~ m) => Var m -> ex1 -> IndigoM () (-=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Sub n m, ArithResHs Sub n m ~ m) => Var m -> ex1 -> IndigoM () (*=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Mul n m, ArithResHs Mul n m ~ m) => Var m -> ex1 -> IndigoM () (||=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Or n m, ArithResHs Or n m ~ m) => Var m -> ex1 -> IndigoM () (&&=) :: (IsExpr ex1 n, IsObject m, ArithOpHs And n m, ArithResHs And n m ~ m) => Var m -> ex1 -> IndigoM () (^=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Xor n m, ArithResHs Xor n m ~ m) => Var m -> ex1 -> IndigoM () (<<<=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Lsl n m, ArithResHs Lsl n m ~ m) => Var m -> ex1 -> IndigoM () (>>>=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Lsr n m, ArithResHs Lsr n m ~ m) => Var m -> ex1 -> IndigoM () -- | Sets a storage field to a new value. setStorageField :: forall store name ftype ex. (HasStorage store, ex :~> ftype, IsObject store, IsObject ftype, HasField store name ftype) => Label name -> ex -> IndigoM () -- | Updates a storage field by using an updating IndigoM. updateStorageField :: forall store ftype fname fex. (HasStorage store, fex :~> ftype, HasField store fname ftype, IsObject store, IsObject ftype) => Label fname -> (Var ftype -> IndigoM fex) -> IndigoM () -- | Get a field from the storage, returns a variable. -- -- Note that the storage type almost always needs to be specified. getStorageField :: forall store ftype fname. (HasStorage store, HasField store fname ftype) => Label fname -> IndigoM (Var ftype) if_ :: forall a b ex. (IfConstraint a b, ex :~> Bool) => ex -> IndigoM a -> IndigoM b -> IndigoM (RetVars a) -- | Run the instruction when the condition is met, do nothing otherwise. when :: exc :~> Bool => exc -> IndigoM () -> IndigoM () -- | Reverse of when. unless :: exc :~> Bool => exc -> IndigoM () -> IndigoM () ifSome :: forall x a b ex. (KnownValue x, ex :~> Maybe x, IfConstraint a b) => ex -> (Var x -> IndigoM a) -> IndigoM b -> IndigoM (RetVars a) ifNone :: forall x a b ex. (KnownValue x, ex :~> Maybe x, IfConstraint a b) => ex -> IndigoM b -> (Var x -> IndigoM a) -> IndigoM (RetVars a) -- | Run the instruction when the given expression returns Just a -- value, do nothing otherwise. whenSome :: forall x exa. (KnownValue x, exa :~> Maybe x) => exa -> (Var x -> IndigoM ()) -> IndigoM () -- | Run the instruction when the given expression returns Nothing, -- do nothing otherwise. whenNone :: forall x exa. (KnownValue x, exa :~> Maybe x) => exa -> IndigoM () -> IndigoM () ifRight :: forall x y a b ex. (KnownValue x, KnownValue y, ex :~> Either y x, IfConstraint a b) => ex -> (Var x -> IndigoM a) -> (Var y -> IndigoM b) -> IndigoM (RetVars a) ifLeft :: forall x y a b ex. (KnownValue x, KnownValue y, ex :~> Either y x, IfConstraint a b) => ex -> (Var y -> IndigoM b) -> (Var x -> IndigoM a) -> IndigoM (RetVars a) whenRight :: forall x y ex. (KnownValue x, KnownValue y, ex :~> Either y x) => ex -> (Var x -> IndigoM ()) -> IndigoM () whenLeft :: forall x y ex. (KnownValue x, KnownValue y, ex :~> Either y x) => ex -> (Var y -> IndigoM ()) -> IndigoM () ifCons :: forall x a b ex. (KnownValue x, ex :~> List x, IfConstraint a b) => ex -> (Var x -> Var (List x) -> IndigoM a) -> IndigoM b -> IndigoM (RetVars a) -- | A case statement for indigo. See examples for a sample usage. caseRec :: forall dt guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) dt ret clauses, guard :~> dt) => guard -> clauses -> IndigoM (RetVars ret) -- | caseRec for tuples. case_ :: forall dt guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) dt ret clauses, RecFromTuple clauses, guard :~> dt) => guard -> IsoRecTuple clauses -> IndigoM (RetVars ret) -- | caseRec for pattern-matching on parameter. entryCaseRec :: forall dt entrypointKind guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) dt ret clauses, DocumentEntrypoints entrypointKind dt, guard :~> dt) => Proxy entrypointKind -> guard -> clauses -> IndigoM (RetVars ret) -- | entryCaseRec for tuples. entryCase :: forall dt entrypointKind guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) dt ret clauses, RecFromTuple clauses, DocumentEntrypoints entrypointKind dt, guard :~> dt) => Proxy entrypointKind -> guard -> IsoRecTuple clauses -> IndigoM (RetVars ret) entryCaseSimple :: forall cp guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) cp ret clauses, RecFromTuple clauses, DocumentEntrypoints PlainEntrypointsKind cp, NiceParameterFull cp, RequireFlatParamEps cp, guard :~> cp) => guard -> IsoRecTuple clauses -> IndigoM (RetVars ret) -- | An alias for #= kept only for backward compatibility. -- | Deprecated: use #= instead (//->) :: (name ~ AppendSymbol "c" ctor, KnownValue x, ScopeCodeGen retBr, ret ~ RetExprs retBr, RetOutStack ret ~ RetOutStack retBr) => Label name -> (Var x -> IndigoM retBr) -> IndigoMCaseClauseL IndigoM ret ('CaseClauseParam ctor ('OneField x)) infixr 0 //-> -- | Use this instead of /->. -- -- This operator is like /-> but wraps a body into -- IndigoAnyOut, which is needed for two reasons: to allow -- having any output stack and to allow returning not exactly the same -- values. -- -- It has the added benefit of not being an arrow, so in case the body of -- the clause is a lambda there won't be several. (#=) :: (name ~ AppendSymbol "c" ctor, KnownValue x, ScopeCodeGen retBr, ret ~ RetExprs retBr, RetOutStack ret ~ RetOutStack retBr) => Label name -> (Var x -> IndigoM retBr) -> IndigoMCaseClauseL IndigoM ret ('CaseClauseParam ctor ('OneField x)) infixr 0 #= scope :: forall a. ScopeCodeGen a => IndigoM a -> IndigoFunction a -- | Alias for scope we use in the tutorial. defFunction :: forall a. ScopeCodeGen a => IndigoM a -> IndigoFunction a -- | A more specific version of defFunction meant to more easily -- create IndigoContracts. -- -- Used in the tutorial. The HasSideEffects constraint is -- specified to avoid the warning for redundant constraints. defContract :: (HasSideEffects => IndigoM ()) -> HasSideEffects => IndigoProcedure -- | Family of defNamed*LambdaN functions put an Indigo -- computation on the stack to later call it avoiding code duplication. -- defNamed*LambdaN takes a computation with N arguments. This -- family of functions add some overhead to contract byte size for every -- call of the function, therefore, DON'T use defNamed*LambdaN -- if: * Your computation is pretty small. It would be cheaper just to -- inline it, so use defFunction. * Your computation is called -- only once, in this case also use defFunction. -- -- Also, pay attention that defNamed*LambdaN accepts a string -- that is a name of the passed computation. Be careful and make sure -- that all declared computations have different names. Later the name -- will be removed. -- -- Pay attention, that lambda argument will be evaluated to variable -- before lambda calling. -- -- TODO Approach with lambda names has critical pitfall: in case if a -- function takes Label name, lambda body won't be regenerated -- for every different label. So be carefully, this will be fixed in a -- following issue. defNamedEffLambda1 :: forall st argExpr res. (ToExpr argExpr, Typeable res, ExecuteLambdaEff1C st (ExprType argExpr) res, CreateLambdaEff1C st (ExprType argExpr) res) => String -> (Var (ExprType argExpr) -> IndigoM res) -> argExpr -> IndigoM (RetVars res) -- | Like defNamedEffLambda1 but doesn't make side effects. defNamedLambda1 :: forall st argExpr res. (ToExpr argExpr, Typeable res, ExecuteLambda1C st (ExprType argExpr) res, CreateLambda1C st (ExprType argExpr) res) => String -> (Var (ExprType argExpr) -> IndigoM res) -> argExpr -> IndigoM (RetVars res) -- | Like defNamedLambda1 but doesn't take an argument. defNamedLambda0 :: forall st res. (Typeable res, ExecuteLambda1C st () res, CreateLambda1C st () res) => String -> IndigoM res -> IndigoM (RetVars res) -- | Like defNamedEffLambda1 but doesn't modify storage and doesn't make -- side effects. defNamedPureLambda1 :: forall argExpr res. (ToExpr argExpr, Typeable res, ExecuteLambdaPure1C (ExprType argExpr) res, CreateLambdaPure1C (ExprType argExpr) res) => String -> (Var (ExprType argExpr) -> IndigoM res) -> argExpr -> IndigoM (RetVars res) -- | While statement. while :: forall ex. ex :~> Bool => ex -> IndigoM () -> IndigoM () whileLeft :: forall x y ex. (ex :~> Either y x, KnownValue y, KnownValue x) => ex -> (Var y -> IndigoM ()) -> IndigoM (Var x) -- | For statements to iterate over a container. forEach :: forall a e. (IterOpHs a, KnownValue (IterOpElHs a), e :~> a) => e -> (Var (IterOpElHs a) -> IndigoM ()) -> IndigoM () -- | Put a document item. doc :: DocItem di => di -> IndigoM () -- | Group documentation built in the given piece of code into a block -- dedicated to one thing, e.g. to one entrypoint. docGroup :: DocGrouping -> IndigoM () -> IndigoM () -- | Insert documentation of the contract's storage type. The type should -- be passed using type applications. docStorage :: forall storage. TypeHasDoc storage => IndigoM () -- | Give a name to the given contract. Apply it to the whole contract -- code. contractName :: Text -> IndigoM () -> IndigoM () -- | Attach general info to the given contract. contractGeneral :: IndigoM () -> IndigoM () -- | Attach default general info to the contract documentation. contractGeneralDefault :: IndigoM () -- | Indigo version for the homonym Lorentz function. finalizeParamCallingDoc :: forall param. (ToExpr param, NiceParameterFull (ExprType param), RequireSumType (ExprType param), HasCallStack) => (Var (ExprType param) -> IndigoM ()) -> param -> IndigoM () -- | Put a DDescription doc item. description :: Markdown -> IndigoM () -- | Put a DAnchor doc item. anchor :: Text -> IndigoM () -- | Put a DEntrypointExample doc item. example :: forall a. NiceParameter a => a -> IndigoM () selfCalling :: forall p mname. (NiceParameterFull p, KnownValue (GetEntrypointArgCustom p mname)) => EntrypointRef mname -> IndigoM (Var (ContractRef (GetEntrypointArgCustom p mname))) contractCalling :: forall cp epRef epArg addr exAddr. (HasEntrypointArg cp epRef epArg, ToTAddress cp addr, ToT addr ~ ToT Address, exAddr :~> addr, KnownValue epArg) => epRef -> exAddr -> IndigoM (Var (Maybe (ContractRef epArg))) transferTokens :: (IsExpr exp p, IsExpr exm Mutez, IsExpr exc (ContractRef p), NiceParameter p, HasSideEffects) => exp -> exm -> exc -> IndigoM () setDelegate :: (HasSideEffects, IsExpr ex (Maybe KeyHash)) => ex -> IndigoM () -- | Create contract using default compilation options for Lorentz -- compiler. -- -- See Lorentz.Run. createContract :: (IsObject st, IsExpr exk (Maybe KeyHash), IsExpr exm Mutez, IsExpr exs st, NiceStorage st, NiceParameterFull param, HasSideEffects) => (HasStorage st => Var param -> IndigoM ()) -> exk -> exm -> exs -> IndigoM (Var Address) -- | Create contract from raw Lorentz Contract. createLorentzContract :: (IsObject st, IsExpr exk (Maybe KeyHash), IsExpr exm Mutez, IsExpr exs st, NiceStorage st, NiceParameterFull param, HasSideEffects) => Contract param st -> exk -> exm -> exs -> IndigoM (Var Address) failWith :: forall ret a ex. (IsExpr ex a, ReturnableValue ret) => ex -> IndigoM (RetVars ret) failCustom :: forall ret tag err ex. (ReturnableValue ret, err ~ ErrorArg tag, CustomErrorHasDoc tag, NiceConstant err, ex :~> err) => Label tag -> ex -> IndigoM (RetVars ret) failCustom_ :: forall ret tag notVoidErrorMsg. (ReturnableValue ret, RequireNoArgError tag notVoidErrorMsg, CustomErrorHasDoc tag) => Label tag -> IndigoM (RetVars ret) failUnexpected_ :: forall ret. ReturnableValue ret => MText -> IndigoM (RetVars ret) assert :: forall x ex. (IsError x, IsExpr ex Bool) => x -> ex -> IndigoM () assertCustom :: forall tag err errEx ex. (err ~ ErrorArg tag, CustomErrorHasDoc tag, NiceConstant err, IsExpr errEx err, IsExpr ex Bool) => Label tag -> errEx -> ex -> IndigoM () assertCustom_ :: forall tag notVoidErrorMsg ex. (RequireNoArgError tag notVoidErrorMsg, CustomErrorHasDoc tag, IsExpr ex Bool) => Label tag -> ex -> IndigoM () assertSome :: forall x err ex. (IsError err, KnownValue x, ex :~> Maybe x) => err -> ex -> IndigoM () assertNone :: forall x err ex. (IsError err, KnownValue x, ex :~> Maybe x) => err -> ex -> IndigoM () assertRight :: forall x y err ex. (IsError err, KnownValue x, KnownValue y, ex :~> Either y x) => err -> ex -> IndigoM () assertLeft :: forall x y err ex. (IsError err, KnownValue x, KnownValue y, ex :~> Either y x) => err -> ex -> IndigoM () -- | Add a comment in a generated Michelson code justComment :: Text -> IndigoM () -- | Add a comment in a generated Michelson code comment :: CommentType -> IndigoM () -- | Add a comment before and after the given Indigo function code. The -- first argument is the name of the function. commentAroundFun :: Text -> IndigoM a -> IndigoM a -- | Add a comment before and after the given Indigo statement code. The -- first argument is the name of the statement. commentAroundStmt :: Text -> IndigoM a -> IndigoM a -- | Pretty-print an Indigo contract into Michelson code. printIndigoContract :: forall param st. (IsObject st, NiceParameterFull param, NiceStorage st) => Bool -> IndigoContract param st -> LText -- | Generate an Indigo contract documentation. renderIndigoDoc :: forall param st. (IsObject st, NiceParameterFull param) => IndigoContract param st -> LText -- | Prints the pretty-printed Michelson code of an Indigo contract to the -- standard output. -- -- This is intended to be easy to use for newcomers. printAsMichelson :: forall param st m. (IsObject st, NiceParameterFull param, NiceStorage st, MonadIO m) => IndigoContract param st -> m () -- | Saves the pretty-printed Michelson code of an Indigo contract to the -- given file. -- -- This is intended to be easy to use for newcomers. saveAsMichelson :: forall param st m. (IsObject st, NiceParameterFull param, NiceStorage st, MonadIO m, MonadMask m) => IndigoContract param st -> FilePath -> m () -- | Print the generated documentation to the standard output. printDocumentation :: forall param st m. (IsObject st, NiceParameterFull param, MonadIO m) => IndigoContract param st -> m () -- | Save the generated documentation to the given file. saveDocumentation :: forall param st m. (IsObject st, NiceParameterFull param, MonadIO m, MonadMask m) => IndigoContract param st -> FilePath -> m () -- | Defines semantics of if ... then ... else ... construction -- for Indigo where the predicate is a generic exa for which -- IsExpr exa Bool holds ifThenElse :: (IfConstraint a b, IsExpr exa Bool) => exa -> IndigoM a -> IndigoM b -> IndigoM (RetVars a) -- | Numerical literal disambiguation value for a Natural, see -- fromInteger. nat :: NumType 'Nat Natural -- | Numerical literal disambiguation value for an Integer, see -- fromInteger. int :: NumType 'Int Integer -- | Numerical literal disambiguation value for a Mutez, see -- fromInteger. mutez :: NumType 'Mtz Mutez -- | Defines numerical literals resolution for Indigo. -- -- It is implemented with an additional NumType argument that -- disambiguates the resulting type. This allows, for example, 1 -- int to be resolved to 1 :: Integer. fromInteger :: Integer -> NumType n t -> t -- | Indigo version of the view macro. It takes a function from -- view argument to view result and a View structure that -- typically comes from a top-level case. view_ :: forall arg r viewExpr exr. (KnownValue arg, NiceParameter r, viewExpr :~> View arg r, exr :~> r, HasSideEffects) => (Expr arg -> IndigoM exr) -> viewExpr -> IndigoM () -- | Flipped version of view_ that is present due to the common -- appearance of flip view parameter $ instr construction. -- -- Semantically we "project" the given parameter inside the body of the -- View construction. project :: forall arg r viewExpr exr. (KnownValue arg, NiceParameter r, viewExpr :~> View arg r, exr :~> r, HasSideEffects) => viewExpr -> (Expr arg -> IndigoM exr) -> IndigoM () -- | Indigo version of the void macro. void_ :: forall a b voidExpr exb. (KnownValue a, IsError (VoidResult b), NiceConstant b, voidExpr :~> Void_ a b, exb :~> b) => (Expr a -> IndigoM exb) -> voidExpr -> IndigoM () -- | Flipped version of void_ that is present due to the common -- appearance of flip void_ parameter $ instr construction. projectVoid :: forall a b voidExpr exb. (KnownValue a, IsError (VoidResult b), NiceConstant b, voidExpr :~> Void_ a b, exb :~> b) => voidExpr -> (Expr a -> IndigoM exb) -> IndigoM () -- | If the first value is greater than the second one, it returns their -- difference. If the values are equal, it returns Nothing. -- Otherwise it fails using the supplied function. subGt0 :: (ex1 :~> Natural, ex2 :~> Natural) => ex1 -> ex2 -> IndigoM () -> IndigoFunction (Maybe Natural)