-- 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.6.0 -- | 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 :: forall {r :: RuntimeRep} a (b :: TYPE r). a -> b -> b infixr 0 `seq` -- | <math>. filter, applied to a predicate and a list, -- returns the list of those elements that satisfy the predicate; i.e., -- --
--   filter p xs = [ x | x <- xs, p x]
--   
-- --
--   >>> filter odd [1, 2, 3]
--   [1,3]
--   
filter :: (a -> Bool) -> [a] -> [a] -- | <math>. zip takes two lists and returns a list of -- corresponding pairs. -- --
--   >>> zip [1, 2] ['a', 'b']
--   [(1, 'a'), (2, 'b')]
--   
-- -- If one input list is shorter than the other, excess elements of the -- longer list are discarded, even if one of the lists is infinite: -- --
--   >>> zip [1] ['a', 'b']
--   [(1, 'a')]
--   
--   >>> zip [1, 2] ['a']
--   [(1, 'a')]
--   
--   >>> zip [] [1..]
--   []
--   
--   >>> zip [1..] []
--   []
--   
-- -- zip is right-lazy: -- --
--   >>> zip [] _|_
--   []
--   
--   >>> 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 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. -- -- 'join bss' can be understood as the do -- expression -- --
--   do bs <- bss
--      bs
--   
-- --

Examples

-- -- A common use of join is to run an IO computation -- returned from an STM transaction, since STM transactions -- can't perform IO directly. Recall that -- --
--   atomically :: STM a -> IO a
--   
-- -- is used to run STM transactions atomically. So, by specializing -- the types of atomically and join to -- --
--   atomically :: STM (IO b) -> IO (IO b)
--   join       :: IO (IO b)  -> IO b
--   
-- -- we can compose them as -- --
--   join . atomically :: STM (IO b) -> IO b
--   
-- -- to run an STM transaction and the IO action it returns. join :: Monad m => m (m a) -> m a -- | The Bounded class is used to name the upper and lower limits of -- a type. Ord is not a superclass of Bounded since types -- that are not totally ordered may also have upper and lower bounds. -- -- The Bounded class may be derived for any enumeration type; -- minBound is the first constructor listed in the data -- declaration and maxBound is the last. Bounded may also -- be derived for single-constructor datatypes whose constituent types -- are in Bounded. class Bounded a minBound :: Bounded a => a maxBound :: Bounded a => a -- | Class Enum defines operations on sequentially ordered types. -- -- The enumFrom... methods are used in Haskell's translation of -- arithmetic sequences. -- -- Instances of Enum may be derived for any enumeration type -- (types whose constructors have no fields). The nullary constructors -- are assumed to be numbered left-to-right by fromEnum from -- 0 through n-1. See Chapter 10 of the Haskell -- Report for more details. -- -- For any type that is an instance of class Bounded as well as -- Enum, the following should hold: -- -- -- --
--   enumFrom     x   = enumFromTo     x maxBound
--   enumFromThen x y = enumFromThenTo x y bound
--     where
--       bound | fromEnum y >= fromEnum x = maxBound
--             | otherwise                = minBound
--   
class Enum a -- | the successor of a value. For numeric types, succ adds 1. succ :: Enum a => a -> a -- | the predecessor of a value. For numeric types, pred subtracts -- 1. pred :: Enum a => a -> a -- | Convert from an Int. toEnum :: Enum a => Int -> a -- | Convert to an Int. It is implementation-dependent what -- fromEnum returns when applied to a value that is too large to -- fit in an Int. fromEnum :: Enum a => a -> Int -- | Used in Haskell's translation of [n..] with [n..] = -- enumFrom n, a possible implementation being enumFrom n = n : -- enumFrom (succ n). For example: -- -- enumFrom :: Enum a => a -> [a] -- | Used in Haskell's translation of [n,n'..] with [n,n'..] = -- enumFromThen n n', a possible implementation being -- enumFromThen n n' = n : n' : worker (f x) (f x n'), -- worker s v = v : worker s (s v), x = fromEnum n' - -- fromEnum n and f n y | n > 0 = f (n - 1) (succ y) | n < -- 0 = f (n + 1) (pred y) | otherwise = y For example: -- -- enumFromThen :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n..m] with [n..m] = -- enumFromTo n m, a possible implementation being enumFromTo n -- m | n <= m = n : enumFromTo (succ n) m | otherwise = []. For -- example: -- -- enumFromTo :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n,n'..m] with [n,n'..m] -- = enumFromThenTo n n' m, a possible implementation being -- enumFromThenTo n n' m = worker (f x) (c x) n m, x = -- fromEnum n' - fromEnum n, c x = bool (>=) ((x -- 0) f n y | n > 0 = f (n - 1) (succ y) | n < 0 = f (n + -- 1) (pred y) | otherwise = y and worker s c v m | c v m = v : -- worker s c (s v) m | otherwise = [] For example: -- -- enumFromThenTo :: Enum a => a -> a -> a -> [a] -- | The Eq class defines equality (==) and inequality -- (/=). All the basic datatypes exported by the Prelude -- are instances of Eq, and Eq may be derived for any -- datatype whose constituents are also instances of Eq. -- -- The Haskell Report defines no laws for Eq. However, == -- 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 `div` infixl 7 `quot` infixl 7 `rem` 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. -- -- 'as >>= bs' can be understood as the do -- expression -- --
--   do a <- as
--      bs a
--   
(>>=) :: 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 is used to apply a function of type (a -> b) -- to a value of type f a, where f is a functor, to produce a -- value of type f b. Note that for any type constructor with -- more than one parameter (e.g., Either), only the last type -- parameter can be modified with fmap (e.g., b in -- `Either a b`). -- -- Some type constructors with two parameters or more have a -- Bifunctor instance that allows both the last and the -- penultimate parameters to be mapped over. ==== Examples -- -- Convert from a Maybe Int to a Maybe String -- using show: -- --
--   >>> fmap show Nothing
--   Nothing
--   
--   >>> fmap show (Just 3)
--   Just "3"
--   
-- -- Convert from an Either Int Int to an Either Int -- String using show: -- --
--   >>> fmap show (Left 17)
--   Left 17
--   
--   >>> fmap show (Right 17)
--   Right "17"
--   
-- -- Double each element of a list: -- --
--   >>> fmap (*2) [1,2,3]
--   [2,4,6]
--   
-- -- Apply even to the second element of a pair: -- --
--   >>> fmap even (2,2)
--   (2,True)
--   
-- -- It may seem surprising that the function is only applied to the last -- element of the tuple compared to the list example above which applies -- it to every element in the list. To understand, remember that tuples -- are type constructors with multiple type parameters: a tuple of 3 -- elements `(a,b,c)` can also be written `(,,) a b c` and its -- Functor instance is defined for `Functor ((,,) a b)` (i.e., -- only the third parameter is free to be mapped over with fmap). -- -- It explains why fmap can be used with tuples containing values -- of different types as in the following example: -- --
--   >>> fmap even ("hello", 1.0, 4)
--   ("hello",1.0,True)
--   
fmap :: Functor f => (a -> b) -> f a -> f b -- | Replace all locations in the input with the same value. The default -- definition is fmap . const, but this may be -- overridden with a more efficient version. (<$) :: Functor f => a -> f b -> f a infixl 4 <$ -- | Basic numeric class. -- -- The Haskell Report defines no laws for Num. However, -- (+) and (*) are customarily expected -- to define a ring and have the following properties: -- -- -- -- Note that it isn't customarily expected that a type instance of -- both Num and Ord implement an ordered ring. Indeed, in -- base only Integer and Rational do. class Num a (+) :: Num a => a -> a -> a (-) :: Num a => a -> a -> a (*) :: Num a => a -> a -> a -- | Unary negation. negate :: Num a => a -> a -- | Absolute value. abs :: Num a => a -> a -- | Sign of a number. The functions abs and signum should -- satisfy the law: -- --
--   abs x * signum x == x
--   
-- -- For real numbers, the signum is either -1 (negative), -- 0 (zero) or 1 (positive). signum :: Num a => a -> a infixl 7 * infixl 6 + infixl 6 - -- | The Ord class is used for totally ordered datatypes. -- -- Instances of Ord can be derived for any user-defined datatype -- whose constituent types are in Ord. The declared order of the -- constructors in the data declaration determines the ordering in -- derived Ord instances. The Ordering datatype allows a -- single comparison to determine the precise ordering of two objects. -- -- 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. --
-- -- Note that (7.) and (8.) do not require min and -- max to return either of their arguments. The result is merely -- required to equal one of the arguments in terms of (==). -- -- Minimal complete definition: either compare or <=. -- Using compare can be more efficient for complex types. class Eq a => Ord a compare :: Ord a => a -> a -> Ordering (<) :: Ord a => a -> a -> Bool (<=) :: Ord a => a -> a -> Bool (>) :: Ord a => a -> a -> Bool (>=) :: Ord a => a -> a -> Bool max :: Ord a => a -> a -> a min :: Ord a => a -> a -> a infix 4 > infix 4 <= infix 4 >= infix 4 < -- | Parsing of Strings, producing values. -- -- Derived instances of Read make the following assumptions, which -- derived instances of Show obey: -- -- -- -- For example, given the declarations -- --
--   infixr 5 :^:
--   data Tree a =  Leaf a  |  Tree a :^: Tree a
--   
-- -- the derived instance of Read in Haskell 2010 is equivalent to -- --
--   instance (Read a) => Read (Tree a) where
--   
--           readsPrec d r =  readParen (d > app_prec)
--                            (\r -> [(Leaf m,t) |
--                                    ("Leaf",s) <- lex r,
--                                    (m,t) <- readsPrec (app_prec+1) s]) r
--   
--                         ++ readParen (d > up_prec)
--                            (\r -> [(u:^:v,w) |
--                                    (u,s) <- readsPrec (up_prec+1) r,
--                                    (":^:",t) <- lex s,
--                                    (v,w) <- readsPrec (up_prec+1) t]) r
--   
--             where app_prec = 10
--                   up_prec = 5
--   
-- -- Note that right-associativity of :^: is unused. -- -- The derived instance in GHC is equivalent to -- --
--   instance (Read a) => Read (Tree a) where
--   
--           readPrec = parens $ (prec app_prec $ do
--                                    Ident "Leaf" <- lexP
--                                    m <- step readPrec
--                                    return (Leaf m))
--   
--                        +++ (prec up_prec $ do
--                                    u <- step readPrec
--                                    Symbol ":^:" <- lexP
--                                    v <- step readPrec
--                                    return (u :^: v))
--   
--             where app_prec = 10
--                   up_prec = 5
--   
--           readListPrec = readListPrecDefault
--   
-- -- Why do both readsPrec and readPrec exist, and why does -- GHC opt to implement readPrec in derived Read instances -- instead of readsPrec? The reason is that readsPrec is -- based on the ReadS type, and although ReadS is mentioned -- in the Haskell 2010 Report, it is not a very efficient parser data -- structure. -- -- readPrec, on the other hand, is based on a much more efficient -- ReadPrec datatype (a.k.a "new-style parsers"), but its -- definition relies on the use of the RankNTypes language -- extension. Therefore, readPrec (and its cousin, -- readListPrec) are marked as GHC-only. Nevertheless, it is -- recommended to use readPrec instead of readsPrec -- whenever possible for the efficiency improvements it brings. -- -- As mentioned above, derived Read instances in GHC will -- implement readPrec instead of readsPrec. The default -- implementations of readsPrec (and its cousin, readList) -- will simply use readPrec under the hood. If you are writing a -- Read instance by hand, it is recommended to write it like so: -- --
--   instance Read T where
--     readPrec     = ...
--     readListPrec = readListPrecDefault
--   
class Read a 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. -- --

Example

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

Example

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

Examples

-- -- If used in conjunction with the Applicative instance for Maybe, -- you can chain Maybe computations, with a possible "early return" in -- case of Nothing. -- --
--   >>> Just 2 *> Just 3
--   Just 3
--   
-- --
--   >>> Nothing *> Just 3
--   Nothing
--   
-- -- Of course a more interesting use case would be to have effectful -- computations instead of just returning pure values. -- --
--   >>> import Data.Char
--   
--   >>> import Text.ParserCombinators.ReadP
--   
--   >>> let p = string "my name is " *> munch1 isAlpha <* eof
--   
--   >>> readP_to_S p "my name is Simon"
--   [("Simon","")]
--   
(*>) :: Applicative f => f a -> f b -> f b -- | Sequence actions, discarding the value of the second argument. (<*) :: Applicative f => f a -> f b -> f a infixl 4 <* infixl 4 *> infixl 4 <*> -- | The Foldable class represents data structures that can be reduced to a -- summary value one element at a time. Strict left-associative folds are -- a good fit for space-efficient reduction, while lazy right-associative -- folds are a good fit for corecursive iteration, or for folds that -- short-circuit after processing an initial subsequence of the -- structure's elements. -- -- Instances can be derived automatically by enabling the -- DeriveFoldable extension. For example, a derived instance for -- a binary tree might be: -- --
--   {-# LANGUAGE DeriveFoldable #-}
--   data Tree a = Empty
--               | Leaf a
--               | Node (Tree a) a (Tree a)
--       deriving Foldable
--   
-- -- A more detailed description can be found in the Overview -- section of Data.Foldable#overview. -- -- For the class laws see the Laws section of -- Data.Foldable#laws. class Foldable (t :: Type -> Type) -- | Functors representing data structures that can be transformed to -- structures of the same shape by performing an -- Applicative (or, therefore, Monad) action on each -- element from left to right. -- -- A more detailed description of what same shape means, the -- various methods, how traversals are constructed, and example advanced -- use-cases can be found in the Overview section of -- Data.Traversable#overview. -- -- For the class laws see the Laws section of -- Data.Traversable#laws. class (Functor t, Foldable t) => Traversable (t :: Type -> Type) -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and collect the results. For a version that -- ignores the results see traverse_. -- --

Examples

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

Examples

-- -- Basic usage: -- -- For the first two examples we show sequenceA fully evaluating a a -- structure and collecting the results. -- --
--   >>> sequenceA [Just 1, Just 2, Just 3]
--   Just [1,2,3]
--   
-- --
--   >>> sequenceA [Right 1, Right 2, Right 3]
--   Right [1,2,3]
--   
-- -- The next two example show Nothing and Just will short -- circuit the resulting structure if present in the input. For more -- context, check the Traversable instances for Either and -- Maybe. -- --
--   >>> sequenceA [Just 1, Just 2, Just 3, Nothing]
--   Nothing
--   
-- --
--   >>> sequenceA [Right 1, Right 2, Right 3, Left 4]
--   Left 4
--   
sequenceA :: (Traversable t, Applicative f) => t (f a) -> f (t a) -- | Map each element of a structure to a monadic action, evaluate these -- actions from left to right, and collect the results. For a version -- that ignores the results see mapM_. -- --

Examples

-- -- mapM is literally a traverse with a type signature -- restricted to Monad. Its implementation may be more efficient -- due to additional power of Monad. mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b) -- | Evaluate each monadic action in the structure from left to right, and -- collect the results. For a version that ignores the results see -- sequence_. -- --

Examples

-- -- Basic usage: -- -- The first two examples are instances where the input and and output of -- sequence are isomorphic. -- --
--   >>> sequence $ Right [1,2,3,4]
--   [Right 1,Right 2,Right 3,Right 4]
--   
-- --
--   >>> sequence $ [Right 1,Right 2,Right 3,Right 4]
--   Right [1,2,3,4]
--   
-- -- The following examples demonstrate short circuit behavior for -- sequence. -- --
--   >>> sequence $ Left [1,2,3,4]
--   Left [1,2,3,4]
--   
-- --
--   >>> sequence $ [Left 0, Right 1,Right 2,Right 3,Right 4]
--   Left 0
--   
sequence :: (Traversable t, Monad m) => t (m a) -> m (t a) -- | Representable types of kind *. This class is derivable in GHC -- with the DeriveGeneric flag on. -- -- A Generic instance must satisfy the following laws: -- --
--   from . toid
--   to . fromid
--   
class Generic a -- | 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. -- --
--   >>> [1,2,3] <> [4,5,6]
--   [1,2,3,4,5,6]
--   
(<>) :: Semigroup a => a -> a -> a -- | Reduce a non-empty list with <> -- -- The default definition should be sufficient, but this can be -- overridden for efficiency. -- --
--   >>> import Data.List.NonEmpty (NonEmpty (..))
--   
--   >>> sconcat $ "Hello" :| [" ", "Haskell", "!"]
--   "Hello Haskell!"
--   
sconcat :: Semigroup a => NonEmpty a -> a -- | Repeat a value n times. -- -- Given that this works on a Semigroup it is allowed to fail if -- you request 0 or fewer repetitions, and the default definition will do -- so. -- -- By making this a member of the class, idempotent semigroups and -- monoids can upgrade this to execute in <math> by picking -- stimes = stimesIdempotent or stimes = -- stimesIdempotentMonoid respectively. -- --
--   >>> stimes 4 [1]
--   [1,1,1,1]
--   
stimes :: (Semigroup a, Integral b) => b -> a -> a infixr 6 <> -- | The class of monoids (types with an associative binary operation that -- has an identity). Instances should satisfy the following: -- -- -- -- The method names refer to the monoid of lists under concatenation, but -- there are many other instances. -- -- Some types can be viewed as a monoid in more than one way, e.g. both -- addition and multiplication on numbers. In such cases we often define -- newtypes and make those instances of Monoid, e.g. -- Sum and Product. -- -- NOTE: Semigroup is a superclass of Monoid since -- base-4.11.0.0. class Semigroup a => Monoid a -- | Identity of mappend -- --
--   >>> "Hello world" <> mempty
--   "Hello world"
--   
mempty :: Monoid a => a -- | An associative operation -- -- NOTE: This method is redundant and has the default -- implementation mappend = (<>) since -- base-4.11.0.0. Should it be implemented manually, since -- mappend is a synonym for (<>), it is expected that -- the two functions are defined the same way. In a future GHC release -- mappend will be removed from Monoid. mappend :: Monoid a => a -> a -> a -- | Fold a list using the monoid. -- -- For most types, the default definition for mconcat will be -- used, but the function is included in the class definition so that an -- optimized version can be provided for specific types. -- --
--   >>> mconcat ["Hello", " ", "Haskell", "!"]
--   "Hello Haskell!"
--   
mconcat :: Monoid a => [a] -> a data Bool False :: Bool True :: Bool -- | A String is a list of characters. String constants in Haskell -- are values of type String. -- -- See Data.List for operations on lists. type String = [Char] -- | The character type Char is an enumeration whose values -- represent Unicode (or equivalently ISO/IEC 10646) code points (i.e. -- characters, see http://www.unicode.org/ for details). This set -- extends the ISO 8859-1 (Latin-1) character set (the first 256 -- characters), which is itself an extension of the ASCII character set -- (the first 128 characters). A character literal in Haskell has type -- Char. -- -- To convert a Char to or from the corresponding Int value -- defined by Unicode, use toEnum and fromEnum from the -- Enum class respectively (or equivalently ord and -- chr). data Char -- | Double-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- double-precision type. data Double 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 -- | Arbitrary precision integers. In contrast with fixed-size integral -- types such as Int, the Integer type represents the -- entire infinite range of integers. -- -- Integers are stored in a kind of sign-magnitude form, hence do not -- expect two's complement form when using bit operations. -- -- If the value is small (fit into an Int), IS constructor -- is used. Otherwise IP and IN constructors are used to -- store a BigNat representing respectively the positive or the -- negative value magnitude. -- -- Invariant: IP and IN are used iff value doesn't fit in -- IS data Integer -- | Natural number -- -- Invariant: numbers <= 0xffffffffffffffff use the NS -- constructor data Natural -- | The Maybe type encapsulates an optional value. A value of type -- Maybe a either contains a value of type a -- (represented as Just a), or it is empty (represented -- as Nothing). Using Maybe is a good way to deal with -- errors or exceptional cases without resorting to drastic measures such -- as error. -- -- The Maybe type is also a monad. It is a simple kind of error -- monad, where all errors are represented by Nothing. A richer -- error monad can be built using the Either type. data Maybe a Nothing :: Maybe a Just :: a -> Maybe a data Ordering LT :: Ordering EQ :: Ordering GT :: Ordering -- | Rational numbers, with numerator and denominator of some -- Integral type. -- -- Note that Ratio's instances inherit the deficiencies from the -- type parameter's. For example, Ratio Natural's Num -- instance has similar problems to Natural's. data Ratio a (:%) :: !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 types with lifted values. For example Int :: -- Type. type Type = Type -- | 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 -- | 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 -- | Reverse order of bytes in Word16. byteSwap16 :: Word16 -> Word16 -- | Reverse order of bytes in Word32. byteSwap32 :: Word32 -> Word32 -- | Reverse order of bytes in Word64. byteSwap64 :: Word64 -> Word64 -- | 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 -- | deepseq: fully evaluates the first argument, before returning -- the second. -- -- The name deepseq is used to illustrate the relationship to -- seq: where seq is shallow in the sense that it only -- evaluates the top level of its argument, deepseq traverses the -- entire data structure evaluating it completely. -- -- deepseq can be useful for forcing pending exceptions, -- eradicating space leaks, or forcing lazy I/O to happen. It is also -- useful in conjunction with parallel Strategies (see the -- parallel package). -- -- There is no guarantee about the ordering of evaluation. The -- implementation may evaluate the components of the structure in any -- order or in parallel. To impose an actual order on evaluation, use -- pseq from Control.Parallel in the parallel -- package. deepseq :: NFData a => a -> b -> b -- | a 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 -- | 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 set of values a. data Set a -- | 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 -- | 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 -- | Function composition. (.) :: (b -> c) -> (a -> b) -> a -> c infixr 9 . -- | Same as >>=, but with the arguments interchanged. (=<<) :: Monad m => (a -> m b) -> m a -> m b infixr 1 =<< -- | 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 -- | asTypeOf is a type-restricted version of const. It is -- usually used as an infix operator, and its typing forces its first -- argument (which is usually overloaded) to have the same type as the -- second. asTypeOf :: a -> a -> a -- | const x is a unary function which evaluates to x for -- all inputs. -- --
--   >>> const 42 "hello"
--   42
--   
-- --
--   >>> map (const 42) [0..3]
--   [42,42,42,42]
--   
const :: a -> b -> a -- | flip f takes its (first) two arguments in the reverse -- order of f. -- --
--   >>> flip (++) "hello" "world"
--   "worldhello"
--   
flip :: (a -> b -> c) -> b -> a -> c -- | Identity function. -- --
--   id x = x
--   
id :: a -> a -- | 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 -- | The fromEnum method restricted to the type Char. ord :: Char -> Int -- | Conditional execution of Applicative expressions. For example, -- --
--   when debug (putStrLn "Debugging")
--   
-- -- will output the string Debugging if the Boolean value -- debug is True, and otherwise do nothing. when :: Applicative f => Bool -> f () -> f () -- | A monoid on applicative functors. -- -- If defined, some and many should be the least solutions -- of the equations: -- -- class Applicative f => Alternative (f :: Type -> Type) -- | The identity of <|> empty :: Alternative f => f a -- | An associative binary operation (<|>) :: Alternative f => f a -> f a -> f a -- | One or more. some :: Alternative f => f a -> f [a] -- | Zero or more. many :: Alternative f => f a -> f [a] infixl 3 <|> -- | Monads that also support choice and failure. class (Alternative m, Monad m) => MonadPlus (m :: Type -> Type) -- | The identity of mplus. It should also satisfy the equations -- --
--   mzero >>= f  =  mzero
--   v >> mzero   =  mzero
--   
-- -- The default definition is -- --
--   mzero = empty
--   
mzero :: MonadPlus m => m a -- | An associative operation. The default definition is -- --
--   mplus = (<|>)
--   
mplus :: MonadPlus m => m a -> m a -> m a -- | Non-empty (and non-strict) list type. data NonEmpty a (:|) :: a -> [a] -> NonEmpty a infixr 5 :| -- | 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 -- | curry converts an uncurried function to a curried function. -- --

Examples

-- --
--   >>> curry fst 1 2
--   1
--   
curry :: ((a, b) -> c) -> a -> b -> c -- | 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 -- | 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 <$> -- | 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 () -- | 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` -- | 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 fromMaybe function takes a default value and a Maybe -- value. If the Maybe is Nothing, it returns the default -- value; otherwise, it returns the value contained in the Maybe. -- --

Examples

-- -- Basic usage: -- --
--   >>> fromMaybe "" (Just "Hello, World!")
--   "Hello, World!"
--   
-- --
--   >>> fromMaybe "" Nothing
--   ""
--   
-- -- Read an integer from a string using readMaybe. If we fail to -- parse an integer, we want to return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> fromMaybe 0 (readMaybe "5")
--   5
--   
--   >>> fromMaybe 0 (readMaybe "")
--   0
--   
fromMaybe :: a -> Maybe a -> a -- | The 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 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 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 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 maybe function takes a default value, a function, and a -- Maybe value. If the Maybe value is Nothing, the -- function returns the default value. Otherwise, it applies the function -- to the value inside the Just and returns the result. -- --

Examples

-- -- Basic usage: -- --
--   >>> maybe False odd (Just 3)
--   True
--   
-- --
--   >>> maybe False odd Nothing
--   False
--   
-- -- Read an integer from a string using readMaybe. If we succeed, -- return twice the integer; that is, apply (*2) to it. If -- instead we fail to parse an integer, return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> maybe 0 (*2) (readMaybe "5")
--   10
--   
--   >>> maybe 0 (*2) (readMaybe "")
--   0
--   
-- -- Apply show to a Maybe Int. If we have Just n, -- we want to show the underlying Int n. But if we have -- Nothing, we return the empty string instead of (for example) -- "Nothing": -- --
--   >>> maybe "" show (Just 5)
--   "5"
--   
--   >>> maybe "" show Nothing
--   ""
--   
maybe :: b -> (a -> b) -> Maybe a -> b -- | The 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] -- | break, applied to a predicate p and a list -- xs, returns a tuple where first element is longest prefix -- (possibly empty) of xs of elements that do not satisfy -- p and second element is the remainder of the list: -- --
--   >>> break (> 3) [1,2,3,4,1,2,3,4]
--   ([1,2,3],[4,1,2,3,4])
--   
--   >>> break (< 9) [1,2,3]
--   ([],[1,2,3])
--   
--   >>> break (> 9) [1,2,3]
--   ([1,2,3],[])
--   
-- -- break p is equivalent to span (not . -- p). break :: (a -> Bool) -> [a] -> ([a], [a]) -- | cycle ties a finite list into a circular one, or equivalently, -- the infinite repetition of the original list. It is the identity on -- infinite lists. -- --
--   >>> cycle []
--   *** Exception: Prelude.cycle: empty list
--   
--   >>> take 20 $ cycle [42]
--   [42,42,42,42,42,42,42,42,42,42...
--   
--   >>> take 20 $ cycle [2, 5, 7]
--   [2,5,7,2,5,7,2,5,7,2,5,7...
--   
cycle :: [a] -> [a] -- | drop n xs returns the suffix of xs after the -- first n elements, or [] if n >= length -- xs. -- --
--   >>> drop 6 "Hello World!"
--   "World!"
--   
--   >>> drop 3 [1,2,3,4,5]
--   [4,5]
--   
--   >>> drop 3 [1,2]
--   []
--   
--   >>> drop 3 []
--   []
--   
--   >>> drop (-1) [1,2]
--   [1,2]
--   
--   >>> drop 0 [1,2]
--   [1,2]
--   
-- -- It is an instance of the more general genericDrop, in which -- n may be of any integral type. drop :: Int -> [a] -> [a] -- | dropWhile p xs returns the suffix remaining after -- takeWhile p xs. -- --
--   >>> dropWhile (< 3) [1,2,3,4,5,1,2,3]
--   [3,4,5,1,2,3]
--   
--   >>> dropWhile (< 9) [1,2,3]
--   []
--   
--   >>> dropWhile (< 0) [1,2,3]
--   [1,2,3]
--   
dropWhile :: (a -> Bool) -> [a] -> [a] -- | iterate f x returns an infinite list of repeated -- applications of f to x: -- --
--   iterate f x == [x, f x, f (f x), ...]
--   
-- -- Note that iterate is lazy, potentially leading to thunk -- build-up if the consumer doesn't force each iterate. See -- iterate' for a strict variant of this function. -- --
--   >>> take 10 $ iterate not True
--   [True,False,True,False...
--   
--   >>> take 10 $ iterate (+3) 42
--   [42,45,48,51,54,57,60,63...
--   
iterate :: (a -> a) -> a -> [a] -- | repeat x is an infinite list, with x the -- value of every element. -- --
--   >>> take 20 $ repeat 17
--   [17,17,17,17,17,17,17,17,17...
--   
repeat :: a -> [a] -- | replicate n x is a list of length n with -- x the value of every element. It is an instance of the more -- general genericReplicate, in which n may be of any -- integral type. -- --
--   >>> replicate 0 True
--   []
--   
--   >>> replicate (-1) True
--   []
--   
--   >>> replicate 4 True
--   [True,True,True,True]
--   
replicate :: Int -> a -> [a] -- | reverse xs returns the elements of xs in -- reverse order. xs must be finite. -- --
--   >>> reverse []
--   []
--   
--   >>> reverse [42]
--   [42]
--   
--   >>> reverse [2,5,7]
--   [7,5,2]
--   
--   >>> reverse [1..]
--   * Hangs forever *
--   
reverse :: [a] -> [a] -- | <math>. scanl is similar to foldl, but returns a -- list of successive reduced values from the left: -- --
--   scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
--   
-- -- Note that -- --
--   last (scanl f z xs) == foldl f z xs
--   
-- --
--   >>> scanl (+) 0 [1..4]
--   [0,1,3,6,10]
--   
--   >>> scanl (+) 42 []
--   [42]
--   
--   >>> scanl (-) 100 [1..4]
--   [100,99,97,94,90]
--   
--   >>> scanl (\reversedString nextChar -> nextChar : reversedString) "foo" ['a', 'b', 'c', 'd']
--   ["foo","afoo","bafoo","cbafoo","dcbafoo"]
--   
--   >>> scanl (+) 0 [1..]
--   * Hangs forever *
--   
scanl :: (b -> a -> b) -> b -> [a] -> [b] -- | <math>. scanr is the right-to-left dual of scanl. -- Note that the order of parameters on the accumulating function are -- reversed compared to scanl. Also note that -- --
--   head (scanr f z xs) == foldr f z xs.
--   
-- --
--   >>> scanr (+) 0 [1..4]
--   [10,9,7,4,0]
--   
--   >>> scanr (+) 42 []
--   [42]
--   
--   >>> scanr (-) 100 [1..4]
--   [98,-97,99,-96,100]
--   
--   >>> scanr (\nextChar reversedString -> nextChar : reversedString) "foo" ['a', 'b', 'c', 'd']
--   ["abcdfoo","bcdfoo","cdfoo","dfoo","foo"]
--   
--   >>> force $ scanr (+) 0 [1..]
--   *** Exception: stack overflow
--   
scanr :: (a -> b -> b) -> b -> [a] -> [b] -- | 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]) -- | take n, applied to a list xs, returns the -- prefix of xs of length n, or xs itself if -- n >= length xs. -- --
--   >>> take 5 "Hello World!"
--   "Hello"
--   
--   >>> take 3 [1,2,3,4,5]
--   [1,2,3]
--   
--   >>> take 3 [1,2]
--   [1,2]
--   
--   >>> take 3 []
--   []
--   
--   >>> take (-1) [1,2]
--   []
--   
--   >>> take 0 [1,2]
--   []
--   
-- -- It is an instance of the more general genericTake, in which -- n may be of any integral type. take :: Int -> [a] -> [a] -- | takeWhile, applied to a predicate p and a list -- xs, returns the longest prefix (possibly empty) of -- xs of elements that satisfy p. -- --
--   >>> takeWhile (< 3) [1,2,3,4,1,2,3,4]
--   [1,2]
--   
--   >>> takeWhile (< 9) [1,2,3]
--   [1,2,3]
--   
--   >>> takeWhile (< 0) [1,2,3]
--   []
--   
takeWhile :: (a -> Bool) -> [a] -> [a] -- | unzip transforms a list of pairs into a list of first -- components and a list of second components. -- --
--   >>> unzip []
--   ([],[])
--   
--   >>> unzip [(1, 'a'), (2, 'b')]
--   ([1,2],"ab")
--   
unzip :: [(a, b)] -> ([a], [b]) -- | The unzip3 function takes a list of triples and returns three -- lists, analogous to unzip. -- --
--   >>> unzip3 []
--   ([],[],[])
--   
--   >>> unzip3 [(1, 'a', True), (2, 'b', False)]
--   ([1,2],"ab",[True,False])
--   
unzip3 :: [(a, b, c)] -> ([a], [b], [c]) -- | 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)] -- | <math>. zipWith generalises zip by zipping with -- the function given as the first argument, instead of a tupling -- function. -- --
--   zipWith (,) xs ys == zip xs ys
--   zipWith f [x1,x2,x3..] [y1,y2,y3..] == [f x1 y1, f x2 y2, f x3 y3..]
--   
-- -- For example, zipWith (+) is applied to two lists to -- produce the list of corresponding sums: -- --
--   >>> zipWith (+) [1, 2, 3] [4, 5, 6]
--   [5,7,9]
--   
-- -- zipWith is right-lazy: -- --
--   >>> 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] -- | The toEnum method restricted to the type Char. chr :: Int -> Char -- | raise a number to a non-negative integral power (^) :: (Num a, Integral b) => a -> b -> a infixr 8 ^ -- | raise a number to an integral power (^^) :: (Fractional a, Integral b) => a -> b -> a infixr 8 ^^ even :: Integral a => a -> Bool -- | 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 -- | lcm x y is the smallest positive integer that both -- x and y divide. lcm :: Integral a => a -> a -> a odd :: Integral a => a -> Bool -- | 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) -- | 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 -- | 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]) -- | 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 -- |
--   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 -- | intercalate xs xss is equivalent to (concat -- (intersperse xs xss)). It inserts the list xs in -- between the lists in xss and concatenates the result. -- --
--   >>> intercalate ", " ["Lorem", "ipsum", "dolor"]
--   "Lorem, ipsum, dolor"
--   
intercalate :: [a] -> [[a]] -> [a] -- | <math>. The 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] -- | <math>. The isPrefixOf function takes two lists and -- returns True iff the first list is a prefix of the second. -- --
--   >>> "Hello" `isPrefixOf` "Hello World!"
--   True
--   
-- --
--   >>> "Hello" `isPrefixOf` "Wello Horld!"
--   False
--   
isPrefixOf :: Eq a => [a] -> [a] -> Bool -- | The sort function implements a stable sorting algorithm. It is -- a special case of sortBy, which allows the programmer to supply -- their own comparison function. -- -- Elements are arranged from lowest to highest, keeping duplicates in -- the order they appeared in the input. -- --
--   >>> sort [1,6,4,3,2,5]
--   [1,2,3,4,5,6]
--   
sort :: Ord a => [a] -> [a] -- | 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 unfoldr function is a `dual' to foldr: while -- foldr reduces a list to a summary value, unfoldr builds -- a list from a seed value. The function takes the element and returns -- Nothing if it is done producing the list or returns Just -- (a,b), in which case, a is a prepended to the list -- and b is used as the next element in a recursive call. For -- example, -- --
--   iterate f == unfoldr (\x -> Just (x, f x))
--   
-- -- In some cases, unfoldr can undo a foldr operation: -- --
--   unfoldr f' (foldr f z xs) == xs
--   
-- -- if the following holds: -- --
--   f' (f x y) = Just (x,y)
--   f' z       = Nothing
--   
-- -- A simple use of unfoldr: -- --
--   >>> unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10
--   [10,9,8,7,6,5,4,3,2,1]
--   
unfoldr :: (b -> Maybe (a, b)) -> b -> [a] -- | The concatenation of all the elements of a container of lists. -- --

Examples

-- -- Basic usage: -- --
--   >>> concat (Just [1, 2, 3])
--   [1,2,3]
--   
-- --
--   >>> concat (Left 42)
--   []
--   
-- --
--   >>> concat [[1, 2, 3], [4, 5], [6], []]
--   [1,2,3,4,5,6]
--   
concat :: Foldable t => t [a] -> [a] -- | Map a function over all the elements of a container and concatenate -- the resulting lists. -- --

Examples

-- -- Basic usage: -- --
--   >>> concatMap (take 3) [[1..], [10..], [100..], [1000..]]
--   [1,2,3,10,11,12,100,101,102,1000,1001,1002]
--   
-- --
--   >>> concatMap (take 3) (Just [1..])
--   [1,2,3]
--   
concatMap :: Foldable t => (a -> [b]) -> t a -> [b] -- | The Const functor. newtype Const a (b :: k) Const :: a -> Const a (b :: k) [getConst] :: Const a (b :: k) -> a -- | Any type that you wish to throw or catch as an exception must be an -- instance of the Exception class. The simplest case is a new -- exception type directly below the root: -- --
--   data MyException = ThisException | ThatException
--       deriving Show
--   
--   instance Exception MyException
--   
-- -- The default method definitions in the Exception class do what -- we need in this case. You can now throw and catch -- ThisException and ThatException as exceptions: -- --
--   *Main> throw ThisException `catch` \e -> putStrLn ("Caught " ++ show (e :: MyException))
--   Caught ThisException
--   
-- -- In more complicated examples, you may wish to define a whole hierarchy -- of exceptions: -- --
--   ---------------------------------------------------------------------
--   -- Make the root exception type for all the exceptions in a compiler
--   
--   data SomeCompilerException = forall e . Exception e => SomeCompilerException e
--   
--   instance Show SomeCompilerException where
--       show (SomeCompilerException e) = show e
--   
--   instance Exception SomeCompilerException
--   
--   compilerExceptionToException :: Exception e => e -> SomeException
--   compilerExceptionToException = toException . SomeCompilerException
--   
--   compilerExceptionFromException :: Exception e => SomeException -> Maybe e
--   compilerExceptionFromException x = do
--       SomeCompilerException a <- fromException x
--       cast a
--   
--   ---------------------------------------------------------------------
--   -- Make a subhierarchy for exceptions in the frontend of the compiler
--   
--   data SomeFrontendException = forall e . Exception e => SomeFrontendException e
--   
--   instance Show SomeFrontendException where
--       show (SomeFrontendException e) = show e
--   
--   instance Exception SomeFrontendException where
--       toException = compilerExceptionToException
--       fromException = compilerExceptionFromException
--   
--   frontendExceptionToException :: Exception e => e -> SomeException
--   frontendExceptionToException = toException . SomeFrontendException
--   
--   frontendExceptionFromException :: Exception e => SomeException -> Maybe e
--   frontendExceptionFromException x = do
--       SomeFrontendException a <- fromException x
--       cast a
--   
--   ---------------------------------------------------------------------
--   -- Make an exception type for a particular frontend compiler exception
--   
--   data MismatchedParentheses = MismatchedParentheses
--       deriving Show
--   
--   instance Exception MismatchedParentheses where
--       toException   = frontendExceptionToException
--       fromException = frontendExceptionFromException
--   
-- -- We can now catch a MismatchedParentheses exception as -- MismatchedParentheses, SomeFrontendException or -- SomeCompilerException, but not other types, e.g. -- IOException: -- --
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: MismatchedParentheses))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeFrontendException))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeCompilerException))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: IOException))
--   *** Exception: MismatchedParentheses
--   
class (Typeable e, Show e) => Exception e toException :: Exception e => e -> SomeException fromException :: Exception e => SomeException -> Maybe e -- | Render this exception value in a human-friendly manner. -- -- Default implementation: show. displayException :: Exception e => e -> String -- | Pretty print a CallStack. prettyCallStack :: CallStack -> String -- | 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 -- | Return the current CallStack. -- -- Does *not* include the call-site of callStack. callStack :: HasCallStack => CallStack -- | Perform some computation without adding new entries to the -- CallStack. withFrozenCallStack :: HasCallStack => (HasCallStack => a) -> a -- | Identity functor and monad. (a non-strict monad) newtype Identity a Identity :: a -> Identity a [runIdentity] :: Identity a -> a -- | One or none. -- -- It is useful for modelling any computation that is allowed to fail. -- --

Examples

-- -- Using the Alternative instance of Except, the following -- functions: -- --
--   >>> canFail = throwError "it failed" :: Except String Int
--   
--   >>> final = return 42                :: Except String Int
--   
-- -- Can be combined by allowing the first function to fail: -- --
--   >>> runExcept $ canFail *> final
--   Left "it failed"
--   
--   >>> runExcept $ optional canFail *> final
--   Right 42
--   
optional :: Alternative f => f a -> f (Maybe a) -- | for is traverse with its arguments flipped. For a -- version that ignores the results see for_. for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b) -- | This generalizes the list-based filter function. filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a] -- | 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 -- | The reverse of when. unless :: Applicative f => Bool -> f () -> f () -- | Extract the first element of the stream. head :: NonEmpty a -> a -- | 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] -- | 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 -- | If Void is uninhabited then any Functor that holds only -- values of type Void is holding no values. It is implemented in -- terms of fmap absurd. vacuous :: Functor f => f Void -> f a -- | Uninhabited data type data Void -- | 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 -- | 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 (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). liftM5 :: Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r -- | fix f is the least fixed point of the function -- f, i.e. the least defined x such that f x = -- x. -- -- For example, we can write the factorial function using direct -- recursion as -- --
--   >>> let fac n = if n <= 1 then 1 else n * fac (n-1) in fac 5
--   120
--   
-- -- This uses the fact that Haskell’s let introduces recursive -- bindings. We can rewrite this definition using fix, -- --
--   >>> fix (\rec n -> if n <= 1 then 1 else n * rec (n-1)) 5
--   120
--   
-- -- Instead of making a recursive call, we introduce a dummy parameter -- rec; when used within fix, this parameter then refers -- to fix’s argument, hence the recursion is reintroduced. fix :: (a -> a) -> a -- | 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) -- | Strict version of <$>. (<$!>) :: Monad m => (a -> b) -> m a -> m b infixl 4 <$!> -- | 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. -- -- '(bs >=> cs) a' can be understood as the -- do expression -- --
--   do b <- bs a
--      cs b
--   
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 >=> -- | Like foldM, but discards the result. foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m () -- | Repeat an action indefinitely. -- --

Examples

-- -- A common use of forever is to process input from network -- sockets, Handles, and channels (e.g. MVar and -- Chan). -- -- For example, here is how we might implement an echo server, -- using forever both to listen for client connections on a -- network socket and to echo client input on client connection handles: -- --
--   echoServer :: Socket -> IO ()
--   echoServer socket = forever $ do
--     client <- accept socket
--     forkFinally (echo client) (\_ -> hClose client)
--     where
--       echo :: Handle -> IO ()
--       echo client = forever $
--         hGetLine client >>= hPutStrLn client
--   
-- -- Note that "forever" isn't necessarily non-terminating. If the action -- is in a MonadPlus and short-circuits after some number -- of iterations. then forever actually returns -- mzero, effectively short-circuiting its caller. forever :: Applicative f => f a -> f b -- | 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]) -- | 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 -- | replicateM n act performs the action act -- n times, and then returns the list of results: -- --

Examples

-- --
--   >>> replicateM 3 (putStrLn "a")
--   a
--   a
--   a
--   
replicateM :: Applicative m => Int -> m a -> m [a] -- | Like replicateM, but discards the result. replicateM_ :: Applicative m => Int -> m a -> m () -- | The zipWithM function generalizes zipWith to arbitrary -- applicative functors. zipWithM :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m [c] -- | zipWithM_ is the extension of zipWithM which ignores the -- final result. zipWithM_ :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m () -- | Monads in which IO computations may be embedded. Any monad -- built by applying a sequence of monad transformers to the IO -- monad will be an instance of this class. -- -- Instances should satisfy the following laws, which state that -- liftIO is a transformer of monads: -- -- class Monad m => MonadIO (m :: Type -> Type) -- | Lift a computation from the IO monad. This allows us to run IO -- computations in any monadic stack, so long as it supports these kinds -- of operations (i.e. IO is the base monad for the stack). -- --

Example

-- --
--   import Control.Monad.Trans.State -- from the "transformers" library
--   
--   printState :: Show s => StateT s IO ()
--   printState = do
--     state <- get
--     liftIO $ print state
--   
-- -- Had we omitted liftIO, we would have ended up with -- this error: -- --
--   • Couldn't match type ‘IO’ with ‘StateT s IO’
--    Expected type: StateT s IO ()
--      Actual type: IO ()
--   
-- -- The important part here is the mismatch between StateT s IO -- () and IO (). -- -- Luckily, we know of a function that takes an IO a and -- returns an (m a): liftIO, enabling us to run -- the program and see the expected results: -- --
--   > evalStateT printState "hello"
--   "hello"
--   
--   > evalStateT printState 3
--   3
--   
liftIO :: MonadIO m => IO a -> m a -- | 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 () type Word62 = OddWord Word64 One One One One One Zero () type Word63 = OddWord Word64 One One One One One One () -- | See examples in Control.Monad.Reader. Note, the partially -- applied function type (->) r is a simple reader monad. See -- the instance declaration below. class Monad m => MonadReader r (m :: Type -> Type) | m -> r -- | Retrieves the monad environment. ask :: MonadReader r m => m r -- | Executes a computation in a modified environment. local :: MonadReader r m => (r -> r) -> m a -> m a -- | Retrieves a function of the current environment. reader :: MonadReader r m => (r -> a) -> m a -- | Minimal definition is either both of get and put or -- just state class Monad m => MonadState s (m :: Type -> Type) | m -> s -- | Return the state from the internals of the monad. get :: MonadState s m => m s -- | Replace the state inside the monad. put :: MonadState s m => s -> m () -- | Embed a simple state action into the monad. state :: MonadState s m => (s -> (a, s)) -> m a -- | The class of types that can be converted to a hash value. -- -- Minimal implementation: hashWithSalt. -- -- Note: the hash is not guaranteed to be stable across library -- versions, operating systems or architectures. For stable hashing use -- named hashes: SHA256, CRC32 etc. -- -- If you are looking for Hashable instance in time -- package, check time-compat class 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 -- | 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 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 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 -- | 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` -- | 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. newtype Option a Option :: Maybe a -> Option a [getOption] :: Option a -> Maybe a -- | Repeat a value n times. -- --
--   mtimesDefault n a = a <> a <> ... <> a  -- using <> (n-1) times
--   
-- -- Implemented using stimes and mempty. -- -- This is a suitable definition for an mtimes member of -- Monoid. mtimesDefault :: (Integral b, Monoid a) => b -> a -> a -- | A generalization of cycle to an arbitrary Semigroup. May -- fail to terminate for some values in some semigroups. cycle1 :: Semigroup m => m -> m -- | 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] -- | 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]) -- | The mapAccumR function behaves like a combination of -- fmap and foldr; it applies a function to each element of -- a structure, passing an accumulating parameter from right to left, and -- returning a final value of this accumulator together with the new -- structure. -- --

Examples

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

Examples

-- -- Basic usage: -- --
--   >>> mapAccumL (\a b -> (a + b, a)) 0 [1..10]
--   (55,[0,1,3,6,10,15,21,28,36,45])
--   
-- --
--   >>> mapAccumL (\a b -> (a <> show b, a)) "0" [1..5]
--   ("012345",["0","01","012","0123","01234"])
--   
mapAccumL :: Traversable t => (s -> a -> (s, b)) -> s -> t a -> (s, t b) -- | This function may be used as a value for foldMap in a -- Foldable instance. -- --
--   foldMapDefault f ≡ getConst . traverse (Const . f)
--   
foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m -- | This function may be used as a value for fmap in a -- Functor instance, provided that traverse is defined. -- (Using fmapDefault with a Traversable instance defined -- only by sequenceA will result in infinite recursion.) -- --
--   fmapDefault f ≡ runIdentity . traverse (Identity . f)
--   
fmapDefault :: Traversable t => (a -> b) -> t a -> t b -- | Lists, but with an Applicative functor based on zipping. newtype ZipList a ZipList :: [a] -> ZipList a [getZipList] :: ZipList a -> [a] -- | 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 &&& stdin :: Handle stderr :: Handle -- | Shared memory locations that support atomic memory transactions. data TVar a -- | A monad supporting atomic memory transactions. data STM a -- | 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 mutable variable in the IO monad data IORef a -- | Pretty print a SrcLoc. prettySrcLoc :: SrcLoc -> String -- | Right-to-left monadic fold over the elements of a structure. -- -- Given a structure t with elements (a, b, c, ..., x, -- y), the result of a fold with an operator function f is -- equivalent to: -- --
--   foldrM f z t = do
--       yy <- f y z
--       xx <- f x yy
--       ...
--       bb <- f b cc
--       aa <- f a bb
--       return aa -- Just @return z@ when the structure is empty
--   
-- -- For a Monad m, given two functions f1 :: a -> m b -- and f2 :: b -> m c, their Kleisli composition (f1 -- >=> f2) :: a -> m c is defined by: -- --
--   (f1 >=> f2) a = f1 a >>= f2
--   
-- -- Another way of thinking about foldrM is that it amounts to an -- application to z of a Kleisli composition: -- --
--   foldrM f z t = f y >=> f x >=> ... >=> f b >=> f a $ z
--   
-- -- The monadic effects of foldrM are sequenced from right to -- left, and e.g. folds of infinite lists will diverge. -- -- If at some step the bind operator (>>=) -- short-circuits (as with, e.g., mzero in a MonadPlus), -- the evaluated effects will be from a tail of the element sequence. If -- you want to evaluate the monadic effects in left-to-right order, or -- perhaps be able to short-circuit after an initial sequence of -- elements, you'll need to use foldlM instead. -- -- If the monadic effects don't short-circuit, the outermost application -- of f is to the leftmost element a, so that, ignoring -- effects, the result looks like a right fold: -- --
--   a `f` (b `f` (c `f` (... (x `f` (y `f` z))))).
--   
-- --

Examples

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

Examples

-- -- Basic usage: -- --
--   >>> let f a e = do { print e ; return $ e : a }
--   
--   >>> foldlM f [] [0..3]
--   0
--   1
--   2
--   3
--   [3,2,1,0]
--   
foldlM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | The transpose function transposes the rows and columns of its -- argument. For example, -- --
--   >>> transpose [[1,2,3],[4,5,6]]
--   [[1,4],[2,5],[3,6]]
--   
-- -- If some of the rows are shorter than the following rows, their -- elements are skipped: -- --
--   >>> transpose [[10,11],[20],[],[30,31,32]]
--   [[10,20,30],[11,31],[32]]
--   
transpose :: [[a]] -> [[a]] -- | <math>. The tails function returns all final segments of -- the argument, longest first. For example, -- --
--   >>> tails "abc"
--   ["abc","bc","c",""]
--   
-- -- Note that tails has the following strictness property: -- tails _|_ = _|_ : _|_ tails :: [a] -> [[a]] -- | The subsequences function returns the list of all subsequences -- of the argument. -- --
--   >>> subsequences "abc"
--   ["","a","b","ab","c","ac","bc","abc"]
--   
subsequences :: [a] -> [[a]] -- | Sort a list by comparing the results of a key function applied to each -- element. sortOn f is equivalent to sortBy (comparing -- f), but has the performance advantage of only evaluating -- f once for each element in the input list. This is called the -- decorate-sort-undecorate paradigm, or Schwartzian transform. -- -- Elements are arranged from lowest to highest, keeping duplicates in -- the order they appeared in the input. -- --
--   >>> sortOn fst [(2, "world"), (4, "!"), (1, "Hello")]
--   [(1,"Hello"),(2,"world"),(4,"!")]
--   
sortOn :: Ord b => (a -> b) -> [a] -> [a] -- | The permutations function returns the list of all permutations -- of the argument. -- --
--   >>> permutations "abc"
--   ["abc","bac","cba","bca","cab","acb"]
--   
permutations :: [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 genericTake function is an overloaded version of -- take, which accepts any Integral value as the number of -- elements to take. genericTake :: Integral i => i -> [a] -> [a] -- | The genericSplitAt function is an overloaded version of -- splitAt, which accepts any Integral value as the -- position at which to split. genericSplitAt :: Integral i => i -> [a] -> ([a], [a]) -- | The genericReplicate function is an overloaded version of -- replicate, which accepts any Integral value as the -- number of repetitions to make. genericReplicate :: Integral i => i -> a -> [a] -- | <math>. The genericLength function is an overloaded -- version of length. In particular, instead of returning an -- Int, it returns any type which is an instance of Num. It -- is, however, less efficient than length. -- --
--   >>> genericLength [1, 2, 3] :: Int
--   3
--   
--   >>> genericLength [1, 2, 3] :: Float
--   3.0
--   
genericLength :: Num i => [a] -> i -- | The 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] -- | Maybe monoid returning the rightmost non-Nothing value. -- -- Last a is isomorphic to Dual (First -- a), and thus to Dual (Alt Maybe a) -- --
--   >>> getLast (Last (Just "hello") <> Last Nothing <> Last (Just "world"))
--   Just "world"
--   
newtype Last a Last :: Maybe a -> Last a [getLast] :: Last a -> Maybe a -- | 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"
--   
newtype First a First :: Maybe a -> First a [getFirst] :: First a -> Maybe a -- | Monoid under addition. -- --
--   >>> getSum (Sum 1 <> Sum 2 <> mempty)
--   3
--   
newtype Sum a Sum :: a -> Sum a [getSum] :: Sum a -> a -- | Monoid under multiplication. -- --
--   >>> getProduct (Product 3 <> Product 4 <> mempty)
--   12
--   
newtype Product a Product :: a -> Product a [getProduct] :: Product a -> a -- | The monoid of endomorphisms under composition. -- --
--   >>> let computation = Endo ("Hello, " ++) <> Endo (++ "!")
--   
--   >>> appEndo computation "Haskell"
--   "Hello, Haskell!"
--   
newtype Endo a Endo :: (a -> a) -> Endo a [appEndo] :: Endo a -> a -> a -- | The dual of a Monoid, obtained by swapping the arguments of -- mappend. -- --
--   >>> getDual (mappend (Dual "Hello") (Dual "World"))
--   "WorldHello"
--   
newtype Dual a Dual :: a -> Dual a [getDual] :: Dual a -> a -- | Monoid under <|>. -- --
--   >>> getAlt (Alt (Just 12) <> Alt (Just 24))
--   Just 12
--   
-- --
--   >>> getAlt $ Alt Nothing <> Alt (Just 24)
--   Just 24
--   
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 -- | This is a valid definition of stimes for a Monoid. -- -- Unlike the default definition of stimes, it is defined for 0 -- and so it should be preferred where possible. stimesMonoid :: (Integral b, Monoid a) => b -> a -> a -- | This is a valid definition of stimes for an idempotent -- Semigroup. -- -- When x <> x = x, this definition should be preferred, -- because it works in <math> rather than <math>. stimesIdempotent :: Integral b => b -> a -> a -- | The Down type allows you to reverse sort order conveniently. A -- value of type Down a contains a value of type -- a (represented as Down a). -- -- If a has an Ord instance associated with it -- then comparing two values thus wrapped will give you the opposite of -- their normal sort order. This is particularly useful when sorting in -- generalised list comprehensions, as in: then sortWith by -- Down x. -- --
--   >>> compare True False
--   GT
--   
-- --
--   >>> compare (Down True) (Down False)
--   LT
--   
-- -- If a has a Bounded instance then the wrapped -- instance also respects the reversed ordering by exchanging the values -- of minBound and maxBound. -- --
--   >>> minBound :: Int
--   -9223372036854775808
--   
-- --
--   >>> minBound :: Down Int
--   Down 9223372036854775807
--   
-- -- All other instances of Down a behave as they do for -- a. newtype Down a Down :: a -> Down a [getDown] :: Down a -> a -- | This type represents unknown type-level natural numbers. data SomeNat SomeNat :: Proxy n -> SomeNat -- | Convert an integer into an unknown type-level natural. someNatVal :: Natural -> SomeNat natVal :: forall (n :: Nat) proxy. KnownNat n => proxy n -> Natural -- | 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] -- | 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 -- | See openFile data IOMode ReadMode :: IOMode WriteMode :: IOMode AppendMode :: IOMode ReadWriteMode :: IOMode -- | Bitwise "xor" xor :: Bits a => a -> a -> a infixl 6 `xor` underflowError :: 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 ratioZeroDenominatorError :: a ratioPrec1 :: Int ratioPrec :: Int overflowError :: a numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a] numericEnumFromThenTo :: (Ord a, Fractional a) => a -> a -> a -> [a] numericEnumFromThen :: Fractional a => a -> a -> [a] numericEnumFrom :: Fractional a => 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 notANumber :: Rational -- | Convert an Int into a Natural, throwing an underflow exception for -- negative values. naturalFromInt :: Int -> Natural integralEnumFromTo :: Integral a => a -> a -> [a] integralEnumFromThenTo :: Integral a => a -> a -> a -> [a] integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a] integralEnumFrom :: (Integral a, Bounded a) => a -> [a] infinity :: Rational divZeroError :: 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 (^^%^^) :: Integral a => Rational -> a -> Rational (^%^) :: Integral a => Rational -> a -> Rational boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a] boundedEnumFrom :: (Enum a, Bounded a) => a -> [a] -- | Case analysis for the Bool type. bool x y p -- evaluates to x when p is False, and evaluates -- to y when p is True. -- -- This is equivalent to if p then y else x; that is, one can -- think of it as an if-then-else construct with its arguments reordered. -- --

Examples

-- -- Basic usage: -- --
--   >>> bool "foo" "bar" True
--   "bar"
--   
--   >>> bool "foo" "bar" False
--   "foo"
--   
-- -- Confirm that bool x y p and if p then y else -- x are equivalent: -- --
--   >>> let p = True; x = "bar"; y = "foo"
--   
--   >>> bool x y p == if p then y else x
--   True
--   
--   >>> let p = False
--   
--   >>> bool x y p == if p then y else x
--   True
--   
bool :: a -> a -> Bool -> a -- | & 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 & -- | 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 <&> -- | 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 $> -- | Swap the components of a pair. swap :: (a, b) -> (b, 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] minInt :: Int maxInt :: Int -- | 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 <**> -- | 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 -- | Extract a list of call-sites from the CallStack. -- -- The list is ordered by most recent call. getCallStack :: CallStack -> [([Char], SrcLoc)] -- | This is a valid definition of stimes for an idempotent -- Monoid. -- -- When mappend x x = x, this definition should be preferred, -- because it works in <math> rather than <math> stimesIdempotentMonoid :: (Integral b, Monoid a) => b -> a -> a -- | The 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 -- | 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 $!! -- | The inverse of ExceptT. runExceptT :: ExceptT e m a -> m (Either e 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 -- | 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 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 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) -- | 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) -- | The (open) type family IntBaseType encodes type-level -- information about the value range of an integral type. -- -- This module also provides type family instances for the standard -- Haskell 2010 integral types (including Foreign.C.Types) as well -- as the Natural type. -- -- Here's a simple example for registering a custom type with the -- Data.IntCast facilities: -- --
--   -- user-implemented unsigned 4-bit integer
--   data Nibble = …
--   
--   -- declare meta-information
--   type instance IntBaseType Nibble = FixedWordTag 4
--   
--   -- user-implemented signed 7-bit integer
--   data MyInt7 = …
--   
--   -- declare meta-information
--   type instance IntBaseType MyInt7 = FixedIntTag 7
--   
-- -- The type-level predicate IsIntSubType provides a partial -- ordering based on the types above. See also intCast. type family IntBaseType a :: IntBaseTypeK -- | 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 -- | Retrieve the first value targeted by a Fold or Traversal -- (or Just the result from a Getter or Lens) into -- the current state. -- --
--   preuse = use . pre
--   
-- --
--   preuse :: MonadState s m => Getter s a     -> m (Maybe a)
--   preuse :: MonadState s m => Fold s a       -> m (Maybe a)
--   preuse :: MonadState s m => Lens' s a      -> m (Maybe a)
--   preuse :: MonadState s m => Iso' s a       -> m (Maybe a)
--   preuse :: MonadState s m => Traversal' s a -> m (Maybe a)
--   
preuse :: MonadState s m => Getting (First a) s a -> m (Maybe a) -- | Retrieve the first value targeted by a Fold or Traversal -- (or Just the result from a Getter or Lens). See -- also firstOf and ^?, which are similar with some subtle -- differences (explained below). -- --
--   listToMaybe . toListpreview folded
--   
-- --
--   preview = view . pre
--   
-- -- Unlike ^?, this function uses a MonadReader to read the -- value to be focused in on. This allows one to pass the value as the -- last argument by using the MonadReader instance for (->) -- s However, it may also be used as part of some deeply nested -- transformer stack. -- -- preview uses a monoidal value to obtain the result. This means -- that it generally has good performance, but can occasionally cause -- space leaks or even stack overflows on some data types. There is -- another function, firstOf, which avoids these issues at the -- cost of a slight constant performance cost and a little less -- flexibility. -- -- It may be helpful to think of preview as having one of the -- following more specialized types: -- --
--   preview :: Getter s a     -> s -> Maybe a
--   preview :: Fold s a       -> s -> Maybe a
--   preview :: Lens' s a      -> s -> Maybe a
--   preview :: Iso' s a       -> s -> Maybe a
--   preview :: Traversal' s a -> s -> Maybe a
--   
-- --
--   preview :: MonadReader s m => Getter s a     -> m (Maybe a)
--   preview :: MonadReader s m => Fold s a       -> m (Maybe a)
--   preview :: MonadReader s m => Lens' s a      -> m (Maybe a)
--   preview :: MonadReader s m => Iso' s a       -> m (Maybe a)
--   preview :: MonadReader s m => Traversal' s a -> m (Maybe a)
--   
preview :: MonadReader s m => Getting (First a) s a -> m (Maybe a) -- | Perform a safe head of a Fold or Traversal or -- retrieve Just the result from a Getter or Lens. -- -- When using a Traversal as a partial Lens, or a -- Fold as a partial Getter this can be a convenient way to -- extract the optional value. -- -- Note: if you get stack overflows due to this, you may want to use -- firstOf instead, which can deal more gracefully with heavily -- left-biased trees. This is because ^? works by using the -- First monoid, which can occasionally cause space leaks. -- --
--   >>> Left 4 ^?_Left
--   Just 4
--   
-- --
--   >>> Right 4 ^?_Left
--   Nothing
--   
-- --
--   >>> "world" ^? ix 3
--   Just 'l'
--   
-- --
--   >>> "world" ^? ix 20
--   Nothing
--   
-- -- This operator works as an infix version of preview. -- --
--   (^?) ≡ flip preview
--   
-- -- It may be helpful to think of ^? as having one of the following -- more specialized types: -- --
--   (^?) :: s -> Getter s a     -> Maybe a
--   (^?) :: s -> Fold s a       -> Maybe a
--   (^?) :: s -> Lens' s a      -> Maybe a
--   (^?) :: s -> Iso' s a       -> Maybe a
--   (^?) :: s -> Traversal' s a -> Maybe a
--   
(^?) :: s -> Getting (First a) s a -> Maybe a infixl 8 ^? -- | A convenient infix (flipped) version of toListOf. -- --
--   >>> [[1,2],[3]]^..id
--   [[[1,2],[3]]]
--   
--   >>> [[1,2],[3]]^..traverse
--   [[1,2],[3]]
--   
--   >>> [[1,2],[3]]^..traverse.traverse
--   [1,2,3]
--   
-- --
--   >>> (1,2)^..both
--   [1,2]
--   
-- --
--   toList xs ≡ xs ^.. folded
--   (^..) ≡ flip toListOf
--   
-- --
--   (^..) :: s -> Getter s a     -> a :: s -> Fold s a       -> a :: s -> Lens' s a      -> a :: s -> Iso' s a       -> a :: s -> Traversal' s a -> a :: s -> Prism' s a     -> [a]
--   
(^..) :: s -> Getting (Endo [a]) s a -> [a] infixl 8 ^.. -- | Use the target of a Lens, Iso, or Getter in the -- current state, or use a summary of a Fold or Traversal -- that points to a monoidal value. -- --
--   >>> evalState (use _1) (a,b)
--   a
--   
-- --
--   >>> evalState (use _1) ("hello","world")
--   "hello"
--   
-- --
--   use :: MonadState s m             => Getter s a     -> m a
--   use :: (MonadState s m, Monoid r) => Fold s r       -> m r
--   use :: MonadState s m             => Iso' s a       -> m a
--   use :: MonadState s m             => Lens' s a      -> m a
--   use :: (MonadState s m, Monoid r) => Traversal' s r -> m r
--   
use :: MonadState s m => Getting a s a -> m a -- | View the value pointed to by a Getter or Lens or the -- result of folding over all the results of a Fold or -- Traversal that points at a monoidal values. -- -- This is the same operation as view with the arguments flipped. -- -- The fixity and semantics are such that subsequent field accesses can -- be performed with (.). -- --
--   >>> (a,b)^._2
--   b
--   
-- --
--   >>> ("hello","world")^._2
--   "world"
--   
-- --
--   >>> import Data.Complex
--   
--   >>> ((0, 1 :+ 2), 3)^._1._2.to magnitude
--   2.23606797749979
--   
-- --
--   (^.) ::             s -> Getter s a     -> a
--   (^.) :: Monoid m => s -> Fold s m       -> m
--   (^.) ::             s -> Iso' s a       -> a
--   (^.) ::             s -> Lens' s a      -> a
--   (^.) :: Monoid m => s -> Traversal' s m -> m
--   
(^.) :: s -> Getting a s a -> a infixl 8 ^. -- | View the value pointed to by a Getter, Iso or -- Lens or the result of folding over all the results of a -- Fold or Traversal that points at a monoidal value. -- --
--   view . toid
--   
-- --
--   >>> view (to f) a
--   f a
--   
-- --
--   >>> view _2 (1,"hello")
--   "hello"
--   
-- --
--   >>> view (to succ) 5
--   6
--   
-- --
--   >>> view (_2._1) ("hello",("world","!!!"))
--   "world"
--   
-- -- As view is commonly used to access the target of a -- Getter or obtain a monoidal summary of the targets of a -- Fold, It may be useful to think of it as having one of these -- more restricted signatures: -- --
--   view ::             Getter s a     -> s -> a
--   view :: Monoid m => Fold s m       -> s -> m
--   view ::             Iso' s a       -> s -> a
--   view ::             Lens' s a      -> s -> a
--   view :: Monoid m => Traversal' s m -> s -> m
--   
-- -- In a more general setting, such as when working with a Monad -- transformer stack you can use: -- --
--   view :: MonadReader s m             => Getter s a     -> m a
--   view :: (MonadReader s m, Monoid a) => Fold s a       -> m a
--   view :: MonadReader s m             => Iso' s a       -> m a
--   view :: MonadReader s m             => Lens' s a      -> m a
--   view :: (MonadReader s m, Monoid a) => Traversal' s a -> m a
--   
view :: MonadReader s m => Getting a s a -> m a -- | Access the 1st field of a tuple (and possibly change its type). -- --
--   >>> (1,2)^._1
--   1
--   
-- --
--   >>> _1 .~ "hello" $ (1,2)
--   ("hello",2)
--   
-- --
--   >>> (1,2) & _1 .~ "hello"
--   ("hello",2)
--   
-- --
--   >>> _1 putStrLn ("hello","world")
--   hello
--   ((),"world")
--   
-- -- This can also be used on larger tuples as well: -- --
--   >>> (1,2,3,4,5) & _1 +~ 41
--   (42,2,3,4,5)
--   
-- --
--   _1 :: Lens (a,b) (a',b) a a'
--   _1 :: Lens (a,b,c) (a',b,c) a a'
--   _1 :: Lens (a,b,c,d) (a',b,c,d) a a'
--   ...
--   _1 :: Lens (a,b,c,d,e,f,g,h,i) (a',b,c,d,e,f,g,h,i) a a'
--   
_1 :: Field1 s t a b => Lens s t a b -- | Access the 2nd field of a tuple. -- --
--   >>> _2 .~ "hello" $ (1,(),3,4)
--   (1,"hello",3,4)
--   
-- --
--   >>> (1,2,3,4) & _2 *~ 3
--   (1,6,3,4)
--   
-- --
--   >>> _2 print (1,2)
--   2
--   (1,())
--   
-- --
--   anyOf _2 :: (s -> Bool) -> (a, s) -> Bool
--   traverse . _2 :: (Applicative f, Traversable t) => (a -> f b) -> t (s, a) -> f (t (s, b))
--   foldMapOf (traverse . _2) :: (Traversable t, Monoid m) => (s -> m) -> t (b, s) -> m
--   
_2 :: Field2 s t a b => Lens s t a b -- | Access the 3rd field of a tuple. _3 :: Field3 s t a b => Lens s t a b -- | Access the 4th field of a tuple. _4 :: Field4 s t a b => Lens s t a b -- | Access the 5th field of a tuple. _5 :: Field5 s t a b => Lens s t a b -- | Replace the target of a Lens or all of the targets of a -- Setter or Traversal with a constant value. -- -- This is an infix version of set, provided for consistency with -- (.=). -- --
--   f <$ a ≡ mapped .~ f $ a
--   
-- --
--   >>> (a,b,c,d) & _4 .~ e
--   (a,b,c,e)
--   
-- --
--   >>> (42,"world") & _1 .~ "hello"
--   ("hello","world")
--   
-- --
--   >>> (a,b) & both .~ c
--   (c,c)
--   
-- --
--   (.~) :: Setter s t a b    -> b -> s -> t
--   (.~) :: Iso s t a b       -> b -> s -> t
--   (.~) :: Lens s t a b      -> b -> s -> t
--   (.~) :: Traversal s t a b -> b -> s -> t
--   
(.~) :: ASetter s t a b -> b -> s -> t infixr 4 .~ -- | Modifies the target of a Lens or all of the targets of a -- Setter or Traversal with a user supplied function. -- -- This is an infix version of over. -- --
--   fmap f ≡ mapped %~ f
--   fmapDefault f ≡ traverse %~ f
--   
-- --
--   >>> (a,b,c) & _3 %~ f
--   (a,b,f c)
--   
-- --
--   >>> (a,b) & both %~ f
--   (f a,f b)
--   
-- --
--   >>> _2 %~ length $ (1,"hello")
--   (1,5)
--   
-- --
--   >>> traverse %~ f $ [a,b,c]
--   [f a,f b,f c]
--   
-- --
--   >>> traverse %~ even $ [1,2,3]
--   [False,True,False]
--   
-- --
--   >>> traverse.traverse %~ length $ [["hello","world"],["!!!"]]
--   [[5,5],[3]]
--   
-- --
--   (%~) :: Setter s t a b    -> (a -> b) -> s -> t
--   (%~) :: Iso s t a b       -> (a -> b) -> s -> t
--   (%~) :: Lens s t a b      -> (a -> b) -> s -> t
--   (%~) :: Traversal s t a b -> (a -> b) -> s -> t
--   
(%~) :: ASetter s t a b -> (a -> b) -> s -> t infixr 4 %~ -- | Replace the target of a Lens or all of the targets of a -- Setter or Traversal with a constant value. -- --
--   (<$) ≡ set mapped
--   
-- --
--   >>> set _2 "hello" (1,())
--   (1,"hello")
--   
-- --
--   >>> set mapped () [1,2,3,4]
--   [(),(),(),()]
--   
-- -- Note: Attempting to set a Fold or Getter will -- fail at compile time with an relatively nice error message. -- --
--   set :: Setter s t a b    -> b -> s -> t
--   set :: Iso s t a b       -> b -> s -> t
--   set :: Lens s t a b      -> b -> s -> t
--   set :: Traversal s t a b -> b -> s -> t
--   
set :: ASetter s t a b -> b -> s -> t -- | Modify the target of a Lens or all the targets of a -- Setter or Traversal with a function. -- --
--   fmapover mapped
--   fmapDefaultover traverse
--   sets . overid
--   over . setsid
--   
-- -- Given any valid Setter l, you can also rely on the -- law: -- --
--   over l f . over l g = over l (f . g)
--   
-- -- e.g. -- --
--   >>> over mapped f (over mapped g [a,b,c]) == over mapped (f . g) [a,b,c]
--   True
--   
-- -- Another way to view over is to say that it transforms a -- Setter into a "semantic editor combinator". -- --
--   >>> over mapped f (Just a)
--   Just (f a)
--   
-- --
--   >>> over mapped (*10) [1,2,3]
--   [10,20,30]
--   
-- --
--   >>> over _1 f (a,b)
--   (f a,b)
--   
-- --
--   >>> over _1 show (10,20)
--   ("10",20)
--   
-- --
--   over :: Setter s t a b -> (a -> b) -> s -> t
--   over :: ASetter s t a b -> (a -> b) -> s -> t
--   
over :: ASetter s t a b -> (a -> b) -> s -> t -- | A Lens is actually a lens family as described in -- http://comonad.com/reader/2012/mirrored-lenses/. -- -- With great power comes great responsibility and a Lens is -- subject to the three common sense Lens laws: -- -- 1) You get back what you put in: -- --
--   view l (set l v s)  ≡ v
--   
-- -- 2) Putting back what you got doesn't change anything: -- --
--   set l (view l s) s  ≡ s
--   
-- -- 3) Setting twice is the same as setting once: -- --
--   set l v' (set l v s) ≡ set l v' s
--   
-- -- These laws are strong enough that the 4 type parameters of a -- Lens cannot vary fully independently. For more on how they -- interact, read the "Why is it a Lens Family?" section of -- http://comonad.com/reader/2012/mirrored-lenses/. -- -- There are some emergent properties of these laws: -- -- 1) set l s must be injective for every s This -- is a consequence of law #1 -- -- 2) set l must be surjective, because of law #2, which -- indicates that it is possible to obtain any v from some -- s such that set s v = s -- -- 3) Given just the first two laws you can prove a weaker form of law #3 -- where the values v that you are setting match: -- --
--   set l v (set l v s) ≡ set l v s
--   
-- -- Every Lens can be used directly as a Setter or -- Traversal. -- -- You can also use a Lens for Getting as if it were a -- Fold or Getter. -- -- Since every Lens is a valid Traversal, the -- Traversal laws are required of any Lens you create: -- --
--   l purepure
--   fmap (l f) . l g ≡ getCompose . l (Compose . fmap f . g)
--   
-- --
--   type Lens s t a b = forall f. Functor f => LensLike f s t a b
--   
type Lens s t a b = forall (f :: Type -> Type). Functor f => a -> f b -> s -> f t -- |
--   type Lens' = Simple Lens
--   
type Lens' s a = Lens s s a a -- | A Traversal can be used directly as a Setter or a -- Fold (but not as a Lens) and provides the ability to -- both read and update multiple fields, subject to some relatively weak -- Traversal laws. -- -- These have also been known as multilenses, but they have the signature -- and spirit of -- --
--   traverse :: Traversable f => Traversal (f a) (f b) a b
--   
-- -- and the more evocative name suggests their application. -- -- Most of the time the Traversal you will want to use is just -- traverse, but you can also pass any Lens or Iso -- as a Traversal, and composition of a Traversal (or -- Lens or Iso) with a Traversal (or Lens or -- Iso) using (.) forms a valid Traversal. -- -- The laws for a Traversal t follow from the laws for -- Traversable as stated in "The Essence of the Iterator Pattern". -- --
--   t purepure
--   fmap (t f) . t g ≡ getCompose . t (Compose . fmap f . g)
--   
-- -- One consequence of this requirement is that a Traversal needs -- to leave the same number of elements as a candidate for subsequent -- Traversal that it started with. Another testament to the -- strength of these laws is that the caveat expressed in section 5.5 of -- the "Essence of the Iterator Pattern" about exotic Traversable -- instances that traverse the same entry multiple times was -- actually already ruled out by the second law in that same paper! type Traversal s t a b = forall (f :: Type -> Type). Applicative f => a -> f b -> s -> f t -- |
--   type Traversal' = Simple Traversal
--   
type Traversal' s a = Traversal s s a a -- | Infix application. -- --
--   f :: Either String $ Maybe Int
--   =
--   f :: Either String (Maybe Int)
--   
type (f :: k1 -> k) $ (a :: k1) = f a infixr 2 $ -- | undefined that leaves a warning in code on every usage. undefined :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => a -- | Unsafe converter between Integer and Integral types -- checking for overflow/underflow. Return value if conversion -- does not produce overflow/underflow and raise an exception with -- corresponding error message otherwise. -- -- Note the function is strict in its argument. fromInteger :: (HasCallStack, Integral a) => Integer -> a -- | error that takes Text as an argument. error :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => Text -> a -- | 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 -- | 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]) -- | Statically safe converter between Integral types, which is just -- intCast under the hood. -- -- It is used to turn the value of type a into the value of type -- b such that a is subtype of b. It is needed -- to prevent silent unsafe conversions. -- --
--   >>> fromIntegral @Int @Word 1
--   ...
--   ... error:
--   ... Can not safely cast 'Int' to 'Word':
--   ... 'Int' is not a subtype of 'Word'
--   ...
--   
--   >>> fromIntegral @Word @Natural 1
--   1
--   
fromIntegral :: (Integral a, Integral b, CheckIntSubType a b) => a -> b -- | Similar to unsafe converter, but with the use of monadic -- fail and returning the result wrapped in a monad. unsafeM :: (MonadFail m, Buildable a) => Either a b -> m b -- | Unsafe converter from Either, which uses buildable Left -- to throw an exception with error. -- -- It is primarily needed for making unsafe counter-parts of safe -- functions. In particular, for replacing unsafeFName x = either -- (error . pretty) id constructors and converters, which produce -- many similar functions at the call site, with unsafe . fName $ -- x. unsafe :: (HasCallStack, Buildable a) => Either a b -> b -- | A version of show that requires the value to have a -- human-readable Show instance. show :: forall b a. (PrettyShow a, Show a, IsString b) => a -> b -- | An open type family for types having a human-readable Show -- representation. The kind is Constraint in case we need to -- further constrain the instance, and also for convenience to avoid -- explicitly writing ~ 'True everywhere. type family PrettyShow a -- | Statically safe converter between Integral types checking for -- overflow/underflow. Returns Right value if conversion does -- not produce overflow/underflow and Left ArithException with -- corresponding ArithException -- (Overflow/Underflow) otherwise. -- -- Note the function is strict in its argument. -- --
--   >>> fromIntegralNoOverflow @Int @Word 123
--   Right 123
--   
--   >>> fromIntegralNoOverflow @Int @Word (-123)
--   Left arithmetic underflow
--   
--   >>> fromIntegralNoOverflow @Int @Integer (-123)
--   Right (-123)
--   
--   >>> fromIntegralNoOverflow @Int @Natural (-123)
--   Left arithmetic underflow
--   
--   >>> fromIntegralNoOverflow @Int @Int8 127
--   Right 127
--   
--   >>> fromIntegralNoOverflow @Int @Int8 128
--   Left arithmetic overflow
--   
fromIntegralNoOverflow :: (Integral a, Integral b) => a -> Either ArithException b -- | Runtime-safe converter between Integral types, which is just -- fromIntegral under the hood. -- -- It is needed to semantically distinguish usages, where overflow is -- intended, from those that have to fail on overflow. E.g. Int8 -- -> Word8 with intended bits reinterpretation from lossy -- Integer -> Int. -- --
--   >>> fromIntegralOverflowing @Int8 @Word8 (-1)
--   255
--   
--   >>> fromIntegralOverflowing @Natural @Int8 450
--   -62
--   
-- -- Please note that like fromIntegral from base, this -- will throw on some conversions! -- --
--   >>> fromIntegralOverflowing @Int @Natural (-1)
--   *** Exception: arithmetic underflow
--   
-- -- See fromIntegralNoOverflow for an alternative that doesn't -- throw. fromIntegralOverflowing :: (Integral a, Num b) => a -> b -- | Statically safe converter between Integral and RealFrac -- types. Could be applied to cast common types like Float, -- Double and Scientific. -- -- It is primarily needed to replace usages of fromIntegral, which -- are safe actually as integral numbers are being casted to fractional -- ones. fromIntegralToRealFrac :: (Integral a, RealFrac b, CheckIntSubType a Integer) => a -> b -- | Statically safe converter between Integral types, which is just -- intCastMaybe under the hood. Unlike fromIntegral accept -- any a and b. Return Just value if -- conversion is possible at runtime and Nothing otherwise. fromIntegralMaybe :: (Integral a, Integral b, Bits a, Bits b) => a -> Maybe b -- | Constraint synonym equivalent to IsIntSubType a b ~ -- 'True, but with better error messages type CheckIntSubType a b = (CheckIntSubTypeErrors a b IsIntSubType a b, IsIntSubType a b ~ 'True) -- | A version of all that works on NonEmpty, thus doesn't -- require BooleanMonoid instance. -- --
--   >>> all1 (\x -> if x > 50 then Yay else Nay) $ 100 :| replicate 10 51
--   Yay
--   
all1 :: Boolean b => (a -> b) -> NonEmpty a -> b -- | A version of any that works on NonEmpty, thus doesn't -- require BooleanMonoid instance. -- --
--   >>> any1 (\x -> if x > 50 then Yay else Nay) $ 50 :| replicate 10 0
--   Nay
--   
any1 :: Boolean b => (a -> b) -> NonEmpty a -> b -- | Generalized all. -- --
--   >>> all (\x -> if x > 50 then Yay else Nay) [1..100]
--   Nay
--   
all :: (Container c, BooleanMonoid b) => (Element c -> b) -> c -> b -- | Generalized any. -- --
--   >>> any (\x -> if x > 50 then Yay else Nay) [1..100]
--   Yay
--   
any :: (Container c, BooleanMonoid b) => (Element c -> b) -> c -> b -- | A version of and that works on NonEmpty, thus doesn't -- require BooleanMonoid instance. -- --
--   >>> and1 $ Yay :| [Nay]
--   Nay
--   
and1 :: Boolean a => NonEmpty a -> a -- | A version of or that works on NonEmpty, thus doesn't -- require BooleanMonoid instance. -- --
--   >>> or1 $ Yay :| [Nay]
--   Yay
--   
or1 :: Boolean a => NonEmpty a -> a -- | Generalized version of and. -- --
--   >>> and $ replicate 10 Yay
--   Yay
--   
--   >>> and $ Nay : replicate 10 Yay
--   Nay
--   
and :: (Container c, BooleanMonoid (Element c)) => c -> Element c -- | Generalized version of or. -- --
--   >>> or $ replicate 10 Nay
--   Nay
--   
--   >>> or $ Yay : replicate 10 Nay
--   Yay
--   
or :: (Container c, BooleanMonoid (Element c)) => c -> Element c -- | Generalized boolean operators. -- -- This is useful for defining things that behave like booleans, e.g. -- predicates, or EDSL for predicates. -- --
--   >>> Yay && Nay
--   Nay
--   
--   >>> and1 $ Yay :| replicate 9 Yay
--   Yay
--   
-- -- There are also instances for these types lifted into IO and -- (->) a: -- --
--   >>> (const Yay) && (const Nay) $ ()
--   Nay
--   
--   >>> (const Yay) || (const Nay) $ ()
--   Yay
--   
class Boolean a (&&) :: Boolean a => a -> a -> a (||) :: Boolean a => a -> a -> a not :: Boolean a => a -> a infixr 2 || infixr 3 && -- | Generalized True and False. -- -- This is useful to complete the isomorphism between regular and -- generalized booleans. It's a separate class because not all -- boolean-like things form a monoid. -- --
--   >>> or $ replicate 10 Nay
--   Nay
--   
class Boolean a => BooleanMonoid a false :: BooleanMonoid a => a true :: BooleanMonoid a => a -- | A generalized version of All monoid wrapper. -- --
--   >>> All Nay <> All Nay
--   All {getAll = Nay}
--   
--   >>> All Yay <> All Nay
--   All {getAll = Nay}
--   
--   >>> All Yay <> All Yay
--   All {getAll = Yay}
--   
newtype All a All :: a -> All a [getAll] :: All a -> a -- | A generalized version of Any monoid wrapper. -- --
--   >>> Any Nay <> Any Nay
--   Any {getAny = Nay}
--   
--   >>> Any Yay <> Any Nay
--   Any {getAny = Yay}
--   
--   >>> Any Yay <> Any Yay
--   Any {getAny = Yay}
--   
newtype Any a Any :: a -> Any a [getAny] :: Any a -> a -- | A newtype for deriving a Boolean instance for any -- Applicative type constructor using DerivingVia. newtype ApplicativeBoolean (f :: k -> Type) (bool :: k) ApplicativeBoolean :: f bool -> ApplicativeBoolean (f :: k -> Type) (bool :: k) -- | Shorter alias for pure (). -- --
--   >>> pass :: Maybe ()
--   Just ()
--   
pass :: Applicative f => f () -- | Similar to some, but reflects in types that a non-empty list is -- returned. someNE :: Alternative f => f a -> f (NonEmpty a) -- | 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 $! -- | 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 -- | 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 <<$>> -- | Lifted to MonadIO version of newEmptyMVar. newEmptyMVar :: MonadIO m => m (MVar a) -- | Lifted to MonadIO version of newMVar. newMVar :: MonadIO m => a -> m (MVar a) -- | Lifted to MonadIO version of putMVar. putMVar :: MonadIO m => MVar a -> a -> m () -- | Lifted to MonadIO version of readMVar. readMVar :: 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 takeMVar. takeMVar :: MonadIO m => MVar a -> m a -- | Lifted to MonadIO version of tryPutMVar. tryPutMVar :: MonadIO m => MVar a -> a -> m Bool -- | Lifted to MonadIO version of tryReadMVar. tryReadMVar :: MonadIO m => MVar a -> m (Maybe a) -- | Lifted to MonadIO version of tryTakeMVar. tryTakeMVar :: MonadIO m => MVar a -> m (Maybe a) -- | Lifted to MonadIO version of atomically. atomically :: MonadIO m => STM a -> m a -- | Lifted to MonadIO version of newTVarIO. newTVarIO :: MonadIO m => a -> m (TVar a) -- | Lifted to MonadIO version of readTVarIO. readTVarIO :: MonadIO m => TVar a -> m a -- | Like modifyMVar, but modification is specified as a -- State computation. -- -- This method is strict in produced s value. updateMVar' :: MonadIO m => MVar s -> StateT s IO a -> m a -- | Like 'modifyTVar'', but modification is specified as a State -- monad. updateTVar' :: TVar s -> StateT s STM a -> STM a -- | Lifted version of exitWith. exitWith :: MonadIO m => ExitCode -> m a -- | Lifted version of exitFailure. exitFailure :: MonadIO m => m a -- | Lifted version of exitSuccess. exitSuccess :: MonadIO m => m a -- | 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 appendFile. appendFile :: MonadIO m => FilePath -> Text -> m () -- | Lifted version of getLine. getLine :: MonadIO m => m Text -- | Lifted version of openFile. -- -- See also withFile for more information. openFile :: MonadIO m => FilePath -> IOMode -> m Handle -- | Close a file handle -- -- See also withFile for more information. hClose :: MonadIO m => Handle -> m () -- | 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 -- | Lifted version of newIORef. newIORef :: MonadIO m => a -> m (IORef a) -- | Lifted version of readIORef. readIORef :: MonadIO m => IORef a -> m a -- | Lifted version of writeIORef. writeIORef :: MonadIO m => IORef a -> a -> m () -- | 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 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 atomicWriteIORef. atomicWriteIORef :: MonadIO m => IORef a -> a -> m () -- | Similar to fromMaybe but with flipped arguments. -- --
--   >>> readMaybe "True" ?: False
--   True
--   
-- --
--   >>> readMaybe "Tru" ?: False
--   False
--   
(?:) :: Maybe a -> a -> a infixr 0 ?: -- | 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 () -- | Monadic version of whenJust. whenJustM :: Monad m => m (Maybe a) -> (a -> m ()) -> m () -- | 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 -- | 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 () -- | Monadic version of whenNothing. whenNothingM :: Monad m => m (Maybe a) -> m a -> m a -- | Monadic version of whenNothingM_. whenNothingM_ :: Monad m => m (Maybe a) -> m () -> m () -- | 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 -- | 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 -- | Maps left part of Either to Maybe. -- --
--   >>> leftToMaybe (Left True)
--   Just True
--   
--   >>> leftToMaybe (Right "aba")
--   Nothing
--   
leftToMaybe :: Either l r -> Maybe l -- | Maps right part of Either to Maybe. -- --
--   >>> rightToMaybe (Left True)
--   Nothing
--   
--   >>> rightToMaybe (Right "aba")
--   Just "aba"
--   
rightToMaybe :: Either l r -> Maybe 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 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 -- | Applies given action to Either content if Left is given. whenLeft :: Applicative f => Either l r -> (l -> f ()) -> f () -- | Monadic version of whenLeft. whenLeftM :: Monad m => m (Either l r) -> (l -> m ()) -> m () -- | Applies given action to Either content if Right is -- given. whenRight :: Applicative f => Either l r -> (r -> f ()) -> f () -- | Monadic version of whenRight. whenRightM :: Monad m => m (Either l r) -> (r -> m ()) -> m () -- | Shorter and more readable alias for flip runReaderT. usingReaderT :: r -> ReaderT r m a -> m a -- | Shorter and more readable alias for flip runReader. usingReader :: r -> Reader r a -> a -- | Shorter and more readable alias for flip runStateT. usingStateT :: s -> StateT s m a -> m (a, s) -- | Shorter and more readable alias for flip runState. usingState :: s -> State s a -> (a, s) -- | 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 -- | 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 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 execState. It's not shorter but sometimes more -- readable. Done by analogy with using* functions family. executingState :: s -> State s a -> s -- | Lift a Maybe to the MaybeT monad hoistMaybe :: forall (m :: Type -> Type) a. Applicative m => Maybe a -> MaybeT m a -- | Lift a Either to the ExceptT monad hoistEither :: forall (m :: Type -> Type) e a. Applicative m => Either e a -> ExceptT e m a -- | Extracts Monoid value from Maybe returning mempty -- if Nothing. -- --
--   >>> maybeToMonoid (Just [1,2,3] :: Maybe [Int])
--   [1,2,3]
--   
--   >>> maybeToMonoid (Nothing :: Maybe [Int])
--   []
--   
maybeToMonoid :: Monoid m => Maybe m -> m -- | 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 type family OneItem x -- | 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 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 notElem :: Container t => Element t -> t -> Bool find :: Container t => (Element t -> Bool) -> t -> Maybe (Element t) safeHead :: Container t => t -> Maybe (Element t) safeMaximum :: Container t => t -> Maybe (Element t) safeMinimum :: Container t => t -> Maybe (Element t) safeFoldr1 :: Container t => (Element t -> Element t -> Element t) -> t -> Maybe (Element t) safeFoldl1 :: Container t => (Element t -> Element t -> Element t) -> t -> Maybe (Element 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 -- | Type class for data types that can be constructed from a list. class FromList l where { type family ListElement l; type family FromListC l; type ListElement l = Item l; type FromListC l = (); } -- | Make a value from list. -- -- For simple types like '[]' and Set: -- --
--   toList . fromList ≡ id
--   fromList . toList ≡ id
--   
--   
-- -- For map-like types: -- --
--   toPairs . fromList ≡ id
--   fromList . toPairs ≡ id
--   
--   
fromList :: FromList l => [ListElement l] -> l type family ListElement l type family FromListC l -- | 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] -- | 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 -- | 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 -- | 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 -- | Constrained to Container version of traverse_. -- --
--   >>> traverse_ putTextLn ["foo", "bar"]
--   foo
--   bar
--   
traverse_ :: (Container t, Applicative f) => (Element t -> f b) -> t -> f () -- | 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 mapM_. -- --
--   >>> mapM_ print [True, False]
--   True
--   False
--   
mapM_ :: (Container t, Monad m) => (Element t -> m b) -> t -> m () -- | 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 sequenceA_. -- --
--   >>> sequenceA_ [putTextLn "foo", print True]
--   foo
--   True
--   
sequenceA_ :: (Container t, Applicative f, Element t ~ f a) => t -> f () -- | 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 asum. -- --
--   >>> asum [Nothing, Just [False, True], Nothing, Just [True]]
--   Just [False,True]
--   
asum :: (Container t, Alternative f, Element t ~ f a) => t -> f a -- | 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 -- | 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 -- | 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 -- | 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 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 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 -- | 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]) -- | 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 () -- | Monadic version of whenNotNull. whenNotNullM :: Monad m => m [a] -> (NonEmpty a -> m ()) -> m () -- | A variant of foldl that has no base case, and thus may only -- be applied to NonEmpty. -- --
--   >>> foldl1 (+) (1 :| [2,3,4,5])
--   15
--   
foldl1 :: (a -> a -> a) -> NonEmpty a -> a -- | A variant of foldr that has no base case, and thus may only -- be applied to NonEmpty. -- --
--   >>> foldr1 (+) (1 :| [2,3,4,5])
--   15
--   
foldr1 :: (a -> a -> a) -> NonEmpty a -> a -- | The least element of a NonEmpty with respect to the given -- comparison function. minimumBy :: (a -> a -> Ordering) -> NonEmpty a -> a -- | The least element of a NonEmpty. -- --
--   >>> minimum (1 :| [2,3,4,5])
--   1
--   
minimum :: Ord a => NonEmpty a -> a -- | The largest element of a NonEmpty with respect to the given -- comparison function. maximumBy :: (a -> a -> Ordering) -> NonEmpty a -> a -- | The largest element of a NonEmpty. -- --
--   >>> maximum (1 :| [2,3,4,5])
--   5
--   
maximum :: Ord a => NonEmpty a -> a -- | 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 -- | 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 -- | Generate a pure value which, when forced, will synchronously throw the -- exception wrapped into Bug data type. bug :: (HasCallStack, Exception e) => e -> a -- | Throws error for Maybe if Nothing is given. Operates -- over MonadError. note :: MonadError e m => e -> Maybe a -> m a -- | Lifted alias for evaluate with clearer name. evaluateWHNF :: MonadIO m => a -> m a -- | Like evaluateWNHF but discards value. evaluateWHNF_ :: MonadIO m => a -> m () -- | Alias for evaluateWHNF . force with clearer name. evaluateNF :: (NFData a, MonadIO m) => a -> m a -- | Alias for evaluateWHNF . rnf. Similar to evaluateNF -- but discards resulting value. evaluateNF_ :: (NFData a, MonadIO m) => a -> 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 () -- | 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 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 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 () -- | 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] -- | 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 ordNub but also sorts a list. -- --
--   >>> sortNub [3, 3, 3, 2, 2, -1, 1]
--   [-1,1,2,3]
--   
sortNub :: Ord a => [a] -> [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] -- | Support class to overload writing of string like values. class Print a -- | Write a string like value a to a supplied Handle. hPutStr :: (Print a, MonadIO m) => Handle -> 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 to stdout/. putStr :: (Print a, MonadIO m) => a -> m () -- | Write a string like value to stdout appending a newline -- character. putStrLn :: (Print a, MonadIO m) => a -> m () -- | Lifted version of print. print :: forall a m. (MonadIO m, Show a) => a -> m () -- | Lifted version of hPrint hPrint :: (MonadIO m, Show a) => Handle -> a -> m () -- | Specialized to Text version of putStr or forcing type -- inference. putText :: 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. putLText :: MonadIO m => Text -> m () -- | Specialized to Text version of putStrLn or forcing type -- inference. putLTextLn :: MonadIO m => Text -> m () -- | Similar to undefined but data type. data Undefined Undefined :: Undefined -- | Version of trace that leaves a warning and takes Text. trace :: Text -> a -> a -- | Version of traceShow that leaves a warning. traceShow :: Show a => a -> b -> b -- | Version of traceShowId that leaves a warning. traceShowId :: Show a => 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. Useful to tag -- printed data, for instance: -- --
--   traceShowIdWith ("My data: ", ) (veryLargeExpression)
--   
traceShowIdWith :: Show s => (a -> s) -> a -> a -- | Version of traceShowM that leaves a warning. traceShowM :: (Show a, Monad m) => a -> m () -- | Version of traceM that leaves a warning and takes Text. traceM :: Monad m => Text -> m () -- | Version of traceId that leaves a warning. traceId :: Text -> Text -- | Type class for converting other strings to String. class ToString a toString :: ToString a => a -> String -- | Type class for converting other strings to Text. class ToLText a toLText :: ToLText a => a -> Text -- | Type class for converting other strings to Text. class ToText a toText :: ToText a => a -> Text -- | 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 synonym for ByteString. type LByteString = ByteString -- | Type synonym for Text. type LText = Text -- | 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 -- | 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 -- | 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 ... -- | 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 -- | Replace an invalid input byte with the Unicode replacement character -- U+FFFD. lenientDecode :: OnDecodeError -- | Throw a UnicodeException if decoding fails. strictDecode :: OnDecodeError -- | A handler for a decoding error. type OnDecodeError = OnError Word8 Char -- | Function type for handling a coding error. It is supplied with two -- inputs: -- -- -- -- If the handler returns a value wrapped with Just, that value -- will be used in the output as the replacement for the invalid input. -- If it returns Nothing, no value will be used in the output. -- -- Should the handler need to abort processing, it should use -- error or throw an exception (preferably a -- UnicodeException). It may use the description provided to -- construct a more helpful error report. type OnError a b = String -> Maybe a -> Maybe b -- | An exception type for representing Unicode encoding errors. data UnicodeException -- | 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 -- | O(n) Breaks a Text up into a list of Texts at -- newline Chars. The resulting strings do not contain newlines. lines :: Text -> [Text] -- | O(n) Joins lines, after appending a terminating newline to -- each. unlines :: [Text] -> Text -- | O(n) Joins words using single space characters. unwords :: [Text] -> Text -- | O(n) Breaks a Text up into a list of words, delimited by -- Chars representing white space. words :: Text -> [Text] -- | O(c) Convert a strict Text into a lazy Text. fromStrict :: Text -> Text -- | Strict version of modifyTVar. modifyTVar' :: TVar a -> (a -> a) -> STM () -- | Synonym for throw throwM :: (MonadThrow m, Exception e) => e -> m a -- | Same as upstream catch, but will not catch asynchronous -- exceptions catch :: (MonadCatch m, Exception e) => m a -> (e -> m a) -> m a -- | catch specialized to catch all synchronous exception catchAny :: MonadCatch m => m a -> (SomeException -> m a) -> m a -- | Flipped version of catchAny handleAny :: MonadCatch m => (SomeException -> m a) -> m a -> m a -- | Same as upstream try, but will not catch asynchronous -- exceptions try :: (MonadCatch m, Exception e) => m a -> m (Either e a) -- | try specialized to catch all synchronous exceptions tryAny :: MonadCatch m => m a -> m (Either SomeException a) -- | Async safe version of onException onException :: MonadMask m => m a -> m b -> m a -- | Async safe version of bracket bracket :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c -- | Async safe version of bracket_ bracket_ :: MonadMask m => m a -> m b -> m c -> m c -- | Async safe version of finally finally :: MonadMask m => m a -> m b -> m a -- | Async safe version of bracketOnError bracketOnError :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c -- | withState f m executes action m on a state -- modified by applying f. -- -- withState :: (s -> s) -> State s a -> State s 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 state, discarding the final value. -- -- execStateT :: Monad m => StateT s m a -> s -> m s -- | Evaluate a state computation with the given initial state and return -- the final state, discarding the final value. -- -- execState :: State s a -> s -> s -- | Evaluate a state computation with the given initial state and return -- the final 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 value, discarding the final state. -- -- evalState :: State s a -> s -> a -- | Runs a Reader and extracts the final value from it. (The -- inverse of reader.) runReader :: Reader r a -> r -> a -- | A variant of modify in which the computation is strict in the -- new state. modify' :: MonadState s m => (s -> s) -> m () -- | TH utilities used in Indigo.Common.Expr module Indigo.Common.Expr.TH -- | Generates an Buildable instance for a Expr GADT. Note: This -- will not generate additional constraints to the generated instance if -- those are required. Inspired by deriveGADTNFData from -- Util.TH. deriveExprBuildable :: Name -> Q [Dec] -- | 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 -- | 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 data Bool False :: Bool True :: Bool -- | Arbitrary precision integers. In contrast with fixed-size integral -- types such as Int, the Integer type represents the -- entire infinite range of integers. -- -- Integers are stored in a kind of sign-magnitude form, hence do not -- expect two's complement form when using bit operations. -- -- If the value is small (fit into an Int), IS constructor -- is used. Otherwise IP and IN constructors are used to -- store a BigNat representing respectively the positive or the -- negative value magnitude. -- -- Invariant: IP and IN are used iff value doesn't fit in -- IS data Integer -- | Natural number -- -- Invariant: numbers <= 0xffffffffffffffff use the NS -- constructor data Natural -- | The Maybe type encapsulates an optional value. A value of type -- Maybe a either contains a value of type a -- (represented as Just a), or it is empty (represented -- as Nothing). Using Maybe is a good way to deal with -- errors or exceptional cases without resorting to drastic measures such -- as error. -- -- The Maybe type is also a monad. It is a simple kind of error -- monad, where all errors are represented by Nothing. A richer -- error monad can be built using the Either type. data Maybe a Nothing :: Maybe a Just :: a -> Maybe a -- | 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 set of values a. data Set a -- | 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 class for types with a default value. class Default a -- | The default value for this type. def :: Default a => a -- | Pretty-print a Lorentz contract into Michelson code. printLorentzContract :: Bool -> Contract cp st vd -> LText -- | Pretty-print a Haskell value as Michelson one. printLorentzValue :: NiceUntypedValue v => Bool -> v -> LText cdCompilationOptionsL :: Lens' (ContractData cp st vd) CompilationOptions cdCodeL :: forall cp st vd cp1. NiceParameterFull cp1 => Lens (ContractData cp st vd) (ContractData cp1 st vd) (ContractCode cp st) (ContractCode cp1 st) coStringTransformerL :: Lens' CompilationOptions (Bool, MText -> MText) coOptimizerConfL :: Lens' CompilationOptions (Maybe OptimizerConf) coBytesTransformerL :: Lens' CompilationOptions (Bool, ByteString -> ByteString) -- | Lorentz version of analyzer. analyzeLorentz :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> AnalyzerRes -- | Like interpretLorentzInstr, but works on singleton input and -- output stacks. interpretLorentzLambda :: (IsoValue inp, IsoValue out) => ContractEnv -> (IsNotInView => Fn inp out) -> inp -> Either (MichelsonFailureWithStack Void) out -- | Interpret a Lorentz instruction, for test purposes. Note that this -- does not run the optimizer. interpretLorentzInstr :: forall (inp :: [Type]) (out :: [Type]). (IsoValuesStack inp, IsoValuesStack out) => ContractEnv -> (IsNotInView => inp :-> out) -> Rec Identity inp -> Either (MichelsonFailureWithStack Void) (Rec Identity out) -- | Restrict type of Contract, ContractData or other similar -- type to have no views. noViews :: forall {k1} {k2} contract (cp :: k1) (st :: k2). contract cp st () -> contract cp st () -- | Version of setViews that accepts a Rec. -- -- May be useful if you have too many views or want to combine views -- sets. setViewsRec :: forall vd cp st. NiceViewsDescriptor vd => Rec (ContractView st) (RevealViews vd) -> ContractData cp st () -> ContractData cp st vd -- | Set all the contract's views. -- --
--   compileLorentzContract $
--     defaultContractData do
--       ...
--     & setViews
--       ( mkView "myView" () do
--           ...
--       , mkView "anotherView" Integer do
--           ...
--       )
--   
setViews :: forall vd cp st. (RecFromTuple (Rec (ContractView st) (RevealViews vd)), NiceViewsDescriptor vd) => IsoRecTuple (Rec (ContractView st) (RevealViews vd)) -> ContractData cp st () -> ContractData cp st vd -- | Compile a whole contract to Michelson. -- -- Note that compiled contract can be ill-typed in terms of Michelson -- code when some of the compilation options are used. However, -- compilation with defaultCompilationOptions should be valid. compileLorentzContract :: ContractData cp st vd -> Contract cp st vd -- | Compile contract with defaultCompilationOptions. defaultContractData :: (NiceParameterFull cp, NiceStorageFull st) => (IsNotInView => '[(cp, st)] :-> ContractOut st) -> ContractData cp st () -- | Construct a view. -- --
--   mkView @"add" @(Integer, Integer) do
--    car; unpair; add
--   
mkView :: forall (name :: Symbol) arg ret st. (KnownSymbol name, NiceViewable arg, NiceViewable ret, HasAnnotation arg, HasAnnotation ret, TypeHasDoc arg, TypeHasDoc ret) => ViewCode arg st ret -> ContractView st ('ViewTyInfo name arg ret) -- | Version of mkContract that accepts custom compilation options. mkContractWith :: (NiceParameterFull cp, NiceStorageFull st) => CompilationOptions -> ContractCode cp st -> Contract cp st () -- | Construct and compile Lorentz contract. -- -- Note that this accepts code with initial and final stacks unpaired for -- simplicity. mkContract :: (NiceParameterFull cp, NiceStorageFull st) => ContractCode cp st -> Contract cp st () -- | Construct and compile Lorentz contract. -- -- This is an alias for mkContract. defaultContract :: (NiceParameterFull cp, NiceStorageFull st) => (IsNotInView => '[(cp, st)] :-> ContractOut st) -> Contract cp st () -- | Compile Lorentz code, optionally running the optimizer, string and -- byte transformers. compileLorentzWithOptions :: forall (inp :: [Type]) (out :: [Type]). CompilationOptions -> (inp :-> out) -> Instr (ToTs inp) (ToTs out) -- | For use outside of Lorentz. Will use defaultCompilationOptions. compileLorentz :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> Instr (ToTs inp) (ToTs out) -- | Leave contract without any modifications. For testing purposes. intactCompilationOptions :: CompilationOptions -- | Runs Michelson optimizer with default config and does not touch -- strings and bytes. defaultCompilationOptions :: CompilationOptions -- | Options to control Lorentz to Michelson compilation. data CompilationOptions CompilationOptions :: Maybe OptimizerConf -> (Bool, MText -> MText) -> (Bool, ByteString -> ByteString) -> CompilationOptions -- | Config for Michelson optimizer. [coOptimizerConf] :: CompilationOptions -> Maybe OptimizerConf -- | Function to transform strings with. See -- transformStringsLorentz. [coStringTransformer] :: CompilationOptions -> (Bool, MText -> MText) -- | Function to transform byte strings with. See -- transformBytesLorentz. [coBytesTransformer] :: CompilationOptions -> (Bool, ByteString -> ByteString) -- | Code for a contract along with compilation options for the Lorentz -- compiler. -- -- It is expected that a Contract is one packaged entity, wholly -- controlled by its author. Therefore the author should be able to set -- all options that control contract's behavior. -- -- This helps ensure that a given contract will be interpreted in the -- same way in all environments, like production and testing. -- -- Raw ContractCode should not be used for distribution of -- contracts. data ContractData cp st vd ContractData :: ContractCode cp st -> Rec (ContractView st) (RevealViews vd) -> CompilationOptions -> ContractData cp st vd -- | The contract itself. [cdCode] :: ContractData cp st vd -> ContractCode cp st -- | Contract views. [cdViews] :: ContractData cp st vd -> Rec (ContractView st) (RevealViews vd) -- | General compilation options for the Lorentz compiler. [cdCompilationOptions] :: ContractData cp st vd -> CompilationOptions -- | Single contract view. data ContractView st (v :: ViewTyInfo) [ContractView] :: forall (name :: Symbol) arg ret st. (KnownSymbol name, NiceViewable arg, NiceViewable ret, HasAnnotation arg, HasAnnotation ret) => ViewCode arg st ret -> ContractView st ('ViewTyInfo name arg ret) -- | Note that calling given entrypoints involves constructing -- UParam. pbsUParam :: forall (ctorName :: Symbol). KnownSymbol ctorName => ParamBuildingStep -- | Make up UParam from ADT sum. -- -- Entry points template will consist of (constructorName, -- constructorFieldType) pairs. Each constructor is expected to have -- exactly one field. uparamFromAdt :: UParamLinearize up => up -> UParam (UParamLinearized up) -- | Like caseUParam, but accepts a tuple of clauses, not a -- Rec. 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 -- | Pattern-match on given UParam entries. -- -- You have to provide all case branches and a fallback action on case -- when entrypoint is not found. caseUParam :: forall (entries :: [EntrypointKind]) (inp :: [Type]) (out :: [Type]). (CaseUParam entries, RequireUniqueEntrypoints entries) => Rec (CaseClauseU inp out) entries -> UParamFallback inp out -> (UParam entries : inp) :-> out -- | Default implementation for UParamFallback, simply reports an -- error. uparamFallbackFail :: forall (inp :: [Type]) (out :: [Type]). UParamFallback inp out -- | Helper instruction which extracts content of UParam. unwrapUParam :: forall (entries :: [EntrypointKind]) (s :: [Type]). (UParam entries : s) :-> ((MText, ByteString) : s) -- | Construct a UParam safely. mkUParam :: forall a (name :: Symbol) (entries :: [EntrypointKind]). (NicePackedValue a, LookupEntrypoint name entries ~ a, RequireUniqueEntrypoints entries) => Label name -> a -> UParam entries -- | An entrypoint is described by two types: its name and type of -- argument. type EntrypointKind = (Symbol, Type) -- | A convenient alias for type-level name-something pair. type (n :: Symbol) ?: (a :: k) = '(n, a) -- | Encapsulates parameter for one of entry points. It keeps entrypoint -- name and corresponding argument serialized. -- -- In Haskell world, we keep an invariant of that contained value relates -- to one of entry points from entries list. newtype UParam (entries :: [EntrypointKind]) UnsafeUParam :: (MText, ByteString) -> UParam (entries :: [EntrypointKind]) -- | Pseudo value for UParam type variable. type SomeInterface = '[ '("SomeEntrypoints", Void)] -- | Homomorphic version of UParam, forgets the exact interface. type UParam_ = UParam SomeInterface -- | Get type of entrypoint argument by its name. type family LookupEntrypoint (name :: Symbol) (entries :: [EntrypointKind]) -- | Ensure that given entry points do no contain duplicated names. type family RequireUniqueEntrypoints (entries :: [EntrypointKind]) -- | This type can store any value that satisfies a certain constraint. data ConstrainedSome (c :: Type -> Constraint) [ConstrainedSome] :: forall (c :: Type -> Constraint) a. c a => a -> ConstrainedSome c -- | This class is needed to implement unpackUParam. class UnpackUParam (c :: Type -> Constraint) (entries :: [EntrypointKind]) -- | Turn UParam into a Haskell value. Since we don't know its type -- in compile time, we have to erase it using ConstrainedSome. The -- user of this function can require arbitrary constraint to hold -- (depending on how they want to use the result). unpackUParam :: UnpackUParam c entries => UParam entries -> Either EntrypointLookupError (MText, ConstrainedSome c) data EntrypointLookupError NoSuchEntrypoint :: MText -> EntrypointLookupError ArgumentUnpackFailed :: EntrypointLookupError -- | Implementations of some entry points. -- -- Note that this thing inherits properties of Rec, e.g. you can -- Data.Vinyl.Core.rappend implementations for two entrypoint -- sets when assembling scattered parts of a contract. type EntrypointsImpl (inp :: [Type]) (out :: [Type]) (entries :: [EntrypointKind]) = Rec CaseClauseU inp out entries -- | An action invoked when user-provided entrypoint is not found. type UParamFallback (inp :: [Type]) (out :: [Type]) = (MText, ByteString) : inp :-> out -- | Make up a "case" over entry points. class CaseUParam (entries :: [EntrypointKind]) -- | Constraint required by uparamFromAdt. type UParamLinearize p = (Generic p, GUParamLinearize Rep p) -- | Entry points template derived from given ADT sum. type UParamLinearized p = GUParamLinearized Rep p -- | Version of entryCase for contracts with recursive delegate -- parameter that needs to be flattened. Use it with EpdDelegate -- when you don't need hierarchical entrypoints in autodoc. You can also -- hide particular entrypoints with the first type parameter. Consider -- using entryCaseFlattened if you don't want to hide any -- entrypoints. -- --
--   entryCaseFlattenedHiding @'[Ep1, Ep2] ...
--   
entryCaseFlattenedHiding :: forall (heps :: [Symbol]) cp (out :: [Type]) (inp :: [Type]) clauses. (CaseTC cp out inp clauses, DocumentEntrypoints (FlattenedEntrypointsKindHiding heps) cp, HasEntrypoints (ParameterEntrypointsDerivation cp) cp heps) => IsoRecTuple clauses -> (cp : inp) :-> out -- | Version of entryCase_ for contracts with recursive delegate -- parameter that needs to be flattened. Use it with EpdDelegate -- when you don't need hierarchical entrypoints in autodoc. You can also -- hide particular entrypoints with the type parameter. Consider using -- entryCaseFlattened_ if you don't want to hide any entrypoints. entryCaseFlattenedHiding_ :: forall (heps :: [Symbol]) cp (out :: [Type]) (inp :: [Type]). (InstrCaseC cp, RMap (CaseClauses cp), DocumentEntrypoints (FlattenedEntrypointsKindHiding heps) cp, HasEntrypoints (ParameterEntrypointsDerivation cp) cp heps) => Rec (CaseClauseL inp out) (CaseClauses cp) -> (cp : inp) :-> out -- | Version of entryCase for contracts with recursive parameter -- that needs to be flattened. Use it with EpdRecursive when you -- don't need intermediary nodes in autodoc. entryCaseFlattened :: forall cp (out :: [Type]) (inp :: [Type]) clauses. (CaseTC cp out inp clauses, DocumentEntrypoints FlattenedEntrypointsKind cp) => IsoRecTuple clauses -> (cp : inp) :-> out -- | Version of entryCase_ for contracts with recursive parameter -- that needs to be flattened. Use it with EpdRecursive when you -- don't need intermediary nodes in autodoc. entryCaseFlattened_ :: forall cp (out :: [Type]) (inp :: [Type]). (InstrCaseC cp, RMap (CaseClauses cp), DocumentEntrypoints FlattenedEntrypointsKind cp) => Rec (CaseClauseL inp out) (CaseClauses cp) -> (cp : inp) :-> out -- | Version of entryCase_ for contracts with flat parameter. entryCaseSimple_ :: forall cp (out :: [Type]) (inp :: [Type]). (InstrCaseC cp, RMap (CaseClauses cp), DocumentEntrypoints PlainEntrypointsKind cp, RequireFlatParamEps cp) => Rec (CaseClauseL inp out) (CaseClauses cp) -> (cp : inp) :-> out -- | Whether finalizeParamCallingDoc has already been applied to -- these steps. areFinalizedParamBuildingSteps :: [ParamBuildingStep] -> Bool -- | Modify param building steps with respect to entrypoints that given -- parameter declares. -- -- Each contract with entrypoints should eventually call this function, -- otherwise, in case if contract uses built-in entrypoints feature, the -- resulting parameter building steps in the generated documentation will -- not consider entrypoints and thus may be incorrect. -- -- Calling this twice over the same code is also prohibited. -- -- This method is for internal use, if you want to apply it to a contract -- manually, use finalizeParamCallingDoc. finalizeParamCallingDoc' :: forall cp (inp :: [Type]) (out :: [Type]). (NiceParameterFull cp, HasCallStack) => Proxy cp -> (inp :-> out) -> inp :-> out -- | Wrapper for documenting single entrypoint which parameter isn't going -- to be unwrapped from some datatype. -- -- entryCase unwraps a datatype, however, sometimes we want to -- have entrypoint parameter to be not wrapped into some datatype. documentEntrypoint :: forall kind (epName :: Symbol) param (s :: [Type]) (out :: [Type]). (KnownSymbol epName, DocItem (DEntrypoint kind), NiceParameter param, TypeHasDoc param) => ((param : s) :-> out) -> (param : s) :-> out -- | Go over contract code and update every occurrence of -- DEntrypointArg documentation item, adding the given step to its -- "how to build parameter" description. clarifyParamBuildingSteps :: forall (inp :: [Type]) (out :: [Type]). ParamBuildingStep -> (inp :-> out) -> inp :-> out mkDEntrypointArgSimple :: (NiceParameter t, TypeHasDoc t) => DEntrypointArg mkDEpUType :: HasAnnotation t => Ty emptyDEpArg :: DEntrypointArg -- | Make a ParamBuildingStep that tells about wrapping an argument -- into a constructor with given name and uses given ParamBuilder -- as description of Michelson part. mkPbsWrapIn :: Text -> ParamBuilder -> ParamBuildingStep -- | Mark code as part of entrypoint with given name. -- -- This is automatically called at most of the appropriate situations, -- like entryCase calls. entrypointSection :: forall kind (i :: [Type]) (o :: [Type]). EntrypointKindHasDoc kind => Text -> Proxy kind -> (i :-> o) -> i :-> o -- | Default implementation of docItemToMarkdown for entrypoints. diEntrypointToMarkdown :: HeaderLevel -> DEntrypoint level -> Markdown -- | Pattern that checks whether given SomeDocItem hides -- DEntrypoint inside (of any entrypoint kind). -- -- In case a specific kind is necessary, use plain (cast -> Just -- DEntrypoint{..}) construction instead. pattern DEntrypointDocItem :: () => DEntrypoint kind -> SomeDocItem -- | Gathers information about single entrypoint. -- -- We assume that entry points might be of different kinds, which is -- designated by phantom type parameter. For instance, you may want to -- have several groups of entry points corresponding to various parts of -- a contract - specifying different kind type argument for each -- of those groups will allow you defining different DocItem -- instances with appropriate custom descriptions for them. data DEntrypoint kind DEntrypoint :: Text -> SubDoc -> DEntrypoint kind [depName] :: DEntrypoint kind -> Text [depSub] :: DEntrypoint kind -> SubDoc -- | Can be used to make a kind equivalent to some other kind; if changing -- this, entrypointKindPos and entrypointKindSectionName -- will be ignored. type family EntrypointKindOverride ep -- | Describes location of entrypoints of the given kind. -- -- All such entrypoints will be placed under the same "entrypoints" -- section, and this instance defines characteristics of this section. class Typeable ep => EntrypointKindHasDoc ep where { -- | Can be used to make a kind equivalent to some other kind; if changing -- this, entrypointKindPos and entrypointKindSectionName -- will be ignored. type family EntrypointKindOverride ep; type EntrypointKindOverride ep = ep; } -- | Implement this when specifying EntrypointKindOverride. This -- should never be normally used, but because MINIMAL pragma -- can't specify type families, we use this hack. -- -- Default implementation is a bottom (i.e. a runtime error). -- -- If implemented, it should be -- --
--   entrypointKindOverrideSpecified = Dict
--   
entrypointKindOverrideSpecified :: EntrypointKindHasDoc ep => Dict ((EntrypointKindOverride ep == ep) ~ 'False) -- | Position of the respective entrypoints section in the doc. This shares -- the same positions space with all other doc items. entrypointKindPos :: EntrypointKindHasDoc ep => Natural -- | Name of the respective entrypoints section. entrypointKindSectionName :: EntrypointKindHasDoc ep => Text -- | Description in the respective entrypoints section. entrypointKindSectionDescription :: EntrypointKindHasDoc ep => Maybe Markdown -- | Default value for DEntrypoint type argument. data PlainEntrypointsKind -- | Special entrypoint kind that flattens one level of recursive -- entrypoints. -- -- With EpdRecursive, intermediary nodes are hidden from -- documentation. -- -- With EpdDelegate, intermediary nodes will still be shown. -- -- Any entrypoints can be omitted from docs by listing those in the type -- parameter (which is especially helpful with EpdDelegate). -- -- For other entrypoint derivation strategies (e.g. EpdPlain), -- behaves like PlainEntrypointsKind (with the exception of hiding -- entrypoints from docs) -- -- If you have several levels of recursion, each level will need to have -- this kind. -- -- Note that list of entrypoints to be hidden is not checked by default. -- Use entryCaseFlattenedHiding to have a static check that -- entrypoints to be hidden do indeed exist. data FlattenedEntrypointsKindHiding (hiddenEntrypoints :: [Symbol]) -- | A convenience type synonym for FlattenedEntrypointsKindHiding -- not hiding any entrypoitns. type FlattenedEntrypointsKind = FlattenedEntrypointsKindHiding '[] :: [Symbol] -- | Describes the behaviour common for all entrypoints. -- -- For instance, if your contract runs some checks before calling any -- entrypoint, you probably want to wrap those checks into -- entrypointSection "Prior checks" (Proxy -- @CommonContractBehaviourKind). data CommonContractBehaviourKind -- | Describes the behaviour common for entrypoints of given kind. -- -- This has very special use cases, like contracts with mix of -- upgradeable and permanent entrypoints. data CommonEntrypointsBehaviourKind (kind :: k) -- | Inserts a reference to an existing entrypoint. -- -- This helps to avoid duplication in the generated documentation, in -- order not to overwhelm the reader. data DEntrypointReference DEntrypointReference :: Text -> Anchor -> DEntrypointReference -- | When describing the way of parameter construction - piece of -- incremental builder for this description. newtype ParamBuilder ParamBuilder :: (Markdown -> Markdown) -> ParamBuilder -- | Argument stands for previously constructed parameter piece, and -- returned value - a piece constructed after our step. [unParamBuilder] :: ParamBuilder -> Markdown -> Markdown data ParamBuildingDesc ParamBuildingDesc :: Markdown -> ParamBuilder -> ParamBuilder -> ParamBuildingDesc -- | Plain english description of this step. [pbdEnglish] :: ParamBuildingDesc -> Markdown -- | How to construct parameter in Haskell code. [pbdHaskell] :: ParamBuildingDesc -> ParamBuilder -- | How to construct parameter working on raw Michelson. [pbdMichelson] :: ParamBuildingDesc -> ParamBuilder -- | Describes a parameter building step. -- -- This can be wrapping into (Haskell) constructor, or a more complex -- transformation. data ParamBuildingStep -- | Wraps something into constructor with given name. Constructor should -- be the one which corresponds to an entrypoint defined via field -- annotation, for more complex cases use PbsCustom. PbsWrapIn :: Text -> ParamBuildingDesc -> ParamBuildingStep -- | Directly call an entrypoint marked with a field annotation. PbsCallEntrypoint :: EpName -> ParamBuildingStep -- | Other action. PbsCustom :: ParamBuildingDesc -> ParamBuildingStep -- | This entrypoint cannot be called, which is possible when an explicit -- default entrypoint is present. This is not a true entrypoint but just -- some intermediate node in or tree and neither it nor any of -- its parents are marked with a field annotation. -- -- It contains dummy ParamBuildingSteps which were assigned before -- entrypoints were taken into account. PbsUncallable :: [ParamBuildingStep] -> ParamBuildingStep -- | Entrypoint argument type in typed representation. data SomeEntrypointArg SomeEntrypointArg :: Proxy a -> SomeEntrypointArg -- | Describes argument of an entrypoint. data DEntrypointArg DEntrypointArg :: Maybe SomeEntrypointArg -> [ParamBuildingStep] -> DEntrypointArg -- | Argument of the entrypoint. Pass Nothing if no argument is -- required. [epaArg] :: DEntrypointArg -> Maybe SomeEntrypointArg -- | Describes a way to lift an entrypoint argument into full parameter -- which can be passed to the contract. -- -- Steps are supposed to be applied in the order opposite to one in which -- they are given. E.g. suppose that an entrypoint is called as Run -- (Service1 arg); then the first step (actual last) should describe -- wrapping into Run constructor, and the second step (actual -- first) should be about wrapping into Service1 constructor. [epaBuilding] :: DEntrypointArg -> [ParamBuildingStep] -- | Pick a type documentation from CtorField. class KnownSymbol con => DeriveCtorFieldDoc (con :: Symbol) (cf :: CtorField) deriveCtorFieldDoc :: DeriveCtorFieldDoc con cf => DEntrypointArg -- | Constraint for documentEntrypoints. type DocumentEntrypoints kind a = (Generic a, GDocumentEntrypoints BuildEPTree' a kind Rep a '[] :: [CaseClauseParam]) -- | Provides arror for convenient entrypoint documentation class EntryArrow (kind :: k) (name :: Symbol) body -- | Lift entrypoint implementation. -- -- Entrypoint names should go with "e" prefix. (#->) :: EntryArrow kind name body => (Label name, Proxy kind) -> body -> body type family RequireFlatParamEps cp type family RequireFlatEpDerivation (cp :: t) deriv -- | Version of stAlias adopted to labels. stNickname :: forall (name :: Symbol). Label name -> FieldRef (FieldAlias name) -- | Construct an alias at term level. -- -- This requires passing the alias via type annotation. stAlias :: forall {k} (alias :: k). FieldRef (FieldAlias alias) -- | Provides alternative variadic interface for deep entries access. -- -- Example: stToField (stNested #a #b #c) stNested :: StNestedImpl f SelfRef => f -- | An alias for SelfRef. -- -- Examples: -- --
--   >>> push 5 # stMem this -$ (mempty :: Map Integer MText)
--   False
--   
-- --
--   >>> stGetField this # pair -$ (5 :: Integer)
--   (5,5)
--   
this :: forall (p :: FieldRefTag). SelfRef p -- | Utility to create EntrypointsFields from an entrypoint name -- (epName) and an EntrypointLambda implementation. Note -- that you need to merge multiple of these (with <>) if -- your field contains more than one entrypoint lambda. mkStoreEp :: forall (epName :: Symbol) epParam epStore. Label epName -> EntrypointLambda epParam epStore -> EntrypointsField epParam epStore -- | Turn submap operations into operations on a part of the submap value. -- -- Normally, if you need this set of operations, it would be better to -- split your submap into several separate submaps, each operating with -- its own part of the value. This set of operations is pretty -- inefficient and exists only as a temporary measure, if due to -- historical reasons you have to leave storage format intact. -- -- This implementation puts no distinction between value == -- Nothing and value == Just defValue cases. Getters, when -- notice a value equal to the default value, report its absence. Setters -- tend to remove the value from submap when possible. -- -- LIso (Maybe value) value and LIso (Maybe subvalue) -- subvalue arguments describe how to get a value if it was absent -- in map and how to detect when it can be safely removed from map. -- -- Example of use: zoomStoreSubmapOps #mySubmap nonDefIso nonDefIso -- storeSubmapOps storeFieldOpsADT zoomStoreSubmapOps :: forall {k1} {k2} store (submapName :: k1) (nameInSubmap :: k2) key value subvalue. (NiceConstant value, NiceConstant subvalue, Dupable key, Dupable store) => FieldRef submapName -> LIso (Maybe value) value -> LIso (Maybe subvalue) subvalue -> StoreSubmapOps store submapName key value -> StoreFieldOps value nameInSubmap subvalue -> StoreSubmapOps store nameInSubmap key subvalue composeStoreEntrypointOps :: forall {k} store substore (nameInStore :: k) (epName :: Symbol) epParam epStore. (HasDupableGetters store, Dupable substore) => FieldRef nameInStore -> StoreFieldOps store nameInStore substore -> StoreEntrypointOps substore epName epParam epStore -> StoreEntrypointOps store epName epParam epStore -- | Chain implementations of two submap operations sets. Used to provide -- shortcut access to a nested submap. -- -- This is very inefficient since on each access to substore it has to be -- serialized/deserialized. Use this implementation only if due to -- historical reasons migrating storage is difficult. -- -- LIso (Maybe substore) substore argument describes how to get -- substore value if it was absent in map and how to detect when -- it can be safely removed. -- -- Example of use: sequenceStoreSubmapOps #mySubmap nonDefIso -- storeSubmapOps storeSubmapOps sequenceStoreSubmapOps :: forall {k1} {k2} store substore value (name :: k1) (subName :: k2) key1 key2. (NiceConstant substore, KnownValue value, Dupable (key1, key2), Dupable store) => FieldRef name -> LIso (Maybe substore) substore -> StoreSubmapOps store name key1 substore -> StoreSubmapOps substore subName key2 value -> StoreSubmapOps store subName (key1, key2) value -- | Chain implementations of field and submap operations. -- -- This requires Dupable substore for simplicity, in most cases -- it is possible to use a different chaining (nameInStore :-| mname -- :-| this) to avoid that constraint. If this constraint is still -- an issue, please create a ticket. composeStoreSubmapOps :: forall {k1} {k2} store substore (nameInStore :: k1) (mname :: k2) key value. (HasDupableGetters store, Dupable substore) => FieldRef nameInStore -> StoreFieldOps store nameInStore substore -> StoreSubmapOps substore mname key value -> StoreSubmapOps store mname key value -- | Chain two implementations of field operations. -- -- Suits for a case when your store does not contain its fields directly -- rather has a nested structure. composeStoreFieldOps :: forall {k1} {k2} substore (nameInStore :: k1) store (nameInSubstore :: k2) field. HasDupableGetters substore => FieldRef nameInStore -> StoreFieldOps store nameInStore substore -> StoreFieldOps substore nameInSubstore field -> StoreFieldOps store nameInSubstore field -- | Change submap operations so that they work on a modified value. mapStoreSubmapOpsValue :: forall {k} value1 value2 store (name :: k) key. (KnownValue value1, KnownValue value2) => LIso value1 value2 -> StoreSubmapOps store name key value1 -> StoreSubmapOps store name key value2 -- | Change submap operations so that they work on a modified key. mapStoreSubmapOpsKey :: forall {k} key2 key1 store (name :: k) value. Fn key2 key1 -> StoreSubmapOps store name key1 value -> StoreSubmapOps store name key2 value -- | Change field operations so that they work on a modified field. -- -- For instance, to go from StoreFieldOps Storage "name" Integer -- to StoreFieldOps Storage "name" (value :! Integer) you can -- use mapStoreFieldOps (namedIso #value) mapStoreFieldOps :: forall {k} field1 field2 store (name :: k). KnownValue field1 => LIso field1 field2 -> StoreFieldOps store name field1 -> StoreFieldOps store name field2 -- | Pretend that given StoreEntrypointOps implementation is made up -- for entrypoint with name desiredName, not its actual name. -- Logic of the implementation remains the same. -- -- See also storeSubmapOpsReferTo. storeEntrypointOpsReferTo :: forall (epName :: Symbol) store epParam epStore (desiredName :: Symbol). Label epName -> StoreEntrypointOps store epName epParam epStore -> StoreEntrypointOps store desiredName epParam epStore -- | Pretend that given StoreFieldOps implementation is made up for -- field with name desiredName, not its actual name. Logic of -- the implementation remains the same. -- -- See also storeSubmapOpsReferTo. storeFieldOpsReferTo :: forall {k1} {k2} (name :: k1) storage field (desiredName :: k2). FieldRef name -> StoreFieldOps storage name field -> StoreFieldOps storage desiredName field -- | Pretend that given StoreSubmapOps implementation is made up for -- submap with name desiredName, not its actual name. Logic of -- the implementation remains the same. -- -- Use case: imagine that your code requires access to submap named -- X, but in your storage that submap is called Y. Then -- you implement the instance which makes X refer to Y: -- --
--   instance StoreHasSubmap Store X Key Value where
--     storeSubmapOps = storeSubmapOpsReferTo #Y storeSubmapOpsForY
--   
storeSubmapOpsReferTo :: forall {k1} {k2} (name :: k1) storage key value (desiredName :: k2). FieldRef name -> StoreSubmapOps storage name key value -> StoreSubmapOps storage desiredName key value -- | Implementation of StoreHasEntrypoint for a data type which has -- an instance of StoreHasEntrypoint inside. For instance, it can -- be used for top-level storage. storeEntrypointOpsDeeper :: forall store (nameInStore :: Symbol) substore (epName :: Symbol) epParam epStore. (HasFieldOfType store nameInStore substore, StoreHasEntrypoint substore epName epParam epStore, HasDupableGetters store, Dupable substore) => FieldRef nameInStore -> StoreEntrypointOps store epName epParam epStore -- | Implementation of StoreHasSubmap for a data type which has an -- instance of StoreHasSubmap inside. For instance, it can be used -- for top-level storage. storeSubmapOpsDeeper :: forall {k} storage (bigMapPartName :: Symbol) fields key value (mname :: k). (HasFieldOfType storage bigMapPartName fields, StoreHasSubmap fields SelfRef key value, HasDupableGetters storage, Dupable fields) => FieldRef bigMapPartName -> StoreSubmapOps storage mname key value -- | Implementation of StoreHasField for a data type which has an -- instance of StoreHasField inside. For instance, it can be used -- for top-level storage. storeFieldOpsDeeper :: forall {k} storage (fieldsPartName :: Symbol) fields (fname :: k) ftype. (HasFieldOfType storage fieldsPartName fields, StoreHasField fields fname ftype, HasDupableGetters fields) => FieldRef fieldsPartName -> StoreFieldOps storage fname ftype -- | Implementation of StoreHasEntrypoint for a datatype that has a -- StoreHasSubmap that contains the entrypoint and a -- StoreHasField for the field such entrypoint operates on. 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 -- | Implementation of StoreHasEntrypoint for a datatype that has a -- StoreHasField for an EntrypointsField that contains the -- entrypoint and a StoreHasField for the field such entrypoint -- operates on. 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 -- | Implementation of StoreHasEntrypoint for a datatype keeping a -- pack of fields, among which one contains the entrypoint and another is -- what such entrypoint operates on. 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 -- | Implementation of StoreHasField for case of datatype keeping a -- pack of fields. storeFieldOpsADT :: forall dt (fname :: Symbol) ftype. HasFieldOfType dt fname ftype => StoreFieldOps dt fname ftype -- | Update the sub-storage that the entrypoint operates on. stSetEpStore :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (epStore : (store : s)) :-> (store : s) -- | Get the sub-storage that the entrypoint operates on, preserving the -- storage itself on the stack. stGetEpStore :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). (StoreHasEntrypoint store epName epParam epStore, Dupable store) => Label epName -> (store : s) :-> (epStore : (store : s)) -- | Pick the sub-storage that the entrypoint operates on. stToEpStore :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (epStore : s) -- | Stores the entrypoint lambda in the storage. Fails if already set. stSetEpLambda :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). (StoreHasEntrypoint store epName epParam epStore, HasDupableGetters store) => Label epName -> (EntrypointLambda epParam epStore : (store : s)) :-> (store : s) -- | Get stored entrypoint lambda, preserving the storage itself on the -- stack. stGetEpLambda :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). (StoreHasEntrypoint store epName epParam epStore, Dupable store) => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : (store : s)) -- | Pick stored entrypoint lambda. stToEpLambda :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : s) -- | Extracts and executes the epName entrypoint lambda from -- storage, returing the updated full storage (store) and the -- produced Operations. stEntrypoint :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). (StoreHasEntrypoint store epName epParam epStore, Dupable store) => Label epName -> (epParam : (store : s)) :-> (([Operation], store) : s) -- | Atomically get and update a value in storage. stGetAndUpdate :: forall {k} store (mname :: k) key value (s :: [Type]). StoreHasSubmap store mname key value => FieldRef mname -> (key : (Maybe value : (store : s))) :-> (Maybe value : (store : s)) -- | Update storage field. stSetField :: forall {k} store (fname :: k) ftype (s :: [Type]). StoreHasField store fname ftype => FieldRef fname -> (ftype : (store : s)) :-> (store : s) -- | Version of stToFieldNamed that preserves the storage on stack. stGetFieldNamed :: forall {k} store (fname :: k) ftype (s :: [Type]). (StoreHasField store fname ftype, FieldRefHasFinalName fname, Dupable ftype, HasDupableGetters store) => FieldRef fname -> (store : s) :-> ((FieldRefFinalName fname :! ftype) : (store : s)) -- | Pick storage field retaining a name label attached. -- -- For complex refs this tries to attach the immediate name of the -- referred field. stToFieldNamed :: forall {k} store (fname :: k) ftype (s :: [Type]). (StoreHasField store fname ftype, FieldRefHasFinalName fname) => FieldRef fname -> (store : s) :-> ((FieldRefFinalName fname :! ftype) : s) -- | Get storage field, preserving the storage itself on stack. stGetField :: forall {k} store (fname :: k) ftype (s :: [Type]). (StoreHasField store fname ftype, Dupable ftype, HasDupableGetters store) => FieldRef fname -> (store : s) :-> (ftype : (store : s)) -- | Pick storage field. stToField :: forall {k} store (fname :: k) ftype (s :: [Type]). StoreHasField store fname ftype => FieldRef fname -> (store : s) :-> (ftype : s) -- | Simplified version of sopSetFieldOpen where res is -- ftype. sopSetField :: forall {k} store (fname :: k) ftype (s :: [Type]). StoreFieldOps store fname ftype -> FieldRef fname -> (ftype : (store : s)) :-> (store : s) -- | Simplified version of sopGetFieldOpen where res is -- ftype. sopGetField :: forall {k} ftype store (fname :: k) (s :: [Type]). (Dupable ftype, HasDupableGetters store) => StoreFieldOps store fname ftype -> FieldRef fname -> (store : s) :-> (ftype : (store : s)) -- | Convert a label to FieldRef, useful for compatibility with -- other interfaces. fieldNameFromLabel :: forall (n :: Symbol). Label n -> FieldSymRef n -- | Convert a symbolic FieldRef to a label, useful for -- compatibility with other interfaces. fieldNameToLabel :: forall (n :: Symbol). FieldSymRef n -> Label n -- | Open kind for various field references. -- -- The simplest field reference could be Label, pointing to a -- field by its name, but we also support more complex scenarios like -- deep fields identifiers. type FieldRefKind = FieldRefTag -> Type data FieldRefTag type family FieldRefObject (ty :: k) = (fr :: FieldRefKind) | fr -> k ty -- | For a type-level field reference - an associated term-level -- representation. -- -- This is similar to singletons Sing + SingI -- pair but has small differences: -- -- class KnownFieldRef (ty :: k) where { type family FieldRefObject (ty :: k) = (fr :: FieldRefKind) | fr -> k ty; } mkFieldRef :: forall (p :: FieldRefTag). KnownFieldRef ty => FieldRefObject ty p -- | Some kind of reference to a field. -- -- The idea behind this type is that in trivial case (name :: -- Symbol) it can be instantiated with a mere label, but it is -- generic enough to allow complex field references as well. type FieldRef (name :: k) = FieldRefObject name 'FieldRefTag -- | The simplest field reference - just a name. Behaves similarly to -- Label. data FieldName (n :: Symbol) (p :: FieldRefTag) -- | Version of FieldRef restricted to symbolic labels. -- --
--   FieldSymRef name ≡ FieldName name 'FieldRefTag
--   
type FieldSymRef (name :: Symbol) = FieldRef name type family FieldRefFinalName (fr :: k) :: Symbol -- | Provides access to the direct name of the referred field. -- -- This is used in stToFieldNamed. class FieldRefHasFinalName (fr :: k) where { type family FieldRefFinalName (fr :: k) :: Symbol; } fieldRefFinalName :: FieldRefHasFinalName fr => FieldRef fr -> Label (FieldRefFinalName fr) -- | Datatype containing the full implementation of StoreHasField -- typeclass. -- -- We use this grouping because in most cases the implementation will be -- chosen among the default ones, and initializing all methods at once is -- simpler and more consistent. (One can say that we are trying to -- emulate the DerivingVia extension.) data StoreFieldOps store (fname :: k) ftype StoreFieldOps :: (forall (s :: [Type]). () => FieldRef fname -> (store : s) :-> (ftype : s)) -> (forall res (s :: [Type]). HasDupableGetters store => ('[ftype] :-> '[res, ftype]) -> ('[ftype] :-> '[res]) -> FieldRef fname -> (store : s) :-> (res : (store : s))) -> (forall new (s :: [Type]). () => ('[new, ftype] :-> '[ftype]) -> FieldRef fname -> (new : (store : s)) :-> (store : s)) -> StoreFieldOps store (fname :: k) ftype [sopToField] :: StoreFieldOps store (fname :: k) ftype -> forall (s :: [Type]). () => FieldRef fname -> (store : s) :-> (ftype : s) -- | See getFieldOpen for explanation of the signature. [sopGetFieldOpen] :: StoreFieldOps store (fname :: k) ftype -> forall res (s :: [Type]). HasDupableGetters store => ('[ftype] :-> '[res, ftype]) -> ('[ftype] :-> '[res]) -> FieldRef fname -> (store : s) :-> (res : (store : s)) -- | See setFieldOpen for explanation of the signature. [sopSetFieldOpen] :: StoreFieldOps store (fname :: k) ftype -> forall new (s :: [Type]). () => ('[new, ftype] :-> '[ftype]) -> FieldRef fname -> (new : (store : s)) :-> (store : s) -- | Provides operations on fields for storage. class StoreHasField store (fname :: k) ftype | store fname -> ftype storeFieldOps :: StoreHasField store fname ftype => StoreFieldOps store fname ftype -- | Datatype containing the full implementation of StoreHasSubmap -- typeclass. -- -- We use this grouping because in most cases the implementation will be -- chosen among the default ones, and initializing all methods at once is -- simpler and more consistent. (One can say that we are trying to -- emulate the DerivingVia extension.) data StoreSubmapOps store (mname :: k) key value StoreSubmapOps :: (forall (s :: [Type]). () => FieldRef mname -> (key : (store : s)) :-> (Bool : s)) -> (forall (s :: [Type]). KnownValue value => FieldRef mname -> (key : (store : s)) :-> (Maybe value : s)) -> (forall (s :: [Type]). () => FieldRef mname -> (key : (Maybe value : (store : s))) :-> (store : s)) -> (forall (s :: [Type]). () => FieldRef mname -> (key : (Maybe value : (store : s))) :-> (Maybe value : (store : s))) -> (forall (s :: [Type]). () => FieldRef mname -> (key : (store : s)) :-> (store : s)) -> (forall (s :: [Type]). () => FieldRef mname -> (key : (value : (store : s))) :-> (store : s)) -> StoreSubmapOps store (mname :: k) key value [sopMem] :: StoreSubmapOps store (mname :: k) key value -> forall (s :: [Type]). () => FieldRef mname -> (key : (store : s)) :-> (Bool : s) [sopGet] :: StoreSubmapOps store (mname :: k) key value -> forall (s :: [Type]). KnownValue value => FieldRef mname -> (key : (store : s)) :-> (Maybe value : s) [sopUpdate] :: StoreSubmapOps store (mname :: k) key value -> forall (s :: [Type]). () => FieldRef mname -> (key : (Maybe value : (store : s))) :-> (store : s) [sopGetAndUpdate] :: StoreSubmapOps store (mname :: k) key value -> forall (s :: [Type]). () => FieldRef mname -> (key : (Maybe value : (store : s))) :-> (Maybe value : (store : s)) [sopDelete] :: StoreSubmapOps store (mname :: k) key value -> forall (s :: [Type]). () => FieldRef mname -> (key : (store : s)) :-> (store : s) [sopInsert] :: StoreSubmapOps store (mname :: k) key value -> forall (s :: [Type]). () => FieldRef mname -> (key : (value : (store : s))) :-> (store : s) -- | Provides operations on submaps of storage. class StoreHasSubmap store (mname :: k) key value | store mname -> key value storeSubmapOps :: StoreHasSubmap store mname key value => StoreSubmapOps store mname key value -- | Type synonym for a Lambda that can be used as an entrypoint type EntrypointLambda param store = Lambda (param, store) ([Operation], store) -- | Type synonym of a BigMap mapping MText (entrypoint -- names) to EntrypointLambda. -- -- This is useful when defining instances of StoreHasEntrypoint as -- a storage field containing one or more entrypoints (lambdas) of the -- same type. type EntrypointsField param store = BigMap MText EntrypointLambda param store -- | Datatype containing the full implementation of -- StoreHasEntrypoint typeclass. -- -- We use this grouping because in most cases the implementation will be -- chosen among the default ones, and initializing all methods at once is -- simpler and more consistent. (One can say that we are trying to -- emulate the DerivingVia extension.) data StoreEntrypointOps store (epName :: Symbol) epParam epStore StoreEntrypointOps :: (forall (s :: [Type]). () => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : s)) -> (forall (s :: [Type]). HasDupableGetters store => 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]). HasDupableGetters store => 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) -- | Provides operations on stored entrypoints. -- -- store is the storage containing both the entrypoint -- epName (note: it has to be in a BigMap to take -- advantage of lazy evaluation) and the epStore field this -- operates on. class StoreHasEntrypoint store (epName :: Symbol) epParam epStore | store epName -> epParam epStore storeEpOps :: StoreHasEntrypoint store epName epParam epStore => StoreEntrypointOps store epName epParam epStore -- | Refer to a nested entry in storage. -- -- Example: stToField (#a :-| #b) fetches field b in -- the type under field a. -- -- If not favouring this name much, you can try an alias from -- Lorentz.StoreClass.Extra. data ( (l :: k1) :-| (r :: k2) ) (p :: FieldRefTag) (:-|) :: FieldRef l -> FieldRef r -> (:-|) (l :: k1) (r :: k2) (p :: FieldRefTag) infixr 8 :-| infixr 8 :-| -- | Refer to no particular field, access itself. data SelfRef (p :: FieldRefTag) SelfRef :: SelfRef (p :: FieldRefTag) -- | Alias for a field reference. -- -- This allows creating _custom_ field references; you will have to -- define the respective StoreHasField and StoreHasSubmap -- instances manually. Since this type occupies a different "namespace" -- than string labels and :-|, no overlappable instances will be -- necessary. -- -- Example: -- --
--   -- Shortcut for a deeply nested field X
--   data FieldX
--   
--   instance StoreHasField Storage (FieldAlias FieldX) Integer where
--     ...
--   
--   accessX = stToField (stAlias @FieldX)
--   
-- -- Note that alias type argument allows instantiations of any -- kind. data FieldAlias (alias :: k) (p :: FieldRefTag) -- | Kind-restricted version of FieldAlias to work solely with -- string labels. type FieldNickname (alias :: Symbol) = FieldAlias alias -- | Indicates a submap with given key and value types. data (k2 :: k) ~> (v :: k1) infix 9 ~> -- | Indicates a stored entrypoint with the given param and -- store types. data (param :: k) ::-> (store :: k1) infix 9 ::-> -- | Concise way to write down constraints with expected content of a -- storage. -- -- Use it like follows: -- --
--   type StorageConstraint store = StorageContains store
--     [ "fieldInt" := Int
--     , "fieldNat" := Nat
--     , "epsToNat" := Int ::-> Nat
--     , "balances" := Address ~> Int
--     ]
--   
-- -- Note that this won't work with complex field references, they have to -- be included using e.g. StoreHasField manually. type family StorageContains store (content :: [NamedField]) -- | Handlers for most common errors defined in Lorentz. baseErrorDocHandlers :: [NumericErrorDocHandler] -- | Handler for VoidResult. voidResultDocHandler :: NumericErrorDocHandler -- | Handler for all CustomErrors. customErrorDocHandler :: NumericErrorDocHandler -- | Extended version of applyErrorTagToErrorsDoc which accepts -- error handlers. -- -- In most cases that function should be enough for your purposes, but it -- uses a fixed set of base handlers which may be not enough in case when -- you define your own errors. In this case define and pass all the -- necessary handlers to this function. -- -- It fails with error if some of the errors used in the contract -- cannot be handled with given handlers. applyErrorTagToErrorsDocWith :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => [NumericErrorDocHandler] -> ErrorTagMap -> (inp :-> out) -> inp :-> out -- | Modify documentation generated for given code so that all -- CustomError mention not their textual error tag rather -- respective numeric one from the given map. -- -- If some documented error is not present in the map, it remains -- unmodified. This function may fail with error if contract uses -- some uncommon errors, see applyErrorTagToErrorsDocWith for -- details. applyErrorTagToErrorsDoc :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => ErrorTagMap -> (inp :-> out) -> inp :-> out -- | Adds a section which explains error tag mapping. data DDescribeErrorTagMap DDescribeErrorTagMap :: Text -> DDescribeErrorTagMap -- | Describes where the error tag map is defined in Haskell code. [detmSrcLoc] :: DDescribeErrorTagMap -> Text -- | Errors for NumericErrorDocHandler data NumericErrorDocHandlerError -- | Handler which changes documentation for one particular error type. data NumericErrorDocHandler -- | Some error with a numeric tag attached. data NumericErrorWrapper (numTag :: Nat) err voidResultTag :: MText -- | view type synonym as described in A1. data View_ a r -- | void type synonym as described in A1. data Void_ a b -- | Newtype over void result type used in tests to distinguish successful -- void result from other errors. -- -- Usage example: lExpectFailWith (== VoidResult roleMaster)` -- -- This error is special - it can contain arguments of different types -- depending on entrypoint which raises it. data VoidResult r class NonZero t -- | Unwrap a constructor with the given name. Useful for sum types. -- --
--   >>> unsafeUnwrap_ @TestSum #cTestSumA -$? TestSumA 42
--   Right 42
--   
--   >>> first pretty $ unsafeUnwrap_ @TestSum #cTestSumA -$? TestSumB (False, ())
--   Left "Reached FAILWITH instruction with \"BadCtor\" at Error occurred on line 1 char 1."
--   
unsafeUnwrap_ :: forall dt (name :: Symbol) (st :: [Type]). InstrUnwrapC dt name => Label name -> (dt : st) :-> (CtorOnlyField name dt : st) -- | Wrap entry in single-field constructor. Useful for sum types. -- --
--   >>> wrapOne @TestSum #cTestSumA -$ 42
--   TestSumA 42
--   
wrapOne :: forall dt (name :: Symbol) (st :: [Type]). InstrWrapOneC dt name => Label name -> (CtorOnlyField name dt : st) :-> (dt : st) -- | Wrap entry in constructor. Useful for sum types. -- --
--   >>> wrap_ @TestSum #cTestSumB -$ (False, ())
--   TestSumB (False,())
--   
wrap_ :: forall dt (name :: Symbol) (st :: [Type]). InstrWrapC dt name => Label name -> AppendCtorField (GetCtorField dt name) st :-> (dt : st) -- | Lift an instruction to field constructor. fieldCtor :: forall (st :: [Type]) f. HasCallStack => (st :-> (f : st)) -> FieldConstructor st f -- | Decompose a complex object into its fields -- --
--   >>> deconstruct @TestProduct # constructStack @TestProduct -$ testProduct
--   TestProduct {fieldA = True, fieldB = 42, fieldC = ()}
--   
deconstruct :: forall dt (fields :: [Type]) (st :: [Type]). (InstrDeconstructC dt (ToTs st), fields ~ GFieldTypes (Rep dt) ('[] :: [Type]), (ToTs fields ++ ToTs st) ~ ToTs (fields ++ st)) => (dt : st) :-> (fields ++ st) -- | Construct an object from fields on the stack. -- --
--   >>> constructStack @TestProduct -$ True ::: 42 ::: ()
--   TestProduct {fieldA = True, fieldB = 42, fieldC = ()}
--   
constructStack :: forall dt (fields :: [Type]) (st :: [Type]). (InstrConstructC dt, fields ~ ConstructorFieldTypes dt, (ToTs fields ++ ToTs st) ~ ToTs (fields ++ st)) => (fields ++ st) :-> (dt : st) -- | "Open" version of setField, an advanced method suitable for -- chaining setters. -- -- It accepts a continuation accepting the field extracted for the update -- and the new value that is being set. Normally this continuation is -- just setField for some nested field. setFieldOpen :: forall dt (name :: Symbol) new (st :: [Type]). InstrSetFieldC dt name => ('[new, GetFieldType dt name] :-> '[GetFieldType dt name]) -> Label name -> (new : (dt : st)) :-> (dt : st) -- | "Open" version of getField, an advanced method suitable for -- chaining getters. -- -- It accepts two continuations accepting the extracted field, one that -- leaves the field on stack (and does a duplication of res -- inside) and another one that consumes the field. Normally these are -- just getField and toField for some nested field. -- -- Unlike the straightforward chaining of getField/toField -- methods, getFieldOpen does not require the immediate field to -- be dupable; rather, in the best case only res has to be -- dupable. getFieldOpen :: forall dt (name :: Symbol) res (st :: [Type]). (InstrGetFieldC dt name, HasDupableGetters dt) => ('[GetFieldType dt name] :-> '[res, GetFieldType dt name]) -> ('[GetFieldType dt name] :-> '[res]) -> Label name -> (dt : st) :-> (res : (dt : st)) -- | Apply given modifier to a datatype field. -- --
--   >>> modifyField @TestProduct #fieldB (dup # mul) -$ testProduct { fieldB = 8 }
--   TestProduct {fieldA = True, fieldB = 64, fieldC = ()}
--   
modifyField :: forall dt (name :: Symbol) (st :: [Type]). (InstrGetFieldC dt name, InstrSetFieldC dt name, Dupable (GetFieldType dt name), HasDupableGetters dt) => Label name -> (forall (st0 :: [Type]). () => (GetFieldType dt name : st0) :-> (GetFieldType dt name : st0)) -> (dt : st) :-> (dt : st) -- | Like getField, but leaves field named. getFieldNamed :: forall dt (name :: Symbol) (st :: [Type]). (InstrGetFieldC dt name, Dupable (GetFieldType dt name), HasDupableGetters dt) => Label name -> (dt : st) :-> ((name :! GetFieldType dt name) : (dt : st)) -- | Extract a field of a datatype, leaving the original datatype on stack. -- --
--   >>> :{
--    (getField @TestProduct #fieldB # L.swap # toField @TestProduct #fieldB # mul) -$
--       testProduct { fieldB = 3 }
--   :}
--   9
--   
getField :: forall dt (name :: Symbol) (st :: [Type]). (InstrGetFieldC dt name, Dupable (GetFieldType dt name), HasDupableGetters dt) => Label name -> (dt : st) :-> (GetFieldType dt name : (dt : st)) -- | Like toField, but leaves field named. toFieldNamed :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt : st) :-> ((name :! GetFieldType dt name) : st) -- | Extract a field of a datatype replacing the value of this datatype -- with the extracted field. -- -- For this and the following functions you have to specify field name -- which is either record name or name attached with (:!) -- operator. -- --
--   >>> :{
--    (toField @TestProductWithNonDup #fieldTP -$ testProductWithNonDup) == testProduct
--   :}
--   True
--   
toField :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt : st) :-> (GetFieldType dt name : st) -- | Like HasField, but allows constrainting field type. type HasFieldOfType dt (fname :: Symbol) fieldTy = (HasField dt fname, GetFieldType dt fname ~ fieldTy) -- | A pair of field name and type. data NamedField NamedField :: Symbol -> Type -> NamedField type (n :: Symbol) := ty = 'NamedField n ty infixr 0 := -- | Shortcut for multiple HasFieldOfType constraints. type family HasFieldsOfType dt (fs :: [NamedField]) -- | This marker typeclass is a requirement for the getField (where -- it is imposed on the datatype), and it is supposed to be -- satisfied in two cases: -- --
    --
  1. The entire datatype is Dupable;
  2. --
  3. When the datatype has non-dupable fields, they are located so that -- getField remains efficient.
  4. --
-- -- The problem we are trying to solve here: without special care, -- getField may become multiple times more costly, see -- instrGetField for the explanation. And this typeclass imposes -- an invariant: if we ever use getField on a datatype, then we -- have to pay attention to the datatype's Michelson representation and -- ensure getField remains optimal. -- -- When you are developing a contract: Lorentz.Layouts.NonDupable -- module contains utilities to help you provide the necessary Michelson -- layout. In case you want to use your custom layout but still allow -- getField for it, you can define an instance for your type -- manually as an assurance that Michelson layout is optimal enough to -- use getField on this type. -- -- When you are developing a library: Note that HasDupableGetters -- resolves to Dupable by default, and when propagating this -- constraint you can switch to Dupable anytime but this will also -- make your code unusable in the presence of Tickets and other -- non-dupable types. class HasDupableGetters (a :: k) -- | Lorentz analogy of CaseClause, it works on plain Type -- types. 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) -- | Provides "case" arrow which works on different wrappers for clauses. class CaseArrow (name :: Symbol) body clause | clause -> name, clause -> body -- | Lift an instruction to case clause. -- -- You should write out constructor name corresponding to the clause -- explicitly. Prefix constructor name with "c" letter, otherwise your -- label will not be recognized by Haskell parser. Passing constructor -- name can be circumvented but doing so is not recomended as mentioning -- contructor name improves readability and allows avoiding some -- mistakes. (/->) :: CaseArrow name body clause => Label name -> body -> clause infixr 0 /-> type CaseTC dt (out :: [Type]) (inp :: [Type]) clauses = (InstrCaseC dt, RMap CaseClauses dt, RecFromTuple clauses, clauses ~ Rec CaseClauseL inp out CaseClauses dt) -- | If you apply numeric error representation in your contract, -- errorToVal will stop working because it doesn't know about this -- transformation. This function takes this transformation into account. -- If a string is used as a tag, but it is not found in the passed map, -- we conservatively preserve that string (because this whole approach is -- rather a heuristic). errorToValNumeric :: IsError e => ErrorTagMap -> e -> (forall (t :: T). ConstantScope t => Value t -> r) -> r -- | If you apply numeric error representation in your contract, -- errorFromVal will stop working because it doesn't know about -- this transformation. This function takes this transformation into -- account. If a number is used as a tag, but it is not found in the -- passed map, we conservatively preserve that number (because this whole -- approach is rather a heuristic). errorFromValNumeric :: forall (t :: T) e. (SingI t, IsError e) => ErrorTagMap -> Value t -> Either Text e -- | This function implements the simplest scenario of using this module's -- functionality: 1. Gather all error tags from a single instruction. 2. -- Turn them into error conversion map. 3. Apply this conversion. useNumericErrors :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => (inp :-> out) -> (inp :-> out, ErrorTagMap) -- | Similar to applyErrorTagMap, but for case when you have -- excluded some tags from map via excludeErrorTags. Needed, -- because both excludeErrorTags and this function do not tolerate -- unknown errors in contract code (for your safety). applyErrorTagMapWithExclusions :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => ErrorTagMap -> ErrorTagExclusions -> (inp :-> out) -> inp :-> out -- | For each typical FAILWITH that uses a string to represent error -- tag this function changes error tag to be a number using the supplied -- conversion map. It assumes that supplied map contains all such strings -- (and will error out if it does not). It will always be the case if you -- gather all error tags using gatherErrorTags and build -- ErrorTagMap from them using addNewErrorTags. applyErrorTagMap :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => ErrorTagMap -> (inp :-> out) -> inp :-> out -- | Remove some error tags from map. This way you say to remain these -- string tags intact, while others will be converted to numbers when -- this map is applied. -- -- Note that later you have to apply this map using -- applyErrorTagMapWithExclusions, otherwise an error would be -- raised. excludeErrorTags :: HasCallStack => ErrorTagExclusions -> ErrorTagMap -> ErrorTagMap -- | Build ErrorTagMap from a set of textual tags. buildErrorTagMap :: HashSet MText -> ErrorTagMap -- | Add more error tags to an existing ErrorTagMap. It is useful -- when your contract consists of multiple parts (e. g. in case of -- contract upgrade), you have existing map for some part and want to add -- tags from another part to it. You can pass empty map as existing one -- if you just want to build ErrorTagMap from a set of textual -- tags. See buildErrorTagMap. addNewErrorTags :: ErrorTagMap -> HashSet MText -> ErrorTagMap -- | Find all textual error tags that are used in typical FAILWITH -- patterns within given instruction. Map them to natural numbers. gatherErrorTags :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> HashSet MText -- | This is a bidirectional map with correspondence between numeric and -- textual error tags. type ErrorTagMap = Bimap Natural MText -- | Tags excluded from map. type ErrorTagExclusions = HashSet MText -- | QuasiQuote that helps generating TypeHasDoc instance. -- -- Usage: -- --
--   [typeDoc| <type> <description> [<field naming strategy>] |]
--   [typeDoc| Storage "This is storage description" |]
--   [typeDoc| Storage "This is storage description" stripFieldPrefix |]
--   
-- -- field naming strategy is optional, and is a function with -- signature Text -> Text. Common strategies include -- id and stripFieldPrefix. If unspecified, ultimately -- defaults to id. -- -- See this tutorial which includes this quasiquote. typeDoc :: QuasiQuoter -- | QuasiQuote that helps generating CustomErrorHasDoc instance. -- -- Usage: -- --
--   [errorDocArg| <error-name> <error-type> <error-description> [<error-arg-type>] |]
--   [errorDocArg| "errorName" exception "Error description" |]
--   [errorDocArg| "errorName" contract-internal "Error description" () |]
--   [errorDocArg| "errorName" bad-argument "Error description" Integer |]
--   
-- -- The default argument type is NoErrorArg. Only a type name can -- be used, if you need complex type, define a type synonym. -- -- See this tutorial which includes this quasiquote. errorDocArg :: QuasiQuoter -- | QuasiQuote that helps generating ParameterHasEntrypoints -- instance. -- -- Usage: -- --
--   [entrypointDoc| Parameter <parameter-type> [<root-annotation>] |]
--   [entrypointDoc| Parameter plain |]
--   [entrypointDoc| Parameter plain "root"|]
--   
-- -- See this tutorial which includes this quasiquote. entrypointDoc :: QuasiQuoter -- | Implementation of typeDocMdDescription (of TypeHasDoc -- typeclass) for Haskell types which sole purpose is to be error. typeDocMdDescriptionReferToError :: IsError e => Markdown -- | Whether given error class is about internal errors. -- -- Internal errors are not enlisted on per-entrypoint basis, only once -- for the entire contract. isInternalErrorClass :: ErrorClass -> Bool errorTagToText :: forall (tag :: Symbol). KnownSymbol tag => Text -- | Demote error tag to term level. errorTagToMText :: forall (tag :: Symbol). Label tag -> MText -- | Fail, providing a reference to the place in the code where this -- function is called. -- -- Like error in Haskell code, this instruction is for internal -- errors only. failUnexpected :: forall (s :: [Type]) (t :: [Type]). MText -> s :-> t -- | Basic implementation for failUsing. simpleFailUsing :: forall e (s :: [Type]) (t :: [Type]). IsError e => e -> s :-> t -- | Implementation of errorFromVal via IsoValue. isoErrorFromVal :: forall (t :: T) e. (SingI t, KnownIsoT e, IsoValue e) => Value t -> Either Text e -- | Implementation of errorToVal via IsoValue. isoErrorToVal :: (KnownError e, IsoValue e) => e -> (forall (t :: T). ErrorScope t => Value t -> r) -> r -- | Since 008 it's prohibited to fail with non-packable values and with -- the 'Contract t' type values, which is equivalent to our -- ConstantScope constraint. See -- https://gitlab.com/tezos/tezos/-/issues/1093#note_496066354 for -- more information. type ErrorScope (t :: T) = ConstantScope t -- | Haskell type representing error. class ErrorHasDoc e => IsError e -- | Converts a Haskell error into Value representation. errorToVal :: IsError e => e -> (forall (t :: T). ErrorScope t => Value t -> r) -> r -- | Converts a Value into Haskell error. errorFromVal :: forall (t :: T). (IsError e, SingI t) => Value t -> Either Text e -- | Fail with the given Haskell value. failUsing :: forall (s :: [Type]) (t :: [Type]). (IsError e, IsError e) => e -> s :-> t -- | Constraints which we require in a particular instance. You are not -- oblidged to often instantiate this correctly, it is only useful for -- some utilities. type family ErrorRequirements e class Typeable e => ErrorHasDoc e where { -- | Constraints which we require in a particular instance. You are not -- oblidged to often instantiate this correctly, it is only useful for -- some utilities. type family ErrorRequirements e; type ErrorRequirements e = (); } -- | Name of error as it appears in the corresponding section title. errorDocName :: ErrorHasDoc e => Text -- | What should happen for this error to be raised. errorDocMdCause :: ErrorHasDoc e => Markdown -- | Brief version of errorDocMdCause. -- -- This will appear along with the error when mentioned in entrypoint -- description. By default, the first sentence of the full description is -- used. errorDocMdCauseInEntrypoint :: ErrorHasDoc e => Markdown -- | How this error is represented in Haskell. errorDocHaskellRep :: ErrorHasDoc e => Markdown -- | Error class. errorDocClass :: ErrorHasDoc e => ErrorClass -- | Which definitions documentation for this error mentions. errorDocDependencies :: ErrorHasDoc e => [SomeDocDefinitionItem] -- | Captured constraints which we require in a particular instance. This -- is a way to encode a bidirectional instance in the nowaday Haskell, -- for class MyConstraint => ErrorHasDoc MyType instance it -- lets deducing MyConstraint by ErrorHasDoc MyType. -- -- You are not oblidged to always instantiate, it is only useful for some -- utilities which otherwise would not compile. errorDocRequirements :: ErrorHasDoc e => Dict (ErrorRequirements e) -- | Use this type as replacement for () when you really -- want to leave error cause unspecified. data UnspecifiedError UnspecifiedError :: UnspecifiedError -- | Use this error when sure that failing at the current position is -- possible in no curcumstances (including invalid user input or -- misconfigured storage). -- -- To use this as error, you have to briefly specify the reason why the -- error scenario is impossible (experimental feature). data Impossible (reason :: Symbol) Impossible :: Impossible (reason :: Symbol) -- | Type wrapper for an IsError. data SomeError SomeError :: e -> SomeError -- | Declares a custom error, defining error name - error argument -- relation. -- -- If your error is supposed to carry no argument, then provide -- (). -- -- Note that this relation is defined globally rather than on -- per-contract basis, so define errors accordingly. If your error has -- argument specific to your contract, call it such that error name -- reflects its belonging to this contract. -- -- This is the basic [error format]. type family ErrorArg (tag :: Symbol) -- | Material custom error. -- -- Use this in pattern matches against error (e.g. in tests). data CustomError (tag :: Symbol) CustomError :: Label tag -> CustomErrorRep tag -> CustomError (tag :: Symbol) [ceTag] :: CustomError (tag :: Symbol) -> Label tag [ceArg] :: CustomError (tag :: Symbol) -> CustomErrorRep tag -- | To be used as ErrorArg instance when failing with just a -- string instead of pair string x data NoErrorArg -- | To be used as ErrorArg instances. This is equivalent to using -- () but using UnitErrorArg is preferred since -- () behavior could be changed in the future. data UnitErrorArg -- | How CustomError is actually represented in Michelson. type CustomErrorRep (tag :: Symbol) = CustomErrorArgRep ErrorArg tag -- | Typeclass implements various method that work with -- CustomErrorArgRep. class IsCustomErrorArgRep a verifyErrorTag :: IsCustomErrorArgRep a => MText -> a -> Either Text a customErrorRepDocDeps :: IsCustomErrorArgRep a => [SomeDocDefinitionItem] customErrorHaskellRep :: forall (tag :: Symbol). (IsCustomErrorArgRep a, KnownSymbol tag, CustomErrorHasDoc tag) => Proxy tag -> Markdown type MustHaveErrorArg (errorTag :: Symbol) expectedArgRep = FailUnlessEqual CustomErrorRep errorTag expectedArgRep 'Text "Error argument type is " :<>: 'ShowType expectedArgRep :<>: 'Text " but given error requires argument of type " :<>: 'ShowType CustomErrorRep errorTag -- | Error class on how the error should be handled by the client. data ErrorClass -- | Normal expected error. Examples: "insufficient balance", "wallet does -- not exist". ErrClassActionException :: ErrorClass -- | Invalid argument passed to entrypoint. Examples: your entrypoint -- accepts an enum represented as nat, and unknown value is -- provided. This includes more complex cases which involve multiple -- entrypoints. E.g. API provides iterator interface, middleware should -- care about using it hiding complex details and exposing a simpler API -- to user; then an attempt to request non-existing element would also -- correspond to an error from this class. ErrClassBadArgument :: ErrorClass -- | Unexpected error. Most likely it means that there is a bug in the -- contract or the contract has been deployed incorrectly. ErrClassContractInternal :: ErrorClass -- | It's possible to leave error class unspecified. ErrClassUnknown :: ErrorClass class (KnownSymbol tag, TypeHasDoc CustomErrorRep tag, IsError CustomError tag) => CustomErrorHasDoc (tag :: Symbol) -- | What should happen for this error to be raised. customErrDocMdCause :: CustomErrorHasDoc tag => Markdown -- | Brief version of customErrDocMdCause. This will appear along -- with the error when mentioned in entrypoint description. -- -- By default, the first sentence of the full description is used. customErrDocMdCauseInEntrypoint :: CustomErrorHasDoc tag => Markdown -- | Error class. -- -- By default this returns "unknown error" class; though you should -- provide explicit implementation in order to avoid a warning. customErrClass :: CustomErrorHasDoc tag => ErrorClass -- | Clarification of error argument meaning. -- -- Provide when it's not obvious, e.g. argument is not named with -- :!. -- -- NOTE: This should not be an entire sentence, rather just the -- semantic backbone. -- -- Bad: * Error argument stands for the previous value of -- approval. -- -- Good: * the previous value of approval * pair, first -- argument of which is one thing, and the second is another customErrArgumentSemantics :: CustomErrorHasDoc tag => Maybe Markdown -- | Mentions that contract uses given error. data DError [DError] :: forall e. ErrorHasDoc e => Proxy e -> DError -- | Documentation for custom errors. -- -- Mentions that entrypoint throws given error. data DThrows [DThrows] :: forall e. ErrorHasDoc e => Proxy e -> DThrows -- | Remove element with the given type from the stack. -- --
--   >>> :{
--   dropSample1 :: [Integer, (), Natural] :-> [Integer, Natural]
--   dropSample1 = dropT @()
--   :}
--   
-- --
--   >>> pretty $ dropSample1 # zipInstr -$ 123 ::: () ::: 321
--   123 : 321
--   
-- --
--   >>> :{
--   dropSampleErr1 :: [Integer, Natural] :-> [Integer, Natural]
--   dropSampleErr1 = dropT @()
--   :}
--   ...
--   ... • Element of type '()' is not present on stack
--   ...   '[Integer, Natural]
--   ...
--   
-- --
--   >>> :{
--   dropSampleErr1 :: [Integer, Integer] :-> '[Integer]
--   dropSampleErr1 = dropT @Integer
--   :}
--   ...
--   ... • Ambiguous reference to element of type 'Integer' for stack
--   ...   '[Integer, Integer]
--   ...
--   
dropT :: forall a (inp :: [Type]) (dinp :: [Type]) (dout :: [Type]) (out :: [Type]). (DipT a inp dinp dout out, dinp ~ (a : dout)) => inp :-> out -- | Allows duplicating stack elements referring them by type. -- --
--   >>> :{
--   dupSample1 :: [Integer, MText, ()] :-> [MText, Integer, MText, ()]
--   dupSample1 = dupT @MText
--   :}
--   
-- --
--   >>> pretty $ dupSample1 # zipInstr -$ 123 ::: [mt|Hello|] ::: ()
--   Hello : 123 : Hello : ()
--   
-- --
--   >>> :{
--   dupSample2 :: [Integer, MText, ()] :-> [MText, Integer, MText, ()]
--   dupSample2 = dupT
--   :}
--   
-- --
--   >>> pretty $ dupSample2 # zipInstr -$ 123 ::: [mt|Hello|] ::: ()
--   Hello : 123 : Hello : ()
--   
-- --
--   >>> :{
--   dupSampleErr1 :: '[] :-> a
--   dupSampleErr1 = dupT @Bool
--   :}
--   ...
--   ... • Element of type 'Bool' is not present on stack
--   ...   '[]
--   ...
--   
-- --
--   >>> :{
--   -- Should fully infer both wildcards
--   dupSampleErr2 :: _ :-> [Bool, Integer, _, ()]
--   dupSampleErr2 = dupT
--   :}
--   ...
--   ... • Found type wildcard ‘_’
--   ...    standing for ‘'[Integer, Bool, ()] :: [*]’
--   ...
--   ... • Found type wildcard ‘_’ standing for ‘Bool’
--   ...   To use the inferred type, enable PartialTypeSignatures
--   ...
--   
-- --
--   >>> :{
--   -- Should fully infer both wildcards
--   _dupSampleErr3 :: [Integer, _, ()] :-> (Bool ': _)
--   _dupSampleErr3 = dupT
--   :}
--   ...
--   ... • Found type wildcard ‘_’ standing for ‘Bool’
--   ...
--   ... • Found type wildcard ‘_’
--   ...     standing for ‘'[Integer, Bool, ()] :: [*]’
--   ...
--   
class st ~ Head st : Tail st => DupT a (st :: [Type]) -- | Duplicate an element of stack referring it by type. -- -- If stack contains multiple entries of this type, compile error is -- raised. dupT :: DupT a st => st :-> (a : st) -- | Allows diving into stack referring expected new tip by type. -- --
--   >>> :{
--   dipSample1
--     :: [Natural, ()] :-> '[()]
--     -> [Integer, MText, Natural, ()] :-> [Integer, MText, ()]
--   dipSample1 = dipT @Natural
--   :}
--   
-- --
--   >>> pretty $ dipSample1 drop # zipInstr -$ 123 ::: [mt|Hello|] ::: 321 ::: ()
--   123 : Hello : ()
--   
-- --
--   >>> :{
--   dipSample2
--     :: [Natural, ()] :-> '[()]
--     -> [Integer, MText, Natural, ()] :-> [Integer, MText, ()]
--   dipSample2 = dipT -- No type application needed
--   :}
--   
-- --
--   >>> pretty $ dipSample2 drop # zipInstr -$ 123 ::: [mt|Hello|] ::: 321 ::: ()
--   123 : Hello : ()
--   
-- --
--   >>> :{
--   -- An implementation of dropT that demands a bit more from inference.
--   dipSample3
--     :: forall a inp dinp dout out.
--        ( DipT a inp dinp dout out
--        , dinp ~ (a ': dout)
--        )
--     => inp :-> out
--   dipSample3 = dipT (drop @a)
--   :}
--   
-- --
--   >>> :{
--   pretty $ dipSample3 @Natural @'[Integer, MText, Natural, ()] # zipInstr
--     -$ 123 ::: [mt|Hello|] ::: 321 ::: ()
--   :}
--   123 : Hello : ()
--   
-- --
--   >>> :{
--   _dipSampleErr1
--     :: [Natural, ()] :-> '[()]
--     -> [Integer, MText, ()] :-> [Integer, MText, ()]
--   _dipSampleErr1 = dipT @Natural
--   :}
--   ...
--   ... • Element of type 'Natural' is not present on stack
--   ...   '[Integer, MText, ()]
--   ...
--   
-- --
--   >>> :{
--   _dipSampleErr2
--     :: [Natural, ()] :-> '[()]
--     -> [Integer, MText, Natural, (), Natural] :-> [Integer, MText, ()]
--   _dipSampleErr2 = dipT @Natural
--   :}
--   ...
--   ... • Ambiguous reference to element of type 'Natural' for stack
--   ...   '[Integer, MText, Natural, (), Natural]
--   ...
--   
-- --
--   >>> :{
--   _dipSampleErr3
--     :: '[] :-> '[()]
--     -> [Integer, MText, Natural, ()] :-> [Integer, MText, ()]
--   _dipSampleErr3 = dipT @Natural
--   :}
--   ...
--   ... • dipT requires a Lorentz instruction that takes input on the stack.
--   ...
--   
class dipInp ~ a : Tail dipInp => DipT a (inp :: [Type]) (dipInp :: [Type]) (dipOut :: [Type]) (out :: [Type]) | inp a -> dipInp, dipOut inp a -> out, inp out a -> dipOut -- | Dip down until an element of the given type is on top of the stack. -- -- If the stack does not contain an element of this type, or contains -- more than one, then a compile-time error is raised. dipT :: DipT a inp dipInp dipOut out => (dipInp :-> dipOut) -> inp :-> out -- | A constructor providing the required constraint for -- WrappedLambda. This is the only way to construct a lambda that -- uses operations forbidden in views. mkLambdaRec :: forall (i :: [Type]) (o :: [Type]). (IsNotInView => (i ++ '[WrappedLambda i o]) :-> o) -> WrappedLambda i o -- | A constructor providing the required constraint for -- WrappedLambda. This is the only way to construct a lambda that -- uses operations forbidden in views. mkLambda :: forall (i :: [Type]) (o :: [Type]). (IsNotInView => i :-> o) -> WrappedLambda i o -- | A helper type to construct Lorentz lambda values; Use this for lambda -- values outside of Lorentz contracts or with push. data WrappedLambda (i :: [Type]) (o :: [Type]) WrappedLambda :: (i :-> o) -> WrappedLambda (i :: [Type]) (o :: [Type]) RecLambda :: ((i ++ '[WrappedLambda i o]) :-> o) -> WrappedLambda (i :: [Type]) (o :: [Type]) -- | A type synonym representing Michelson lambdas. type Lambda i o = WrappedLambda '[i] '[o] -- | Implementation of castDummy for types composed from smaller -- types. It helps to ensure that all necessary constraints are requested -- in instance head. castDummyG :: (Generic a, Generic b, GCanCastTo (Rep a) (Rep b)) => Proxy a -> Proxy b -> () -- | Locally provide bidirectional CanCastTo instance. allowCheckedCoerce :: forall {k1} {k2} (a :: k1) (b :: k2). Dict (CanCastTo a b, CanCastTo b a) -- | Locally provide given CanCastTo instance. allowCheckedCoerceTo :: forall {k1} {k2} (b :: k1) (a :: k2). Dict (CanCastTo a b) -- | Pretends that the top item of the stack was coerced. checkedCoercing_ :: forall a b (s :: [Type]). Coercible_ a b => ((b : s) :-> (b : s)) -> (a : s) :-> (a : s) -- | Coerce between types which have an explicit permission for that in the -- face of CanCastTo constraint. checkedCoerce_ :: forall a b (s :: [Type]). Castable_ a b => (a : s) :-> (b : s) -- | Coercion in Haskell world which respects CanCastTo. checkedCoerce :: (CanCastTo a b, Coercible a b) => a -> b -- | Unpack named value. fromNamed :: forall (name :: Symbol) a (s :: [Type]). Label name -> ((name :! a) : s) :-> (a : s) -- | Lift given value to a named value. toNamed :: forall (name :: Symbol) a (s :: [Type]). Label name -> (a : s) :-> ((name :! a) : s) -- | Specialized version of forcedCoerce_ to wrap into a haskell -- newtype. -- -- Requires Wrappable constraint. coerceWrap :: forall a (s :: [Type]). Wrappable a => (Unwrappabled a : s) :-> (a : s) -- | Specialized version of forcedCoerce_ to wrap a haskell newtype. -- -- Works under Unwrappable constraint, thus is not safe. unsafeCoerceWrap :: forall a (s :: [Type]). Unwrappable a => (Unwrappabled a : s) :-> (a : s) -- | Specialized version of forcedCoerce_ to unwrap a haskell -- newtype. coerceUnwrap :: forall a (s :: [Type]). Unwrappable a => (a : s) :-> (Unwrappabled a : s) fakeCoercing :: forall (s1 :: [Type]) (s2 :: [Type]) (s1' :: [Type]) (s2' :: [Type]). (s1 :-> s2) -> s1' :-> s2' -- | Convert between two stacks via failing. fakeCoerce :: forall (s1 :: [Type]) (s2 :: [Type]). s1 :-> s2 gForcedCoerce_ :: forall {k} t (a :: k) (b :: k) (s :: [Type]). MichelsonCoercible (t a) (t b) => (t a : s) :-> (t b : s) -- | Convert between values of types that have the same representation. -- -- This function is not safe in a sense that this allows * breaking -- invariants of casted type (example: UStore from -- morley-upgradeable), or * may stop compile on code changes (example: -- coercion of pair to a datatype with two fields will break if new field -- is added). Still, produced Michelson code will always be valid. -- -- Prefer using one of more specific functions from this module. forcedCoerce_ :: forall a b (s :: [Type]). MichelsonCoercible a b => (a : s) :-> (b : s) -- | Coercion for Haskell world. -- -- We discourage using this function on Lorentz types, consider using -- coerce instead. One of the reasons for that is that in Lorentz -- it's common to declare types as newtypes consisting of existing -- primitives, and forcedCoerce tends to ignore all phantom type -- variables of newtypes thus violating their invariants. forcedCoerce :: Coercible a b => a -> b -- | Whether two types have the same Michelson representation. type MichelsonCoercible a b = ToT a ~ ToT b -- | Explicitly allowed coercions. -- -- a CanCastTo b proclaims that a can be casted -- to b without violating any invariants of b. -- -- This relation is reflexive; it may be symmetric or not. It -- tends to be composable: casting complex types usually requires -- permission to cast their respective parts; for such types consider -- using castDummyG as implementation of the method of this -- typeclass. -- -- For cases when a cast from a to b requires some -- validation, consider rather making a dedicated function which performs -- the necessary checks and then calls forcedCoerce. class CanCastTo (a :: k) (b :: k1) -- | An optional method which helps passing -Wredundant-constraints check. -- Also, you can set specific implementation for it with specific sanity -- checks. castDummy :: CanCastTo a b => Proxy a -> Proxy b -> () -- | Coercion from a to b is permitted and safe. type Castable_ a b = (MichelsonCoercible a b, CanCastTo a b) -- | Coercions between a to b are permitted and safe. type Coercible_ a b = (MichelsonCoercible a b, CanCastTo a b, CanCastTo b a) -- | Wrap parameter into this to locally assign a way to derive entrypoints -- for it. newtype ParameterWrapper deriv cp ParameterWrapper :: cp -> ParameterWrapper deriv cp [unParameterWraper] :: ParameterWrapper deriv cp -> cp -- | The type we unwrap to (inner type of the newtype). -- -- Used in constraint for Lorentz instruction wrapping into a Haskell -- newtype and vice versa. type family Unwrappabled s -- | Declares that this type is just a wrapper over some other type and it -- can be safely unwrapped to that inner type. -- -- Inspired by lens Wrapped. class ToT s ~ ToT Unwrappabled s => Unwrappable s where { -- | The type we unwrap to (inner type of the newtype). -- -- Used in constraint for Lorentz instruction wrapping into a Haskell -- newtype and vice versa. type family Unwrappabled s; type Unwrappabled s = GUnwrappabled s Rep s; } -- | Declares that it is safe to wrap an inner type to the given wrapper -- type. Can be provided in addition to Unwrappable. -- -- You can declare this instance when your wrapper exists just to make -- type system differentiate the two types. Example: newtype TokenId -- = TokenId Natural. -- -- Do not define this instance for wrappers that provide some -- invariants. Example: UStore type from -- morley-upgradeable. -- -- Wrappable is similar to lens Wrapped class without the -- method. class Unwrappable s => Wrappable s -- | Lifted ArithOp. class ArithOpHs aop n m r evalArithOpHs :: forall (s :: [Type]). ArithOpHs aop n m r => (n : (m : s)) :-> (r : s) -- | Helper typeclass that provides default definition of -- evalArithOpHs. class DefArithOp (aop :: k) defEvalOpHs :: forall (n :: T) (m :: T) (r :: T) (s :: [T]). (DefArithOp aop, ArithOp aop n m, r ~ ArithRes aop n m) => Instr (n : (m : s)) (r : s) type family UnaryArithResHs aop n -- | Lifted UnaryArithOp. class UnaryArithOpHs aop n where { type family UnaryArithResHs aop n; } evalUnaryArithOpHs :: forall (s :: [Type]). UnaryArithOpHs aop n => (n : s) :-> (UnaryArithResHs aop n : s) type family DefUnaryArithOpExtraConstraints (aop :: k) (n :: T) -- | Helper typeclass that provides default definition of -- evalUnaryArithOpHs. class DefUnaryArithOp (aop :: k) where { type family DefUnaryArithOpExtraConstraints (aop :: k) (n :: T); type DefUnaryArithOpExtraConstraints aop :: k n :: T = (); } defUnaryArithOpHs :: forall (n :: T) (r :: T) (s :: [T]). (DefUnaryArithOp aop, UnaryArithOp aop n, r ~ UnaryArithRes aop n, DefUnaryArithOpExtraConstraints aop n) => Instr (n : s) (r : s) class ToIntegerArithOpHs n evalToIntOpHs :: forall (s :: [Type]). ToIntegerArithOpHs n => (n : s) :-> (Integer : s) class ToBytesArithOpHs n evalToBytesOpHs :: forall bs (s :: [Type]). (ToBytesArithOpHs n, BytesLike bs) => (n : s) :-> (bs : s) -- | Similar to valueToScriptExpr, but for values encoded as -- Expressions. This is only used in tests. expressionToScriptExpr :: Expression -> ByteString -- | This function transforms Lorentz values into script_expr. -- -- script_expr is used in RPC as an argument in entrypoint -- designed for getting value by key from the big_map in Babylon. In -- order to convert value to the script_expr we have to pack it, -- take blake2b hash and add specific expr prefix. Take a look -- at -- https://gitlab.com/tezos/tezos/blob/6e25ae8eb385d9975a30388c7a7aa2a9a65bf184/src/proto_005_PsBabyM1/lib_protocol/script_expr_hash.ml -- and -- https://gitlab.com/tezos/tezos/blob/6e25ae8eb385d9975a30388c7a7aa2a9a65bf184/src/proto_005_PsBabyM1/lib_protocol/contract_services.ml#L136 -- for more information. valueToScriptExpr :: NicePackedValue t => t -> ByteString lEncodeValue :: NiceUntypedValue a => a -> ByteString lUnpackValue :: NiceUnpackedValue a => Packed a -> Either UnpackError a lPackValue :: NicePackedValue a => a -> Packed a lUnpackValueRaw :: NiceUnpackedValue a => ByteString -> Either UnpackError a lPackValueRaw :: NicePackedValue a => a -> ByteString openChestT :: forall a (s :: [Type]). BytesLike a => (ChestKey : (ChestT a : (Natural : s))) :-> (OpenChestT a : s) -- | Evaluate hash in Haskell world. toHashHs :: forall (alg :: HashAlgorithmKind) bs. (BytesLike bs, KnownHashAlgorithm alg) => bs -> Hash alg bs -- | Sign data using SecretKey lSign :: (MonadRandom m, BytesLike a) => SecretKey -> a -> m (TSignature a) -- | Everything which is represented as bytes inside. class (KnownValue bs, ToT bs ~ ToT ByteString) => BytesLike bs toBytes :: BytesLike bs => bs -> ByteString -- | Represents a ByteString resulting from packing a value of type -- a. -- -- This is not guaranteed to keep some packed value, and -- unpack can fail. We do so because often we need to accept -- values of such type from user, and also because there is no simple way -- to check validity of packed data without performing full unpack. So -- this wrapper is rather a hint for users. newtype Packed a Packed :: ByteString -> Packed a [unPacked] :: Packed a -> ByteString -- | Represents a signature, where signed data has given type. -- -- Since we usually sign a packed data, a common pattern for this type is -- TSignature (Packed signedData). If you don't want to -- use Packed, use plain TSignature ByteString instead. newtype TSignature a TSignature :: Signature -> TSignature a [unTSignature] :: TSignature a -> Signature -- | Hash of type t evaluated from data of type a. newtype Hash (alg :: HashAlgorithmKind) a UnsafeHash :: ByteString -> Hash (alg :: HashAlgorithmKind) a [unHash] :: Hash (alg :: HashAlgorithmKind) a -> ByteString -- | Hash algorithm used in Tezos. class Typeable alg => KnownHashAlgorithm (alg :: HashAlgorithmKind) hashAlgorithmName :: KnownHashAlgorithm alg => Proxy alg -> Text computeHash :: KnownHashAlgorithm alg => ByteString -> ByteString toHash :: forall bs (s :: [Type]). (KnownHashAlgorithm alg, BytesLike bs) => (bs : s) :-> (Hash alg bs : s) -- | Documentation item for hash algorithms. data DHashAlgorithm data Sha256 (a :: HashAlgoTag) data Sha512 (a :: HashAlgoTag) data Blake2b (a :: HashAlgoTag) data Sha3 (a :: HashAlgoTag) data Keccak (a :: HashAlgoTag) newtype ChestT a ChestT :: Chest -> ChestT a [unChestT] :: ChestT a -> Chest data OpenChestT a ChestContentT :: a -> OpenChestT a ChestOpenFailedT :: Bool -> OpenChestT a mkDEntrypointExample :: NiceParameter a => a -> DEntrypointExample -- | Leave only instructions related to documentation. -- -- This function is useful when your method executes a lambda coming from -- outside, but you know its properties and want to propagate its -- documentation to your contract code. cutLorentzNonDoc :: forall (inp :: [Type]) (out :: [Type]) (s :: [Type]). (inp :-> out) -> s :-> s -- | Modify the example value of an entrypoint data DEntrypointExample DEntrypointExample :: Value t -> DEntrypointExample -- | Renders to a view section. data DView DView :: ViewName -> SubDoc -> DView [dvName] :: DView -> ViewName [dvSub] :: DView -> SubDoc -- | Renders to a line mentioning the view's argument. data DViewArg DViewArg :: Proxy a -> DViewArg -- | Renders to a line mentioning the view's argument. data DViewRet DViewRet :: Proxy a -> DViewRet -- | Provides documentation for views descriptor. -- -- Note that views descriptors may describe views that do not belong to -- the current contract, e.g. TAddress may refer to an external -- contract provided by the user in which we want to call a view. class (Typeable vd, RenderViewsImpl RevealViews vd) => ViewsDescriptorHasDoc vd viewsDescriptorName :: ViewsDescriptorHasDoc vd => Proxy vd -> Text renderViewsDescriptorDoc :: ViewsDescriptorHasDoc vd => Proxy vd -> Builder -- | Renders to documentation of view descriptor. data DViewDesc DViewDesc :: Proxy vd -> DViewDesc -- | Implementation of ParameterHasEntrypoints which fits for case -- when your contract exposes multiple entrypoints via having sum type as -- its parameter. -- -- In particular, each constructor would produce a homonymous entrypoint -- with argument type equal to type of constructor field (each -- constructor should have only one field). Constructor called -- Default will designate the default entrypoint. data EpdPlain -- | Extension of EpdPlain on parameters being defined as several -- nested datatypes. -- -- In particular, this will traverse sum types recursively, stopping at -- Michelson primitives (like Natural) and constructors with -- number of fields different from one. -- -- It does not assign names to intermediate nodes of Or tree, only -- to the very leaves. -- -- If some entrypoint arguments have custom IsoValue instance, -- this derivation way will not work. As a workaround, you can wrap your -- argument into some primitive (e.g. :!). data EpdRecursive -- | Extension of EpdPlain on parameters being defined as several -- nested datatypes. -- -- In particular, it will traverse the immediate sum type, and require -- another ParameterHasEntrypoints for the inner complex -- datatypes. Only those inner types are considered which are the only -- fields in their respective constructors. Inner types should not -- themselves declare default entrypoint, we enforce this for better -- modularity. Each top-level constructor will be treated as entrypoint -- even if it contains a complex datatype within, in such case that would -- be an entrypoint corresponding to intermediate node in or -- tree. -- -- Comparing to EpdRecursive this gives you more control over -- where and how entrypoints will be derived. data EpdDelegate -- | Extension of EpdPlain, EpdRecursive, and -- EpdDelegate which allow specifying root annotation for the -- parameters. data EpdWithRoot (r :: Symbol) (epd :: k) type family MemOpKeyHs c -- | Lifted MemOpKey. class (MemOp ToT c, ToT MemOpKeyHs c ~ MemOpKey ToT c) => MemOpHs c where { type family MemOpKeyHs c; } -- | A useful property which holds for reasonable MapOp instances. -- -- It's a separate thing from MapOpHs because it mentions -- b type parameter. type family IsoMapOpRes c b type family MapOpResHs c :: Type -> Type type family MapOpInpHs c -- | Lifted MapOp. 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 IterOpElHs c -- | Lifted IterOp. class (IterOp ToT c, ToT IterOpElHs c ~ IterOpEl ToT c) => IterOpHs c where { type family IterOpElHs c; } -- | Lifted SizeOp. -- -- This could be just a constraint alias, but to avoid T types -- appearance in error messages we make a full type class with concrete -- instances. class SizeOp ToT c => SizeOpHs c type family UpdOpParamsHs c type family UpdOpKeyHs c -- | Lifted UpdOp. 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 GetOpValHs c type family GetOpKeyHs c -- | Lifted GetOp. 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; } -- | Lifted ConcatOp. class ConcatOp ToT c => ConcatOpHs c -- | Lifted SliceOp. class SliceOp ToT c => SliceOpHs c -- | Provides Buildable instance that prints Lorentz value via -- Michelson's Value. -- -- Result won't be very pretty, but this avoids requiring Show or -- Buildable instances. newtype PrintAsValue a PrintAsValue :: a -> PrintAsValue a data OpenChest type List = [] data Never -- | Value returned by READ_TICKET instruction. data ReadTicket a ReadTicket :: Address -> a -> Natural -> ReadTicket a [rtTicketer] :: ReadTicket a -> Address [rtData] :: ReadTicket a -> a [rtAmount] :: ReadTicket a -> Natural convertContractRef :: forall cp contract2 contract1. (ToContractRef cp contract1, FromContractRef cp contract2) => contract1 -> contract2 -- | Specialization of callingAddress to call the default -- entrypoint. callingDefAddress :: (ToTAddress cp vd addr, NiceParameterFull cp) => addr -> ContractRef (GetDefaultEntrypointArg cp) -- | Turn any typed address to ContractRef in Haskell world. -- -- This is an analogy of address to contract convertion -- in Michelson world, thus you have to supply an entrypoint (or call the -- default one explicitly). callingAddress :: forall cp vd addr (mname :: Maybe Symbol). (ToTAddress cp vd addr, NiceParameterFull cp) => addr -> EntrypointRef mname -> ContractRef (GetEntrypointArgCustom cp mname) -- | Address which remembers the parameter and views types of the contract -- it refers to. -- -- It differs from Michelson's contract type because it cannot -- contain entrypoint, and it always refers to entire contract parameter -- even if this contract has explicit default entrypoint. newtype TAddress p vd TAddress :: Address -> TAddress p vd [unTAddress] :: TAddress p vd -> Address -- | Address associated with value of contract arg type. -- -- Places where ContractRef can appear are now severely limited, -- this type gives you type-safety of ContractRef but still can be -- used everywhere. This type is not a full-featured one rather a helper; -- in particular, once pushing it on stack, you cannot return it back to -- Haskell world. -- -- Note that it refers to an entrypoint of the contract, not just the -- contract as a whole. In this sense this type differs from -- TAddress. -- -- Unlike with ContractRef, having this type you still cannot be -- sure that the referred contract exists and need to perform a lookup -- before calling it. newtype FutureContract arg FutureContract :: ContractRef arg -> FutureContract arg [unFutureContract] :: FutureContract arg -> ContractRef arg -- | Convert something to Address in Haskell world. -- -- Use this when you want to access state of the contract and are not -- interested in calling it. class ToAddress a toAddress :: ToAddress a => a -> Address -- | Convert something referring to a contract (not specific entrypoint) to -- TAddress in Haskell world. class ToTAddress cp vd a toTAddress :: ToTAddress cp vd a => a -> TAddress cp vd -- | Convert something to ContractRef in Haskell world. class ToContractRef cp contract toContractRef :: ToContractRef cp contract => contract -> ContractRef cp -- | Convert something from ContractRef in Haskell world. class FromContractRef cp contract fromContractRef :: FromContractRef cp contract => ContractRef cp -> contract -- | Single entrypoint of a contract. -- -- Note that we cannot make it return [[Operation], store] -- because such entrypoint should've been followed by pair, and -- this is not possible if entrypoint implementation ends with -- failWith. type Entrypoint param store = '[param, store] :-> ContractOut store -- | Version of Entrypoint which accepts no argument. type Entrypoint_ store = '[store] :-> ContractOut store -- | Fix the current type of the stack to be given one. -- --
--   stackType @'[Natural]
--   stackType @(Integer : Natural : s)
--   stackType @'["balance" :! Integer, "toSpend" :! Integer, BigMap Address Integer]
--   
-- -- Note that you can omit arbitrary parts of the type. -- --
--   stackType @'["balance" :! Integer, "toSpend" :! _, BigMap _ _]
--   
stackType :: forall (s :: [Type]). s :-> s -- | Test an invariant, fail if it does not hold. -- -- This won't be included into production contract and is executed only -- in tests. testAssert :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => Text -> PrintComment (ToTs inp) -> (inp :-> (Bool : out)) -> inp :-> inp commentAroundStmt :: forall (i :: [Type]) (o :: [Type]). Text -> (i :-> o) -> i :-> o commentAroundFun :: forall (i :: [Type]) (o :: [Type]). Text -> (i :-> o) -> i :-> o comment :: forall (s :: [Type]). CommentType -> s :-> s justComment :: forall (s :: [Type]). Text -> s :-> s -- | Print a comment. It will be visible in tests. -- --
--   printComment "Hello world!"
--   printComment $ "On top of the stack I see " <> stackRef @0
--   
printComment :: forall (s :: [Type]). PrintComment (ToTs s) -> s :-> s -- | Include a value at given position on stack into comment produced by -- printComment. -- --
--   stackRef @0
--   
-- -- the top of the stack stackRef :: forall (gn :: Nat) (st :: [T]) (n :: Peano). (n ~ ToPeano gn, SingI n, RequireLongerThan st n) => PrintComment st optimizeLorentz :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> inp :-> out optimizeLorentzWithConf :: forall (inp :: [Type]) (out :: [Type]). OptimizerConf -> (inp :-> out) -> inp :-> out -- | Lorentz version of transformBytes. transformBytesLorentz :: forall (inp :: [Type]) (out :: [Type]). Bool -> (ByteString -> ByteString) -> (inp :-> out) -> inp :-> out -- | Lorentz version of transformStrings. transformStringsLorentz :: forall (inp :: [Type]) (out :: [Type]). Bool -> (MText -> MText) -> (inp :-> out) -> inp :-> out -- | Parse textual representation of a Michelson value and turn it into -- corresponding Haskell value. -- -- Note: it won't work in some complex cases, e. g. if there is a lambda -- which uses an instruction which depends on current contract's type. -- Obviously it can not work, because we don't have any information about -- a contract to which this value belongs (there is no such contract at -- all). parseLorentzValue :: KnownValue v => MichelsonSource -> Text -> Either ParseLorentzError v -- | Demote Lorentz Contract to Michelson typed Contract. toMichelsonContract :: Contract cp st vd -> Contract (ToT cp) (ToT st) -- | A helper to construct ContractCode that provides -- IsNotInView constraint. mkContractCode :: (IsNotInView => '[(cp, st)] :-> ContractOut st) -> ContractCode cp st iForceNotFail :: forall (i :: [Type]) (o :: [Type]). (i :-> o) -> i :-> o 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) iAnyCode :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> Instr (ToTs inp) (ToTs out) 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 pattern I :: Instr (ToTs inp) (ToTs out) -> inp :-> out pattern FI :: (forall (out' :: [T]). () => Instr (ToTs inp) out') -> inp :-> out -- | Alias for instruction which hides inner types representation via -- T. 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) infixr 1 :-> -- | Alias for :->, seems to make signatures more readable -- sometimes. -- -- Let's someday decide which one of these two should remain. type (%>) = (:->) infixr 1 %> type ContractOut st = '[([Operation], st)] -- | Wrap contract code capturing the constraint that the code is not -- inside a view. newtype ContractCode cp st ContractCode :: ('[(cp, st)] :-> ContractOut st) -> ContractCode cp st [unContractCode] :: ContractCode cp st -> '[(cp, st)] :-> ContractOut st data SomeContractCode [SomeContractCode] :: forall cp st. (NiceParameter cp, NiceStorage st) => ContractCode cp st -> SomeContractCode type ViewCode arg st ret = '[(arg, st)] :-> '[ret] -- | Ready contract code. cMichelsonContract :: Contract cp st vd -> Contract (ToT cp) (ToT st) -- | Contract that contains documentation. -- -- We have to keep it separately, since optimizer is free to destroy -- documentation blocks. Also, it is not ContractDoc but Lorentz -- code because the latter is easier to modify. cDocumentedCode :: Contract cp st vd -> ContractCode cp st -- | An alias for ':. -- -- We discourage its use as this hinders reading error messages (the -- compiler inserts unnecessary parentheses and indentation). type a & (b :: [Type]) = a : b infixr 2 & -- | An instruction sequence taking one stack element as input and -- returning one stack element as output. Essentially behaves as a -- Michelson lambda without any additional semantical meaning. -- -- The reason for this distinction is Michelson lambdas allow -- instructions inside them that might be forbidden in the outer scope. -- This type doesn't add any such conditions. type Fn a b = '[a] :-> '[b] -- | Applicable for wrappers over Lorentz code. class MapLorentzInstr instr -- | Modify all the code under given entity. mapLorentzInstr :: MapLorentzInstr instr => (forall (i :: [Type]) (o :: [Type]). () => (i :-> o) -> i :-> o) -> instr -> instr -- | Check whether given value is dupable, returning a proof of that when -- it is. -- -- This lets defining methods that behave differently depending on -- whether given value is dupable or not. This may be suitable when for -- the dupable case you can provide a more efficient implementation, but -- you also want your implementation to be generic. -- -- Example: -- --
--   code = case decideOnDupable @a of
--     IsDupable -> do dup; ...
--     IsNotDupable -> ...
--   
decideOnDupable :: KnownValue a => DupableDecision a -- | Constraint applied to a whole parameter type. type NiceParameterFull cp = (Typeable cp, ParameterDeclaresEntrypoints cp) -- | Tells whether given type is dupable or not. data DupableDecision a IsDupable :: DupableDecision a IsNotDupable :: DupableDecision a -- | Require views set to be proper. type NiceViews (vs :: [ViewTyInfo]) = RequireAllUnique "view" ViewsNames vs -- | Require views set referred by the given views descriptor to be proper. type NiceViewsDescriptor vd = NiceViews RevealViews vd -- | Universal entrypoint calling. parameterEntrypointCallCustom :: forall cp (mname :: Maybe Symbol). ParameterDeclaresEntrypoints cp => EntrypointRef mname -> EntrypointCall cp (GetEntrypointArgCustom cp mname) eprName :: forall (mname :: Maybe Symbol). EntrypointRef mname -> EpName -- | Call root entrypoint safely. sepcCallRootChecked :: (NiceParameter cp, ForbidExplicitDefaultEntrypoint cp) => SomeEntrypointCall cp -- | Call the default entrypoint. parameterEntrypointCallDefault :: ParameterDeclaresEntrypoints cp => EntrypointCall cp (GetDefaultEntrypointArg cp) -- | Prepare call to given entrypoint. -- -- This does not treat calls to default entrypoint in a special way. To -- call default entrypoint properly use -- parameterEntrypointCallDefault. parameterEntrypointCall :: forall cp (name :: Symbol). ParameterDeclaresEntrypoints cp => Label name -> EntrypointCall cp (GetEntrypointArg cp name) -- | Derive annotations for given parameter. parameterEntrypointsToNotes :: ParameterDeclaresEntrypoints cp => ParamNotes (ToT cp) -- | Get entrypoint argument by name. type family EpdLookupEntrypoint (deriv :: k) cp :: Symbol -> Exp Maybe Type -- | Name and argument of each entrypoint. This may include intermediate -- ones, even root if necessary. -- -- Touching this type family is costly (O(N^2)), don't use it -- often. -- -- Note [order of entrypoints children]: If this contains entrypoints -- referring to indermediate nodes (not leaves) in or tree, then -- each such entrypoint should be mentioned eariler than all of its -- children. type family EpdAllEntrypoints (deriv :: k) cp :: [(Symbol, Type)] -- | Defines a generalized way to declare entrypoints for various parameter -- types. -- -- When defining instances of this typeclass, set concrete deriv -- argument and leave variable cp argument. Also keep in mind, -- that in presence of explicit default entrypoint, all other Or -- arms should be callable, though you can put this burden on user if -- very necessary. -- -- Methods of this typeclass aim to better type-safety when making up an -- implementation and they may be not too convenient to use; users should -- exploit their counterparts. class EntrypointsDerivation (deriv :: k) cp where { -- | Name and argument of each entrypoint. This may include intermediate -- ones, even root if necessary. -- -- Touching this type family is costly (O(N^2)), don't use it -- often. -- -- Note [order of entrypoints children]: If this contains entrypoints -- referring to indermediate nodes (not leaves) in or tree, then -- each such entrypoint should be mentioned eariler than all of its -- children. type family EpdAllEntrypoints (deriv :: k) cp :: [(Symbol, Type)]; -- | Get entrypoint argument by name. type family EpdLookupEntrypoint (deriv :: k) cp :: Symbol -> Exp Maybe Type; } -- | Construct parameter annotations corresponding to expected entrypoints -- set. -- -- This method is implementation detail, for actual notes construction -- use parameterEntrypointsToNotes. epdNotes :: EntrypointsDerivation deriv cp => (Notes (ToT cp), RootAnn) -- | Construct entrypoint caller. -- -- This does not treat calls to default entrypoint in a special way. -- -- This method is implementation detail, for actual entrypoint lookup use -- parameterEntrypointCall. epdCall :: forall (name :: Symbol). (EntrypointsDerivation deriv cp, ParameterScope (ToT cp)) => Label name -> EpConstructionRes (ToT cp) (Eval (EpdLookupEntrypoint deriv cp name)) -- | Description of how each of the entrypoints is constructed. epdDescs :: EntrypointsDerivation deriv cp => Rec EpCallingDesc (EpdAllEntrypoints deriv cp) -- | Ensure that all declared entrypoints are unique. type RequireAllUniqueEntrypoints cp = RequireAllUniqueEntrypoints' ParameterEntrypointsDerivation cp cp type family ParameterEntrypointsDerivation cp -- | Which entrypoints given parameter declares. -- -- Note that usually this function should not be used as constraint, use -- ParameterDeclaresEntrypoints for this purpose. class (EntrypointsDerivation ParameterEntrypointsDerivation cp cp, RequireAllUniqueEntrypoints cp) => ParameterHasEntrypoints cp where { type family ParameterEntrypointsDerivation cp; } -- | Parameter declares some entrypoints. -- -- This is a version of ParameterHasEntrypoints which we actually -- use in constraints. When given type is a sum type or newtype, we refer -- to ParameterHasEntrypoints instance, otherwise this instance is -- not necessary. type ParameterDeclaresEntrypoints cp = (If CanHaveEntrypoints cp ParameterHasEntrypoints cp (), NiceParameter cp, EntrypointsDerivation GetParameterEpDerivation cp cp) -- | Get all entrypoints declared for parameter. type family AllParameterEntrypoints cp :: [(Symbol, Type)] -- | Lookup for entrypoint type by name. -- -- Does not treat default entrypoints in a special way. type family LookupParameterEntrypoint cp :: Symbol -> Exp Maybe Type -- | Get type of entrypoint with given name, fail if not found. 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 -- | Get type of entrypoint with given name, fail if not found. type GetDefaultEntrypointArg cp = Eval LiftM2 FromMaybe :: Type -> Maybe Type -> Type -> Type Pure cp LookupParameterEntrypoint cp DefaultEpName -- | Ensure that there is no explicit "default" entrypoint. 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 -- | Similar to ForbidExplicitDefaultEntrypoint, but in a version -- which the compiler can work with (and which produces errors confusing -- for users :/) type NoExplicitDefaultEntrypoint cp = Eval LookupParameterEntrypoint cp DefaultEpName ~ 'Nothing :: Maybe Type -- | Which entrypoint to call. -- -- We intentionally distinguish default and non-default cases because -- this makes API more details-agnostic. data EntrypointRef (mname :: Maybe Symbol) -- | Call the default entrypoint, or root if no explicit default is -- assigned. [CallDefault] :: EntrypointRef ('Nothing :: Maybe Symbol) -- | Call the given entrypoint; calling default is not treated specially. -- You have to provide entrypoint name via passing it as type argument. -- -- Unfortunatelly, here we cannot accept a label because in most cases -- our entrypoints begin from capital letter (being derived from -- constructor name), while labels must start from a lower-case letter, -- and there is no way to make a conversion at type-level. [Call] :: forall (name :: Symbol). NiceEntrypointName name => EntrypointRef ('Just name) -- | Universal entrypoint lookup. type family GetEntrypointArgCustom cp (mname :: Maybe Symbol) -- | When we call a Lorentz contract we should pass entrypoint name and -- corresponding argument. Ideally we want to statically check that -- parameter has entrypoint with given name and argument. Constraint -- defined by this type class holds for contract with parameter -- cp that have entrypoint matching name with type -- arg. -- -- In order to check this property statically, we need to know entrypoint -- name in compile time, EntrypointRef type serves this purpose. -- If entrypoint name is not known, one can use TrustEpName -- wrapper to take responsibility for presence of this entrypoint. -- -- If you want to call a function which has this constraint, you have two -- options: -- --
    --
  1. Pass contract parameter cp using type application, pass -- EntrypointRef as a value and pass entrypoint argument. Type -- system will check that cp has an entrypoint with given -- reference and type.
  2. --
  3. Pass EpName wrapped into TrustEpName and entrypoint -- argument. In this case passing contract parameter is not necessary, -- you do not even have to know it.
  4. --
-- -- You may need to add this constraint for polymorphic arguments. GHC -- should tell you when that is the case: -- --
--   >>> :{
--   f :: forall (cp :: Type). ParameterDeclaresEntrypoints cp => ()
--   f = useHasEntrypointArg @cp @_ @(Maybe Integer) CallDefault & const ()
--   :}
--   ...
--   ... Can not look up entrypoints in type
--   ...   cp
--   ... The most likely reason it is ambiguous, or you need
--   ...   HasEntrypointArg cp (EntrypointRef 'Nothing) (Maybe Integer)
--   ... constraint
--   ...
--   
-- -- If GHC can't deduce the type of entrypoint argument, it'll use an -- unbound type variable, usually arg0, in the error message: -- --
--   >>> :{
--   f :: forall (cp :: Type). ParameterDeclaresEntrypoints cp => ()
--   f = useHasEntrypointArg @cp CallDefault & const ()
--   :}
--   ...
--   ... Can not look up entrypoints in type
--   ...   cp
--   ... The most likely reason it is ambiguous, or you need
--   ...   HasEntrypointArg cp (EntrypointRef 'Nothing) arg0
--   ... constraint
--   ...
--   
class HasEntrypointArg (cp :: k) name arg -- | Data returned by this method may look somewhat arbitrary. -- EpName is obviously needed because name can be -- EntrypointRef or TrustEpName. Dict is returned -- because in EntrypointRef case we get this evidence for free and -- don't want to use it. We seem to always need it anyway. useHasEntrypointArg :: HasEntrypointArg cp name arg => name -> (Dict (ParameterScope (ToT arg)), EpName) -- | HasEntrypointArg constraint specialized to default entrypoint. type HasDefEntrypointArg (cp :: k) defEpName defArg = (defEpName ~ EntrypointRef 'Nothing :: Maybe Symbol, HasEntrypointArg cp defEpName defArg) -- | This wrapper allows to pass untyped EpName and bypass checking -- that entrypoint with given name and type exists. newtype TrustEpName TrustEpName :: EpName -> TrustEpName -- | Checks that the given parameter consists of some specific entrypoint. -- Similar as HasEntrypointArg but ensures that the argument -- matches the following datatype. type HasEntrypointOfType param (con :: Symbol) exp = (GetEntrypointArgCustom param 'Just con ~ exp, ParameterDeclaresEntrypoints param) type (n :: Symbol) :> ty = 'NamedEp n ty infixr 0 :> -- | Check that the given entrypoint has some fields inside. This interface -- allows for an abstraction of contract parameter so that it requires -- some *minimal* specification, but not a concrete one. type family ParameterContainsEntrypoints param (fields :: [NamedEp]) -- | No entrypoints declared, parameter type will serve as argument type of -- the only existing entrypoint (default one). data EpdNone -- | A special type which wraps over a primitive type and states that it -- has entrypoints (one). -- -- Assuming that any type can have entrypoints makes use of Lorentz -- entrypoints too annoying, so for declaring entrypoints for not sum -- types we require an explicit wrapper. newtype ShouldHaveEntrypoints a ShouldHaveEntrypoints :: a -> ShouldHaveEntrypoints a [unHasEntrypoints] :: ShouldHaveEntrypoints a -> a -- | Gathers constraints, commonly required for values. class (IsoValue a, Typeable a) => KnownValue a -- | Ensure given type does not contain "operation". class (ForbidOp ToT a, IsoValue a) => NoOperation a class (ForbidContract ToT a, IsoValue a) => NoContractType a class (ForbidBigMap ToT a, IsoValue a) => NoBigMap a class (HasNoNestedBigMaps ToT a, IsoValue a) => CanHaveBigMap a -- | Constraint applied to any part of a parameter type. -- -- Use NiceParameterFull instead when you need to know the -- contract's entrypoints at compile-time. type NiceParameter a = (ProperParameterBetterErrors ToT a, KnownValue a) type NiceStorage a = (ProperStorageBetterErrors ToT a, KnownValue a) type NiceStorageFull a = (NiceStorage a, HasAnnotation a) type NiceConstant a = (ProperConstantBetterErrors ToT a, KnownValue a) type Dupable a = (ProperDupableBetterErrors ToT a, KnownValue a) type NicePackedValue a = (ProperPackedValBetterErrors ToT a, KnownValue a) type NiceUnpackedValue a = (ProperUnpackedValBetterErrors ToT a, KnownValue a) type NiceFullPackedValue a = (NicePackedValue a, NiceUnpackedValue a) type NiceUntypedValue a = (ProperUntypedValBetterErrors ToT a, KnownValue a) type NiceViewable a = (ProperViewableBetterErrors ToT a, KnownValue a) -- | Constraint applied to any type, to check if Michelson representation -- (if exists) of this type is Comparable. In case it is not prints -- human-readable error message type NiceComparable n = (ProperNonComparableValBetterErrors ToT n, KnownValue n, Comparable ToT n) type NiceNoBigMap n = (KnownValue n, HasNoBigMap ToT n) -- | This class defines the type and field annotations for a given type. -- Right now the type annotations come from names in a named field, and -- field annotations are generated from the record fields. class HasAnnotation a -- | 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 :& -- | 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 -- | Type of a strategy to derive Generic instances. data GenericStrategy -- | In this strategy the desired depths of contructors (in the type tree) -- and fields (in each constructor's tree) are provided manually and -- simply checked against the number of actual constructors and fields. withDepths :: [CstrDepth] -> GenericStrategy -- | Strategy to make right-balanced instances (both in constructors and -- fields). -- -- This will try its best to produce a flat tree: -- -- rightBalanced :: GenericStrategy -- | Strategy to make left-balanced instances (both in constructors and -- fields). -- -- This is the same as symmetrically mapped rightBalanced. leftBalanced :: GenericStrategy -- | Strategy to make fully right-leaning instances (both in constructors -- and fields). rightComb :: GenericStrategy -- | Strategy to make fully left-leaning instances (both in constructors -- and fields). leftComb :: GenericStrategy -- | Strategy to make Haskell's Generics-like instances (both in -- constructors and fields). -- -- This is similar to rightBalanced, except for the "flat" part: -- -- -- -- This strategy matches A1.1. -- -- customGeneric "T" haskellBalanced is equivalent to mere -- deriving stock Generic T. haskellBalanced :: GenericStrategy -- | Modify given strategy to reorder constructors. -- -- The reordering will take place before depths are evaluated and -- structure of generic representation is formed. -- -- Example: reorderingConstrs alphabetically rightBalanced. reorderingConstrs :: EntriesReorder -> GenericStrategy -> GenericStrategy -- | Modify given strategy to reorder fields. -- -- Same notes as for reorderingConstrs apply here. -- -- Example: reorderingFields forbidUnnamedFields alphabetically -- rightBalanced. reorderingFields :: UnnamedEntriesReorder -> EntriesReorder -> GenericStrategy -> GenericStrategy -- | Modify given strategy to reorder constructors and fields. -- -- Same notes as for reorderingConstrs apply here. -- -- Example: reorderingData forbidUnnamedFields alphabetically -- rightBalanced. reorderingData :: UnnamedEntriesReorder -> EntriesReorder -> GenericStrategy -> GenericStrategy -- | Sort entries by name alphabetically. alphabetically :: EntriesReorder -- | Leave unnamed fields intact, without any reordering. leaveUnnamedFields :: UnnamedEntriesReorder -- | Fail in case records are unnamed and we cannot figure out the -- necessary reordering. forbidUnnamedFields :: UnnamedEntriesReorder -- | Helper to make a strategy that created depths for constructor and -- fields in the same way, just from their number. -- -- The provided function f must satisfy the following rules: -- -- fromDepthsStrategy :: (Int -> [Natural]) -> GenericStrategy -- | Like fromDepthsStrategy, but allows specifying different -- strategies for constructors and fields. fromDepthsStrategy' :: (Int -> [Natural]) -> (Int -> [Natural]) -> GenericStrategy makeRightBalDepths :: Int -> [Natural] -- | Helper for making a constructor depth. -- -- Note that this is only intended to be more readable than directly -- using a tuple with withDepths and for the ability to be used in -- places where RebindableSyntax overrides the number literal -- resolution. cstr :: forall (n :: Nat). KnownNat n => [Natural] -> CstrDepth -- | Helper for making a field depth. -- -- Note that this is only intended to be more readable than directly -- using a tuple with withDepths and for the ability to be used in -- places where RebindableSyntax overrides the number literal -- resolution. fld :: forall (n :: Nat). KnownNat n => Natural customGeneric :: String -> GenericStrategy -> Q [Dec] -- | If a Type type is given, this function will generate a new -- Generic instance with it, and generate the appropriate "to" and -- "from" methods. -- -- Otherwise, it'll generate a new Type instance as well. customGeneric' :: Maybe Type -> Name -> Type -> [Con] -> GenericStrategy -> Q [Dec] -- | Reifies info from a type name (given as a String). The lookup -- happens from the current splice's scope (see lookupTypeName) -- and the only accepted result is a "plain" data type (no GADTs). reifyDataType :: Name -> Q (Name, Cxt, Maybe Kind, [TyVarBndr ()], [Con]) -- | Derives, as well as possible, a type definition from its name, its -- kind (where known) and its variables. deriveFullType :: Name -> Maybe Kind -> [TyVarBndr flag] -> TypeQ -- | Patch a given strategy by applying a transformation function to -- constructor names before passing them through ordering function. mangleGenericStrategyConstructors :: (Text -> Text) -> GenericStrategy -> GenericStrategy -- | Patch a given strategy by applying a transformation function to field -- names before passing them through ordering function. mangleGenericStrategyFields :: (Text -> Text) -> GenericStrategy -> GenericStrategy -- | Default layout in LIGO. -- -- To be used with customGeneric, see this method for more info. -- -- This is similar to leftBalanced, but -- -- ligoLayout :: GenericStrategy -- | Comb layout in LIGO ( [@layout:comb] ). -- -- To be used with customGeneric. -- -- Note: to make comb layout work for sum types, make sure that in LIGO -- all the constructors are preceded by the bar symbol in your type -- declaration: -- --
--   type my_type =
--     [@layout:comb]
--     | Ctor1 of nat  ← bar symbol _must_ be here
--     | Ctor2 of int
--     ...
--   
-- -- Though the situation may change: -- https://gitlab.com/ligolang/ligo/-/issues/1104. ligoCombLayout :: GenericStrategy -- | A piece of markdown document. -- -- This is opposed to Text type, which in turn is not supposed to -- contain markup elements. type Markdown = Builder -- | Set of constraints that Michelson applies to pushed constants. -- -- Not just a type alias in order to be able to partially apply it class (SingI t, WellTyped t, HasNoOp t, HasNoBigMap t, HasNoContract t, HasNoTicket t, HasNoSaplingState t) => ConstantScope (t :: T) -- | Proxy for a label type that includes the KnownSymbol constraint data Label (name :: Symbol) [Label] :: forall (name :: Symbol). KnownSymbol name => Label name -- | A locked chest data Chest -- | A chest "key" with proof that it was indeed opened fairly. data ChestKey -- | Entrypoint name. -- -- There are two properties we care about: -- --
    --
  1. Special treatment of the default entrypoint name. -- default is prohibited in the CONTRACT instruction -- and in values of address and contract types. -- However, it is not prohibited in the SELF instruction. Hence, -- the value inside EpName can be "default", so -- that we can distinguish SELF and SELF %default. It -- is important to distinguish them because their binary representation -- that is inserted into blockchain is different. For example, -- typechecking SELF %default consumes more gas than -- SELF. In this module, we provide several smart constructors -- with different handling of default, please use the -- appropriate one for your use case.
  2. --
  3. The set of permitted characters. Intuitively, an entrypoint name -- should be valid only if it is a valid annotation (because entrypoints -- are defined using field annotations). However, it is not enforced in -- Tezos. It is not clear whether this behavior is intended. There is an -- upstream issue which received bug label, so probably -- it is considered a bug. Currently we treat it as a bug and deviate -- from upstream implementation by probiting entrypoint names that are -- not valid annotations. If Tezos developers fix it soon, we will be -- happy. If they don't, we should (maybe temporarily) remove this -- limitation from our code. There is an issue in our repo as -- well.
  4. --
data EpName -- | This is a bidirectional pattern that can be used for two purposes: -- --
    --
  1. Construct an EpName referring to the default -- entrypoint.
  2. --
  3. Use it in pattern-matching or in equality comparison to check -- whether EpName refers to the default entrypoint. This is -- trickier because there are two possible EpName values referring -- to the default entrypoints. DefEpName will match only the most -- common one (no entrypoint). However, there is a special case: -- SELF instruction can have explicit %default -- reference. For this reason, it is recommended to use -- isDefEpName instead. Pattern-matching on DefEpName is -- still permitted for backwards compatibility and for the cases when you -- are sure that EpName does not come from the SELF -- instruction.
  4. --
pattern DefEpName :: EpName -- | An element of an algebraic number field (scalar), used for multiplying -- Bls12381G1 and Bls12381G2. data Bls12381Fr -- | G2 point on the curve. data Bls12381G2 -- | G1 point on the curve. data Bls12381G1 -- | Michelson string value. -- -- This is basically a mere text with limits imposed by the language: -- https://tezos.gitlab.io/whitedoc/michelson.html#constants -- Although, this document seems to be not fully correct, and thus we -- applied constraints deduced empirically. -- -- You construct an item of this type using one of the following ways: -- -- -- --
--   >>> [mt|Some text|]
--   UnsafeMText {unMText = "Some text"}
--   
-- -- data MText -- | QuasyQuoter for constructing Michelson strings. -- -- Validity of result will be checked at compile time. Note: -- -- mt :: QuasiQuoter -- | Convenience synonym for an on-chain public key hash. type KeyHash = Hash 'HashKindPublicKey -- | Cryptographic signatures used by Tezos. Constructors correspond to -- PublicKey constructors. -- -- Tezos distinguishes signatures for different curves. For instance, -- ed25519 signatures and secp256k1 signatures are printed differently -- (have different prefix). However, signatures are packed without -- information about the curve. For this purpose there is a generic -- signature which only stores bytes and doesn't carry information about -- the curve. Apparently unpacking from bytes always produces such -- signature. Unpacking from string produces a signature with curve -- information. data Signature -- | Public cryptographic key used by Tezos. There are three cryptographic -- curves each represented by its own constructor. data PublicKey -- | Identifier of a network (babylonnet, mainnet, test network or other). -- Evaluated as hash of the genesis block. -- -- The only operation supported for this type is packing. Use case: -- multisig contract, for instance, now includes chain ID into signed -- data "in order to add extra replay protection between the main chain -- and the test chain". data ChainId -- | Time in the real world. Use the functions below to convert it to/from -- Unix time in seconds. data Timestamp -- | Mutez is a wrapper over integer data type. 1 mutez is 1 token (μTz). -- -- The constructor is marked Unsafe since GHC does not warn on -- overflowing literals (exceeding custom Word63 type bounds), -- thus the resultant Mutez value may get truncated silently. -- --
--   >>> UnsafeMutez 9223372036854775809
--   UnsafeMutez {unMutez = 1}
--   
data Mutez -- | Quotes a Mutez value. -- -- The value is in XTZ, i.e. 1e6 Mutez, with optional suffix -- representing a unit: -- -- -- -- This is the safest and recommended way to create Mutez from a -- numeric literal. -- -- The suffix can be separated from the number by whitespace. You can -- also use underscores as a delimiter (those will be ignored), and -- scientific notation, e.g. 123.456e6. Note that if the -- scientific notation represents a mutez fraction, that is a -- compile-time error. -- --
--   >>> [tz|123|]
--   UnsafeMutez {unMutez = 123000000}
--   
-- --
--   >>> [tz|123k|]
--   UnsafeMutez {unMutez = 123000000000}
--   
-- --
--   >>> [tz|123 kilo|]
--   UnsafeMutez {unMutez = 123000000000}
--   
-- --
--   >>> [tz|123M|]
--   UnsafeMutez {unMutez = 123000000000000}
--   
-- --
--   >>> [tz|123 Mega|]
--   UnsafeMutez {unMutez = 123000000000000}
--   
-- --
--   >>> [tz|123 mega|]
--   UnsafeMutez {unMutez = 123000000000000}
--   
-- --
--   >>> [tz|123e6|]
--   UnsafeMutez {unMutez = 123000000000000}
--   
-- --
--   >>> [tz|123m|]
--   UnsafeMutez {unMutez = 123000}
--   
-- --
--   >>> [tz|123 milli|]
--   UnsafeMutez {unMutez = 123000}
--   
-- --
--   >>> [tz|123u|]
--   UnsafeMutez {unMutez = 123}
--   
-- --
--   >>> [tz|123μ|]
--   UnsafeMutez {unMutez = 123}
--   
-- --
--   >>> [tz|123 micro|]
--   UnsafeMutez {unMutez = 123}
--   
-- --
--   >>> [tz| 123.456_789 |]
--   UnsafeMutez {unMutez = 123456789}
--   
-- --
--   >>> [tz|123.456u|]
--   ...
--   ... error:
--   ...  • The number is a mutez fraction. The smallest possible subdivision is 0.000001 XTZ
--   ...
--   
-- --
--   >>> [tz|0.012_345_6|]
--   ...
--   ... error:
--   ...  • The number is a mutez fraction. The smallest possible subdivision is 0.000001 XTZ
--   ...
--   
-- --
--   >>> [tz| 9223372.036854775807 M |]
--   UnsafeMutez {unMutez = 9223372036854775807}
--   
-- --
--   >>> [tz| 9223372.036854775808 M |]
--   ...
--   ... error:
--   ...  • The number is out of mutez bounds. It must be between 0 and 9223372036854.775807 XTZ (inclusive).
--   ...
--   
-- --
--   >>> [tz| -1 |]
--   ...
--   ... error:
--   ...  • The number is out of mutez bounds. It must be between 0 and 9223372036854.775807 XTZ (inclusive).
--   ...
--   
tz :: QuasiQuoter -- | Safely create Mutez. -- -- When constructing literals, you'll need to specify the type of the -- literal. GHC will check for literal overflow on builtin types like -- Word16 and Word32, but not on Word62 or -- Word63, so those can overflow silently. -- -- It's recommended to use tz quasiquote for literals instead. toMutez :: (Integral a, CheckIntSubType a Word63) => a -> Mutez zeroMutez :: Mutez oneMutez :: Mutez timestampFromSeconds :: Integer -> Timestamp timestampFromUTCTime :: UTCTime -> Timestamp -- | Quote a value of type Timestamp in -- yyyy-mm-ddThh:mm:ss[.sss]Z format. -- --
--   >>> formatTimestamp [timestampQuote| 2019-02-21T16:54:12.2344523Z |]
--   "2019-02-21T16:54:12Z"
--   
-- -- Inspired by 'time-quote' library. timestampQuote :: QuasiQuoter -- | Data type corresponding to address structure in Tezos. type Address = Constrained NullConstraint :: AddressKind -> Constraint KindedAddress -- | Get the term-level type of notes, preserving annotations. mkUType :: forall (x :: T). Notes x -> Ty -- | Address with optional entrypoint name attached to it. data EpAddress EpAddress' :: Address -> EpName -> EpAddress -- | Address itself [eaAddress] :: EpAddress -> Address -- | Entrypoint name (might be empty) [eaEntrypoint] :: EpAddress -> EpName pattern EpAddress :: forall (kind :: AddressKind). () => KindedAddress kind -> EpName -> EpAddress -- | Constraint ensuring the given code does not appear on the top level of -- a view. Some Michelson instructions are forbidden on the top level of -- views, but allowed in main contract code, and also inside lambdas in -- views. Hence, this constraint can be provided by mkContractCode -- or by mkVLam. class IsNotInView -- | Keeps documentation gathered for some piece of contract code. -- -- Used for building documentation of a contract. data ContractDoc ContractDoc :: DocBlock -> DocBlock -> Set SomeDocDefinitionItem -> Set DocItemId -> ContractDoc -- | All inlined doc items. [cdContents] :: ContractDoc -> DocBlock -- | Definitions used in document. -- -- Usually you put some large and repetitive descriptions here. This -- differs from the document content in that it contains sections which -- are always at top-level, disregard the nesting. -- -- All doc items which define docItemId method go here, and only -- they. [cdDefinitions] :: ContractDoc -> DocBlock -- | We remember all already declared entries to avoid cyclic dependencies -- in documentation items discovery. [cdDefinitionsSet] :: ContractDoc -> Set SomeDocDefinitionItem -- | We remember all already used identifiers. (Documentation naturally -- should not declare multiple items with the same identifier because -- that would make references to the respective anchors ambiguous). [cdDefinitionIds] :: ContractDoc -> Set DocItemId -- | A part of documentation to be grouped. Essentially incapsulates -- DocBlock. newtype SubDoc SubDoc :: DocBlock -> SubDoc -- | Several doc items of the same type. data DocSection DocSection :: (NonEmpty $ DocElem d) -> DocSection -- | A doc item which we store, along with related information. data DocElem d DocElem :: d -> Maybe SubDoc -> DocElem d -- | Doc item itself. [deItem] :: DocElem d -> d -- | Subdocumentation, if given item is a group. [deSub] :: DocElem d -> Maybe SubDoc -- | Hides some documentation item which is put to "definitions" section. data SomeDocDefinitionItem [SomeDocDefinitionItem] :: forall d. (DocItem d, DocItemPlacement d ~ 'DocItemInDefinitions) => d -> SomeDocDefinitionItem -- | Hides some documentation item. data SomeDocItem [SomeDocItem] :: forall d. DocItem d => d -> SomeDocItem -- | How to render section name. data DocSectionNameStyle -- | Suitable for block name. DocSectionNameBig :: DocSectionNameStyle -- | Suitable for subsection title within block. DocSectionNameSmall :: DocSectionNameStyle data DocItemRef (p :: DocItemPlacementKind) (r :: DocItemReferencedKind) [DocItemRef] :: DocItemId -> DocItemRef 'DocItemInDefinitions 'True [DocItemRefInlined] :: DocItemId -> DocItemRef 'DocItemInlined 'True [DocItemNoRef] :: DocItemRef 'DocItemInlined 'False -- | Where do we place given doc item. data DocItemPlacementKind -- | Placed in the document content itself. DocItemInlined :: DocItemPlacementKind -- | Placed in dedicated definitions section; can later be referenced. DocItemInDefinitions :: DocItemPlacementKind -- | Position of all doc items of some type. newtype DocItemPos DocItemPos :: (Natural, Text) -> DocItemPos -- | Some unique identifier of a doc item. -- -- All doc items which should be refer-able need to have this identifier. newtype DocItemId DocItemId :: Text -> DocItemId -- | A piece of documentation describing one property of a thing, be it a -- name or description of a contract, or an error throwable by given -- endpoint. -- -- Items of the same type appear close to each other in a rendered -- documentation and form a section. -- -- Doc items are later injected into a contract code via a dedicated -- nop-like instruction. Normally doc items which belong to one section -- appear in resulting doc in the same order in which they appeared in -- the contract. -- -- While documentation framework grows, this typeclass acquires more and -- more methods for fine tuning of existing rendering logic because we -- don't want to break backward compatibility, hope one day we will make -- everything concise :( E.g. all rendering and reording stuff could be -- merged in one method, and we could have several template -- implementations for it which would allow user to specify only stuff -- relevant to his case. class (Typeable d, DOrd d) => DocItem d where { -- | Defines where given doc item should be put. There are two options: 1. -- Inline right here (default behaviour); 2. Put into definitions -- section. -- -- Note that we require all doc items with "in definitions" placement to -- have Eq and Ord instances which comply the following -- law: if two documentation items describe the same entity or property, -- they should be considered equal. type family DocItemPlacement d :: DocItemPlacementKind; type family DocItemReferenced d :: DocItemReferencedKind; type DocItemPlacement d = 'DocItemInlined; type DocItemReferenced d = 'False; } -- | Position of this item in the resulting documentation; the smaller the -- value, the higher the section with this element will be placed. If the -- position is the same as other doc items, they will be placed base on -- their name, alphabetically. -- -- Documentation structure is not necessarily flat. If some doc item -- consolidates a whole documentation block within it, this block will -- have its own placement of items independent from outer parts of the -- doc. docItemPos :: DocItem d => Natural -- | When multiple items of the same type belong to one section, how this -- section will be called. -- -- If not provided, section will contain just untitled content. docItemSectionName :: DocItem d => Maybe Text -- | Description of a section. -- -- Can be used to mention some common things about all elements of this -- section. Markdown syntax is permitted here. docItemSectionDescription :: DocItem d => Maybe Markdown -- | How to render section name. -- -- Takes effect only if section name is set. docItemSectionNameStyle :: DocItem d => DocSectionNameStyle -- | Defines a function which constructs an unique identifier of given doc -- item, if it has been decided to put the doc item into definitions -- section. -- -- Identifier should be unique both among doc items of the same type and -- items of other types. Thus, consider using "typeId-contentId" pattern. docItemRef :: DocItem d => d -> DocItemRef (DocItemPlacement d) (DocItemReferenced d) -- | Render given doc item to Markdown, preferably one line, optionally -- with header. -- -- Accepts the smallest allowed level of header. (Using smaller value -- than provided one will interfere with existing headers thus delivering -- mess). docItemToMarkdown :: DocItem d => HeaderLevel -> d -> Markdown -- | Render table of contents entry for given doc item to Markdown. docItemToToc :: DocItem d => HeaderLevel -> d -> Markdown -- | All doc items which this doc item refers to. -- -- They will automatically be put to definitions as soon as given doc -- item is detected. docItemDependencies :: DocItem d => d -> [SomeDocDefinitionItem] -- | This function accepts doc items put under the same section in the -- order in which they appeared in the contract and returns their new -- desired order. It's also fine to use this function for filtering or -- merging doc items. -- -- Default implementation * leaves inlined items as is; * for items put -- to definitions, lexicographically sorts them by their id. docItemsOrder :: DocItem d => [d] -> [d] -- | Defines where given doc item should be put. There are two options: 1. -- Inline right here (default behaviour); 2. Put into definitions -- section. -- -- Note that we require all doc items with "in definitions" placement to -- have Eq and Ord instances which comply the following -- law: if two documentation items describe the same entity or property, -- they should be considered equal. type family DocItemPlacement d :: DocItemPlacementKind type family DocItemReferenced d :: DocItemReferencedKind -- | Generate DToc entry anchor from docItemRef. mdTocFromRef :: (DocItem d, DocItemReferenced d ~ 'True) => HeaderLevel -> Markdown -> d -> Markdown -- | Get doc item position at term-level. docItemPosition :: DocItem d => DocItemPos -- | Make a reference to doc item in definitions. docDefinitionRef :: (DocItem d, DocItemPlacement d ~ 'DocItemInDefinitions) => Markdown -> d -> Markdown -- | Reference to the given section. -- -- Will return Nothing if sections of given doc item type are -- not assumed to be referred outside. docItemSectionRef :: DocItem di => Maybe Markdown -- | Render documentation for SubDoc. subDocToMarkdown :: HeaderLevel -> SubDoc -> Markdown -- | A hand-made anchor. data DAnchor DAnchor :: Anchor -> DAnchor -- | Comment in the doc (mostly used for licenses) data DComment DComment :: Text -> DComment -- | Repository settings for DGitRevision. newtype GitRepoSettings GitRepoSettings :: (Text -> Text) -> GitRepoSettings -- | By commit sha make up a url to that commit in remote repository. [grsMkGitRevision] :: GitRepoSettings -> Text -> Text data DGitRevision DGitRevisionKnown :: DGitRevisionInfo -> DGitRevision DGitRevisionUnknown :: DGitRevision -- | Description of something. data DDescription DDescription :: Markdown -> DDescription -- | Give a name to document block. data DName DName :: Text -> SubDoc -> DName -- | General (meta-)information about the contract such as git revision, -- contract's authors, etc. Should be relatively short (not several -- pages) because it is put somewhere close to the beginning of -- documentation. newtype DGeneralInfoSection DGeneralInfoSection :: SubDoc -> DGeneralInfoSection -- | Often there is some tuning recommended prior to rendering the -- contract, like attaching git revision info; this type designates that -- those last changes were applied. -- -- For example, at Michelson level you may want to use -- attachDocCommons. -- -- If you want no special tuning (e.g. for tests), say that explicitly -- with finalizedAsIs. data WithFinalizedDoc a -- | Some contract languages may support documentation update. class ContainsDoc a => ContainsUpdateableDoc a -- | Modify all documentation items recursively. modifyDocEntirely :: ContainsUpdateableDoc a => (SomeDocItem -> SomeDocItem) -> a -> a -- | Everything that contains doc items that can be used to render the -- documentation. class ContainsDoc a -- | Gather documentation. -- -- Calling this method directly is discouraged in prod, see -- buildDoc instead. Using this method in tests is fine though. buildDocUnfinalized :: ContainsDoc a => a -> ContractDoc -- | A function which groups a piece of doc under one doc item. type DocGrouping = SubDoc -> SomeDocItem -- | Render given contract documentation to markdown document. contractDocToMarkdown :: ContractDoc -> LText -- | Mark the code with doc as finalized without any changes. finalizedAsIs :: a -> WithFinalizedDoc a -- | Gather documenation. buildDoc :: ContainsDoc a => WithFinalizedDoc a -> ContractDoc -- | Construct and format documentation in textual form. buildMarkdownDoc :: ContainsDoc a => WithFinalizedDoc a -> LText -- | Recursevly traverse doc items and modify those that match given type. -- -- If mapper returns Nothing, doc item will remain unmodified. modifyDoc :: (ContainsUpdateableDoc a, DocItem i1, DocItem i2) => (i1 -> Maybe i2) -> a -> a morleyRepoSettings :: GitRepoSettings -- | Make DGitRevision. -- --
--   >>> :t $mkDGitRevision
--   ...
--   ... :: GitRepoSettings -> DGitRevision
--   
mkDGitRevision :: ExpQ -- | Attach common information that is available only in the end. attachDocCommons :: ContainsUpdateableDoc a => DGitRevision -> a -> WithFinalizedDoc a type Operation = Operation' Instr type Value = Value' Instr data BigMap k v -- | Phantom type that represents the ID of a big_map with keys of type -- k and values of type v. newtype BigMapId (k2 :: k) (v :: k1) BigMapId :: Natural -> BigMapId (k2 :: k) (v :: k1) [unBigMapId] :: BigMapId (k2 :: k) (v :: k1) -> Natural -- | Ticket type. data Ticket arg Ticket :: Address -> arg -> Natural -> Ticket arg [tTicketer] :: Ticket arg -> Address [tData] :: Ticket arg -> arg [tAmount] :: Ticket arg -> Natural -- | Since Contract name is used to designate contract code, lets -- call analogy of TContract type as follows. -- -- Note that type argument always designates an argument of entrypoint. -- If a contract has explicit default entrypoint (and no root -- entrypoint), ContractRef referring to it can never have the -- entire parameter as its type argument. data ContractRef arg ContractRef :: Address -> SomeEntrypointCall arg -> ContractRef arg [crAddress] :: ContractRef arg -> Address [crEntrypoint] :: ContractRef arg -> SomeEntrypointCall arg type WellTypedToT a = (IsoValue a, WellTyped ToT a) type SomeEntrypointCall arg = SomeEntrypointCallT ToT arg type EntrypointCall param arg = EntrypointCallT ToT param ToT arg -- | Isomorphism between Michelson values and plain Haskell types. -- -- Default implementation of this typeclass converts ADTs to Michelson -- "pair"s and "or"s. class WellTypedToT a => IsoValue a where { -- | Type function that converts a regular Haskell type into a T -- type. type family ToT a :: T; type ToT a = GValueType Rep a; } -- | Converts a Haskell structure into Value representation. toVal :: IsoValue a => a -> Value (ToT a) -- | Converts a Value into Haskell type. fromVal :: IsoValue a => Value (ToT a) -> a -- | Type function that converts a regular Haskell type into a T -- type. type family ToT a :: T -- | Replace type argument of ContractRef with isomorphic one. coerceContractRef :: ToT a ~ ToT b => ContractRef a -> ContractRef b -- | Constraint for instrConstruct and gInstrConstructStack. type InstrConstructC dt = (GenericIsoValue dt, GInstrConstruct Rep dt '[] :: [Type]) -- | Types of all fields in a datatype. type ConstructorFieldTypes dt = GFieldTypes Rep dt '[] :: [Type] -- | Require this type to be homomorphic. class IsHomomorphic (a :: k) -- | Require two types to be built from the same type constructor. -- -- E.g. HaveCommonTypeCtor (Maybe Integer) (Maybe Natural) is -- defined, while HaveCmmonTypeCtor (Maybe Integer) [Integer] is -- not. class HaveCommonTypeCtor (a :: k) (b :: k1) -- | Doc element with description of a type. data DType [DType] :: forall a. TypeHasDoc a => Proxy a -> DType -- | Data hides some type implementing TypeHasDoc. data SomeTypeWithDoc [SomeTypeWithDoc] :: forall td. TypeHasDoc td => Proxy td -> SomeTypeWithDoc -- | Description for a Haskell type appearing in documentation. class (Typeable a, SingI TypeDocFieldDescriptions a, FieldDescriptionsValid TypeDocFieldDescriptions a a) => TypeHasDoc a where { -- | Description of constructors and fields of a. -- -- See FieldDescriptions documentation for an example of usage. -- -- Descriptions will be checked at compile time to make sure that only -- existing constructors and fields are referenced. -- -- For that check to work instance Generic a is required -- whenever TypeDocFieldDescriptions is not empty. -- -- For implementation of the check see FieldDescriptionsValid type -- family. type family TypeDocFieldDescriptions a :: FieldDescriptions; type TypeDocFieldDescriptions a = '[] :: [(Symbol, (Maybe Symbol, [(Symbol, Symbol)]))]; } -- | Name of type as it appears in definitions section. -- -- Each type must have its own unique name because it will be used in -- identifier for references. -- -- Default definition derives name from Generics. If it does not fit, -- consider defining this function manually. (We tried using -- Data.Data for this, but it produces names including module -- names which is not do we want). typeDocName :: TypeHasDoc a => Proxy a -> Text -- | Explanation of a type. Markdown formatting is allowed. typeDocMdDescription :: TypeHasDoc a => Markdown -- | How reference to this type is rendered, in Markdown. -- -- Examples: -- -- -- -- Consider using one of the following functions as default -- implementation; which one to use depends on number of type arguments -- in your type: -- -- -- -- If none of them fits your purposes precisely, consider using -- customTypeDocMdReference. typeDocMdReference :: TypeHasDoc a => Proxy a -> WithinParens -> Markdown -- | All types which this type directly contains. -- -- Used in automatic types discovery. typeDocDependencies :: TypeHasDoc a => Proxy a -> [SomeDocDefinitionItem] -- | For complex types - their immediate Haskell representation. -- -- For primitive types set this to Nothing. -- -- For homomorphic types use homomorphicTypeDocHaskellRep -- implementation. -- -- For polymorphic types consider using concreteTypeDocHaskellRep -- as implementation. -- -- Modifier haskellRepNoFields can be used to hide names of -- fields, beneficial for newtypes. -- -- Use haskellRepAdjust or haskellRepMap for more involved -- adjustments. -- -- Also, consider defining an instance of -- TypeHasFieldNamingStrategy instead of defining this method -- -- the former can be used downstream, e.g. in lorentz, for better naming -- consistency. typeDocHaskellRep :: TypeHasDoc a => TypeDocHaskellRep a -- | Final michelson representation of a type. -- -- For homomorphic types use homomorphicTypeDocMichelsonRep -- implementation. -- -- For polymorphic types consider using -- concreteTypeDocMichelsonRep as implementation. typeDocMichelsonRep :: TypeHasDoc a => TypeDocMichelsonRep a -- | Description of constructors and fields of a. -- -- See FieldDescriptions documentation for an example of usage. -- -- Descriptions will be checked at compile time to make sure that only -- existing constructors and fields are referenced. -- -- For that check to work instance Generic a is required -- whenever TypeDocFieldDescriptions is not empty. -- -- For implementation of the check see FieldDescriptionsValid type -- family. type family TypeDocFieldDescriptions a :: FieldDescriptions -- | Field naming strategy used by a type. id by default. -- -- Some common options include: > typeFieldNamingStrategy = -- stripFieldPrefix > typeFieldNamingStrategy = toSnake . dropPrefix -- -- This is used by the default implementation of typeDocHaskellRep -- and intended to be reused downstream. -- -- You can also use DerivingVia together with -- FieldCamelCase and FieldSnakeCase to easily define -- instances of this class: -- --
--   data MyType = ... deriving TypeHasFieldNamingStrategy via FieldCamelCase
--   
class TypeHasFieldNamingStrategy (a :: k) typeFieldNamingStrategy :: TypeHasFieldNamingStrategy a => Text -> Text -- | Fully render Michelson representation of a type. typeDocBuiltMichelsonRep :: TypeHasDoc a => Proxy a -> Builder -- | Create a DType in form suitable for putting to -- typeDocDependencies. dTypeDep :: TypeHasDoc t => SomeDocDefinitionItem -- | Shortcut for DStorageType. dStorage :: TypeHasDoc store => DStorageType -- | Render a reference to a type which consists of type constructor (you -- have to provide name of this type constructor and documentation for -- the whole type) and zero or more type arguments. customTypeDocMdReference :: (Text, DType) -> [DType] -> WithinParens -> Markdown -- | Derive typeDocMdReference, for homomorphic types only. homomorphicTypeDocMdReference :: (Typeable t, TypeHasDoc t, IsHomomorphic t) => Proxy t -> WithinParens -> Markdown -- | Derive typeDocMdReference, for polymorphic type with one type -- argument, like Maybe Integer. poly1TypeDocMdReference :: forall (t :: Type -> Type) r a. (r ~ t a, Typeable t, Each '[TypeHasDoc] '[r, a], IsHomomorphic t) => Proxy r -> WithinParens -> Markdown -- | Derive typeDocMdReference, for polymorphic type with two type -- arguments, like Lambda Integer Natural. 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 -- | Implement typeDocDependencies via getting all immediate fields -- of a datatype. -- -- Note: this will not include phantom types, I'm not sure yet how this -- scenario should be handled (@martoon). genericTypeDocDependencies :: (Generic a, GTypeHasDoc (Rep a)) => Proxy a -> [SomeDocDefinitionItem] -- | Implement typeDocHaskellRep for a homomorphic type. -- -- Note that it does not require your type to be of IsHomomorphic -- instance, which can be useful for some polymorphic types which, for -- documentation purposes, we want to consider homomorphic. -- -- Example: Operation is in fact polymorphic, but we don't want -- this fact to be reflected in the documentation. homomorphicTypeDocHaskellRep :: (Generic a, GTypeHasDoc (Rep a)) => TypeDocHaskellRep a -- | Implement typeDocHaskellRep on example of given concrete type. -- -- This is a best effort attempt to implement typeDocHaskellRep -- for polymorphic types, as soon as there is no simple way to preserve -- type variables when automatically deriving Haskell representation of a -- type. concreteTypeDocHaskellRep :: (Typeable a, GenericIsoValue a, GTypeHasDoc (Rep a), HaveCommonTypeCtor b a) => TypeDocHaskellRep b -- | Version of concreteTypeDocHaskellRep which does not ensure -- whether the type for which representation is built is any similar to -- the original type which you implement a TypeHasDoc instance -- for. unsafeConcreteTypeDocHaskellRep :: (Typeable a, GenericIsoValue a, GTypeHasDoc (Rep a)) => TypeDocHaskellRep b -- | Erase fields from Haskell datatype representation. -- -- Use this when rendering fields names is undesired. haskellRepNoFields :: TypeDocHaskellRep a -> TypeDocHaskellRep a -- | Map over fields with stripFieldPrefix. Equivalent to -- haskellRepMap stripFieldPrefix. Left for compatibility. haskellRepStripFieldPrefix :: TypeDocHaskellRep a -> TypeDocHaskellRep a -- | Add field name for newtype. -- -- Since newtype field is automatically erased. Use this -- function to add the desired field name. haskellAddNewtypeField :: Text -> TypeDocHaskellRep a -> TypeDocHaskellRep a -- | Implement typeDocMichelsonRep for homomorphic type. homomorphicTypeDocMichelsonRep :: KnownIsoT a => TypeDocMichelsonRep a -- | Implement typeDocMichelsonRep on example of given concrete -- type. -- -- This function exists for the same reason as -- concreteTypeDocHaskellRep. concreteTypeDocMichelsonRep :: forall {k} a (b :: k). (Typeable a, KnownIsoT a, HaveCommonTypeCtor b a) => TypeDocMichelsonRep b -- | Version of unsafeConcreteTypeDocHaskellRep which does not -- ensure whether the type for which representation is built is any -- similar to the original type which you implement a TypeHasDoc -- instance for. unsafeConcreteTypeDocMichelsonRep :: forall {k} a (b :: k). (Typeable a, KnownIsoT a) => TypeDocMichelsonRep b mkBigMap :: ToBigMap m => m -> BigMap (ToBigMapKey m) (ToBigMapValue m) -- | Replicate the old behavior of (#), which ignores anything -- after failing instructions. Indigo relies on this. TODO #62: -- reconsider this. (#) :: (a :-> b) -> (b :-> c) -> a :-> c infixl 8 # -- | Datatype representing Indigo variables and utilities for working with -- them. module Indigo.Common.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. data StackVars (stk :: [Type]) [StkElements] :: Rec StkEl stk -> StackVars stk [FailureStack] :: StackVars stk type StackVars' stk = 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, KnownIsoT a) => StkEl a [Ref] :: (KnownValue a, KnownIsoT 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 GHC.Enum.Bounded Indigo.Common.Var.RefId instance GHC.Enum.Enum Indigo.Common.Var.RefId instance GHC.Real.Integral Indigo.Common.Var.RefId instance GHC.Num.Num Indigo.Common.Var.RefId instance GHC.Real.Real Indigo.Common.Var.RefId instance GHC.Classes.Ord Indigo.Common.Var.RefId instance GHC.Classes.Eq Indigo.Common.Var.RefId instance GHC.Generics.Generic Indigo.Common.Var.RefId instance GHC.Show.Show Indigo.Common.Var.RefId instance forall k (a :: k). GHC.Show.Show (Indigo.Common.Var.Var a) instance forall k (a :: k). GHC.Generics.Generic (Indigo.Common.Var.Var a) instance forall k (a :: k). Formatting.Buildable.Buildable (Indigo.Common.Var.Var a) instance Data.Default.Class.Default (Indigo.Common.Var.StackVars '[]) instance (Lorentz.Constraints.Scopes.KnownValue x, Data.Default.Class.Default (Indigo.Common.Var.StackVars xs)) => Data.Default.Class.Default (Indigo.Common.Var.StackVars (x : xs)) instance Data.Type.Equality.TestEquality Indigo.Common.Var.StkEl instance Formatting.Buildable.Buildable Indigo.Common.Var.RefId module Indigo.Common.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), RecordToList (FieldTypes a)) castFieldConstructors :: forall a st. CastFieldConstructors (FieldTypes a) (ConstructorFieldTypes a) => Rec (FieldConstructor st) (FieldTypes a) -> Rec (FieldConstructor st) (ConstructorFieldTypes a) -- | Produce evidence of InstrDeconstructC for a concrete input -- stack, and run a computation with it. withInstrDeconstructC :: forall a st r. InstrDeconstructCGeneral a => (InstrDeconstructCClass a st => r) -> r instance Indigo.Common.Object.IsObject' (Indigo.Common.Object.TypeDecision a) a => Indigo.Common.Object.IsObject a instance Lorentz.Constraints.Scopes.KnownValue a => Indigo.Common.Object.IsObject' 'Indigo.Common.Object.PrimitiveD a instance Lorentz.Constraints.Scopes.KnownValue a => Indigo.Common.Object.IsObject' 'Indigo.Common.Object.SumTypeD a instance Indigo.Common.Object.ComplexObjectC a => Indigo.Common.Object.IsObject' 'Indigo.Common.Object.ProductTypeD a instance (forall (st :: [*]). Indigo.Common.Object.InstrDeconstructCClass a st) => Indigo.Common.Object.InstrDeconstructCGeneral a instance Indigo.Common.Object.InstrDeconstructCClassConstraint a st => Indigo.Common.Object.InstrDeconstructCClass a st -- | 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.Common.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 GenCodeHooks GenCodeHooks :: (forall inp out. Text -> (inp :-> out) -> inp :-> out) -> (forall inp out. Text -> (inp :-> out) -> inp :-> out) -> (forall inp out. Text -> (inp :-> out) -> inp :-> out) -> GenCodeHooks [gchStmtHook] :: GenCodeHooks -> forall inp out. Text -> (inp :-> out) -> inp :-> out [gchAuxiliaryHook] :: GenCodeHooks -> forall inp out. Text -> (inp :-> out) -> inp :-> out [gchExprHook] :: GenCodeHooks -> forall inp out. Text -> (inp :-> out) -> inp :-> out emptyGenCodeHooks :: GenCodeHooks data MetaData inp MetaData :: StackVars inp -> DecomposedObjects -> GenCodeHooks -> MetaData inp [mdStack] :: MetaData inp -> StackVars inp [mdObjects] :: MetaData inp -> DecomposedObjects [mdHooks] :: MetaData inp -> GenCodeHooks stmtHook :: forall inp out any. MetaData any -> Text -> (inp :-> out) -> inp :-> out stmtHookState :: Text -> IndigoState inp out -> IndigoState inp out auxiliaryHook :: forall inp out any. MetaData any -> Text -> (inp :-> out) -> inp :-> out auxiliaryHookState :: Text -> IndigoState inp out -> IndigoState inp out exprHook :: forall inp out any. MetaData any -> Text -> (inp :-> out) -> inp :-> out exprHookState :: Text -> 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 -- | 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 -- | Version of # which performs some optimizations immediately. -- -- In particular, this avoids glueing Nops. (##) :: (a :-> b) -> (b :-> c) -> a :-> c instance GHC.Base.Semigroup Indigo.Common.State.GenCodeHooks instance GHC.Base.Monoid Indigo.Common.State.GenCodeHooks -- | 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.Backend.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.Backend.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 :: forall {r :: RuntimeRep} a (b :: TYPE r). a -> b -> b infixr 0 `seq` -- | <math>. filter, applied to a predicate and a list, -- returns the list of those elements that satisfy the predicate; i.e., -- --
--   filter p xs = [ x | x <- xs, p x]
--   
-- --
--   >>> filter odd [1, 2, 3]
--   [1,3]
--   
filter :: (a -> Bool) -> [a] -> [a] -- | <math>. zip takes two lists and returns a list of -- corresponding pairs. -- --
--   >>> zip [1, 2] ['a', 'b']
--   [(1, 'a'), (2, 'b')]
--   
-- -- If one input list is shorter than the other, excess elements of the -- longer list are discarded, even if one of the lists is infinite: -- --
--   >>> zip [1] ['a', 'b']
--   [(1, 'a')]
--   
--   >>> zip [1, 2] ['a']
--   [(1, 'a')]
--   
--   >>> zip [] [1..]
--   []
--   
--   >>> zip [1..] []
--   []
--   
-- -- zip is right-lazy: -- --
--   >>> zip [] _|_
--   []
--   
--   >>> 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 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. -- -- 'join bss' can be understood as the do -- expression -- --
--   do bs <- bss
--      bs
--   
-- --

Examples

-- -- A common use of join is to run an IO computation -- returned from an STM transaction, since STM transactions -- can't perform IO directly. Recall that -- --
--   atomically :: STM a -> IO a
--   
-- -- is used to run STM transactions atomically. So, by specializing -- the types of atomically and join to -- --
--   atomically :: STM (IO b) -> IO (IO b)
--   join       :: IO (IO b)  -> IO b
--   
-- -- we can compose them as -- --
--   join . atomically :: STM (IO b) -> IO b
--   
-- -- to run an STM transaction and the IO action it returns. join :: Monad m => m (m a) -> m a -- | The Bounded class is used to name the upper and lower limits of -- a type. Ord is not a superclass of Bounded since types -- that are not totally ordered may also have upper and lower bounds. -- -- The Bounded class may be derived for any enumeration type; -- minBound is the first constructor listed in the data -- declaration and maxBound is the last. Bounded may also -- be derived for single-constructor datatypes whose constituent types -- are in Bounded. class Bounded a minBound :: Bounded a => a maxBound :: Bounded a => a -- | Class Enum defines operations on sequentially ordered types. -- -- The enumFrom... methods are used in Haskell's translation of -- arithmetic sequences. -- -- Instances of Enum may be derived for any enumeration type -- (types whose constructors have no fields). The nullary constructors -- are assumed to be numbered left-to-right by fromEnum from -- 0 through n-1. See Chapter 10 of the Haskell -- Report for more details. -- -- For any type that is an instance of class Bounded as well as -- Enum, the following should hold: -- -- -- --
--   enumFrom     x   = enumFromTo     x maxBound
--   enumFromThen x y = enumFromThenTo x y bound
--     where
--       bound | fromEnum y >= fromEnum x = maxBound
--             | otherwise                = minBound
--   
class Enum a -- | the successor of a value. For numeric types, succ adds 1. succ :: Enum a => a -> a -- | the predecessor of a value. For numeric types, pred subtracts -- 1. pred :: Enum a => a -> a -- | Convert from an Int. toEnum :: Enum a => Int -> a -- | Convert to an Int. It is implementation-dependent what -- fromEnum returns when applied to a value that is too large to -- fit in an Int. fromEnum :: Enum a => a -> Int -- | Used in Haskell's translation of [n..] with [n..] = -- enumFrom n, a possible implementation being enumFrom n = n : -- enumFrom (succ n). For example: -- -- enumFrom :: Enum a => a -> [a] -- | Used in Haskell's translation of [n,n'..] with [n,n'..] = -- enumFromThen n n', a possible implementation being -- enumFromThen n n' = n : n' : worker (f x) (f x n'), -- worker s v = v : worker s (s v), x = fromEnum n' - -- fromEnum n and f n y | n > 0 = f (n - 1) (succ y) | n < -- 0 = f (n + 1) (pred y) | otherwise = y For example: -- -- enumFromThen :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n..m] with [n..m] = -- enumFromTo n m, a possible implementation being enumFromTo n -- m | n <= m = n : enumFromTo (succ n) m | otherwise = []. For -- example: -- -- enumFromTo :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n,n'..m] with [n,n'..m] -- = enumFromThenTo n n' m, a possible implementation being -- enumFromThenTo n n' m = worker (f x) (c x) n m, x = -- fromEnum n' - fromEnum n, c x = bool (>=) ((x -- 0) f n y | n > 0 = f (n - 1) (succ y) | n < 0 = f (n + -- 1) (pred y) | otherwise = y and worker s c v m | c v m = v : -- worker s c (s v) m | otherwise = [] For example: -- -- enumFromThenTo :: Enum a => a -> a -> a -> [a] -- | The Eq class defines equality (==) and inequality -- (/=). All the basic datatypes exported by the Prelude -- are instances of Eq, and Eq may be derived for any -- datatype whose constituents are also instances of Eq. -- -- The Haskell Report defines no laws for Eq. However, == -- 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. -- -- 'as >>= bs' can be understood as the do -- expression -- --
--   do a <- as
--      bs a
--   
(>>=) :: Monad m => m a -> (a -> m b) -> m b -- | Sequentially compose two actions, discarding any value produced by the -- first, like sequencing operators (such as the semicolon) in imperative -- languages. -- -- 'as >> bs' can be understood as the do -- expression -- --
--   do as
--      bs
--   
(>>) :: Monad m => m a -> m b -> m b -- | Inject a value into the monadic type. return :: Monad m => a -> m a infixl 1 >>= infixl 1 >> -- | A type f is a Functor if it provides a function fmap -- which, given any types a and b lets you apply any -- function from (a -> b) to turn an f a into an -- f b, preserving the structure of f. Furthermore -- f needs to adhere to the following: -- -- -- -- Note, that the second law follows from the free theorem of the type -- fmap and the first law, so you need only check that the former -- condition holds. class Functor (f :: Type -> Type) -- | fmap is used to apply a function of type (a -> b) -- to a value of type f a, where f is a functor, to produce a -- value of type f b. Note that for any type constructor with -- more than one parameter (e.g., Either), only the last type -- parameter can be modified with fmap (e.g., b in -- `Either a b`). -- -- Some type constructors with two parameters or more have a -- Bifunctor instance that allows both the last and the -- penultimate parameters to be mapped over. ==== Examples -- -- Convert from a Maybe Int to a Maybe String -- using show: -- --
--   >>> fmap show Nothing
--   Nothing
--   
--   >>> fmap show (Just 3)
--   Just "3"
--   
-- -- Convert from an Either Int Int to an Either Int -- String using show: -- --
--   >>> fmap show (Left 17)
--   Left 17
--   
--   >>> fmap show (Right 17)
--   Right "17"
--   
-- -- Double each element of a list: -- --
--   >>> fmap (*2) [1,2,3]
--   [2,4,6]
--   
-- -- Apply even to the second element of a pair: -- --
--   >>> fmap even (2,2)
--   (2,True)
--   
-- -- It may seem surprising that the function is only applied to the last -- element of the tuple compared to the list example above which applies -- it to every element in the list. To understand, remember that tuples -- are type constructors with multiple type parameters: a tuple of 3 -- elements `(a,b,c)` can also be written `(,,) a b c` and its -- Functor instance is defined for `Functor ((,,) a b)` (i.e., -- only the third parameter is free to be mapped over with fmap). -- -- It explains why fmap can be used with tuples containing values -- of different types as in the following example: -- --
--   >>> fmap even ("hello", 1.0, 4)
--   ("hello",1.0,True)
--   
fmap :: Functor f => (a -> b) -> f a -> f b -- | Replace all locations in the input with the same value. The default -- definition is fmap . const, but this may be -- overridden with a more efficient version. (<$) :: Functor f => a -> f b -> f a infixl 4 <$ -- | Basic numeric class. -- -- The Haskell Report defines no laws for Num. However, -- (+) and (*) are customarily expected -- to define a ring and have the following properties: -- -- -- -- Note that it isn't customarily expected that a type instance of -- both Num and Ord implement an ordered ring. Indeed, in -- base only Integer and Rational do. class Num a -- | 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. --
-- -- Note that (7.) and (8.) do not require min and -- max to return either of their arguments. The result is merely -- required to equal one of the arguments in terms of (==). -- -- Minimal complete definition: either compare or <=. -- Using compare can be more efficient for complex types. class Eq a => Ord a compare :: Ord a => a -> a -> Ordering 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. -- --

Example

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

Example

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

Examples

-- -- If used in conjunction with the Applicative instance for Maybe, -- you can chain Maybe computations, with a possible "early return" in -- case of Nothing. -- --
--   >>> Just 2 *> Just 3
--   Just 3
--   
-- --
--   >>> Nothing *> Just 3
--   Nothing
--   
-- -- Of course a more interesting use case would be to have effectful -- computations instead of just returning pure values. -- --
--   >>> import Data.Char
--   
--   >>> import Text.ParserCombinators.ReadP
--   
--   >>> let p = string "my name is " *> munch1 isAlpha <* eof
--   
--   >>> readP_to_S p "my name is Simon"
--   [("Simon","")]
--   
(*>) :: Applicative f => f a -> f b -> f b -- | Sequence actions, discarding the value of the second argument. (<*) :: Applicative f => f a -> f b -> f a infixl 4 <* infixl 4 *> infixl 4 <*> -- | The Foldable class represents data structures that can be reduced to a -- summary value one element at a time. Strict left-associative folds are -- a good fit for space-efficient reduction, while lazy right-associative -- folds are a good fit for corecursive iteration, or for folds that -- short-circuit after processing an initial subsequence of the -- structure's elements. -- -- Instances can be derived automatically by enabling the -- DeriveFoldable extension. For example, a derived instance for -- a binary tree might be: -- --
--   {-# LANGUAGE DeriveFoldable #-}
--   data Tree a = Empty
--               | Leaf a
--               | Node (Tree a) a (Tree a)
--       deriving Foldable
--   
-- -- A more detailed description can be found in the Overview -- section of Data.Foldable#overview. -- -- For the class laws see the Laws section of -- Data.Foldable#laws. class Foldable (t :: Type -> Type) -- | Functors representing data structures that can be transformed to -- structures of the same shape by performing an -- Applicative (or, therefore, Monad) action on each -- element from left to right. -- -- A more detailed description of what same shape means, the -- various methods, how traversals are constructed, and example advanced -- use-cases can be found in the Overview section of -- Data.Traversable#overview. -- -- For the class laws see the Laws section of -- Data.Traversable#laws. class (Functor t, Foldable t) => Traversable (t :: Type -> Type) -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and collect the results. For a version that -- ignores the results see traverse_. -- --

Examples

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

Examples

-- -- Basic usage: -- -- For the first two examples we show sequenceA fully evaluating a a -- structure and collecting the results. -- --
--   >>> sequenceA [Just 1, Just 2, Just 3]
--   Just [1,2,3]
--   
-- --
--   >>> sequenceA [Right 1, Right 2, Right 3]
--   Right [1,2,3]
--   
-- -- The next two example show Nothing and Just will short -- circuit the resulting structure if present in the input. For more -- context, check the Traversable instances for Either and -- Maybe. -- --
--   >>> sequenceA [Just 1, Just 2, Just 3, Nothing]
--   Nothing
--   
-- --
--   >>> sequenceA [Right 1, Right 2, Right 3, Left 4]
--   Left 4
--   
sequenceA :: (Traversable t, Applicative f) => t (f a) -> f (t a) -- | Map each element of a structure to a monadic action, evaluate these -- actions from left to right, and collect the results. For a version -- that ignores the results see mapM_. -- --

Examples

-- -- mapM is literally a traverse with a type signature -- restricted to Monad. Its implementation may be more efficient -- due to additional power of Monad. mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b) -- | Evaluate each monadic action in the structure from left to right, and -- collect the results. For a version that ignores the results see -- sequence_. -- --

Examples

-- -- Basic usage: -- -- The first two examples are instances where the input and and output of -- sequence are isomorphic. -- --
--   >>> sequence $ Right [1,2,3,4]
--   [Right 1,Right 2,Right 3,Right 4]
--   
-- --
--   >>> sequence $ [Right 1,Right 2,Right 3,Right 4]
--   Right [1,2,3,4]
--   
-- -- The following examples demonstrate short circuit behavior for -- sequence. -- --
--   >>> sequence $ Left [1,2,3,4]
--   Left [1,2,3,4]
--   
-- --
--   >>> sequence $ [Left 0, Right 1,Right 2,Right 3,Right 4]
--   Left 0
--   
sequence :: (Traversable t, Monad m) => t (m a) -> m (t a) -- | Representable types of kind *. This class is derivable in GHC -- with the DeriveGeneric flag on. -- -- A Generic instance must satisfy the following laws: -- --
--   from . toid
--   to . fromid
--   
class Generic a -- | 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. -- --
--   >>> import Data.List.NonEmpty (NonEmpty (..))
--   
--   >>> sconcat $ "Hello" :| [" ", "Haskell", "!"]
--   "Hello Haskell!"
--   
sconcat :: Semigroup a => NonEmpty a -> a -- | Repeat a value n times. -- -- Given that this works on a Semigroup it is allowed to fail if -- you request 0 or fewer repetitions, and the default definition will do -- so. -- -- By making this a member of the class, idempotent semigroups and -- monoids can upgrade this to execute in <math> by picking -- stimes = stimesIdempotent or stimes = -- stimesIdempotentMonoid respectively. -- --
--   >>> stimes 4 [1]
--   [1,1,1,1]
--   
stimes :: (Semigroup a, Integral b) => b -> a -> a -- | The class of monoids (types with an associative binary operation that -- has an identity). Instances should satisfy the following: -- -- -- -- The method names refer to the monoid of lists under concatenation, but -- there are many other instances. -- -- Some types can be viewed as a monoid in more than one way, e.g. both -- addition and multiplication on numbers. In such cases we often define -- newtypes and make those instances of Monoid, e.g. -- Sum and Product. -- -- NOTE: Semigroup is a superclass of Monoid since -- base-4.11.0.0. class Semigroup a => Monoid a -- | Identity of mappend -- --
--   >>> "Hello world" <> mempty
--   "Hello world"
--   
mempty :: Monoid a => a -- | An associative operation -- -- NOTE: This method is redundant and has the default -- implementation mappend = (<>) since -- base-4.11.0.0. Should it be implemented manually, since -- mappend is a synonym for (<>), it is expected that -- the two functions are defined the same way. In a future GHC release -- mappend will be removed from Monoid. mappend :: Monoid a => a -> a -> a -- | Fold a list using the monoid. -- -- For most types, the default definition for mconcat will be -- used, but the function is included in the class definition so that an -- optimized version can be provided for specific types. -- --
--   >>> mconcat ["Hello", " ", "Haskell", "!"]
--   "Hello Haskell!"
--   
mconcat :: Monoid a => [a] -> a data Bool False :: Bool True :: Bool -- | A String is a list of characters. String constants in Haskell -- are values of type String. -- -- See Data.List for operations on lists. type String = [Char] -- | The character type Char is an enumeration whose values -- represent Unicode (or equivalently ISO/IEC 10646) code points (i.e. -- characters, see http://www.unicode.org/ for details). This set -- extends the ISO 8859-1 (Latin-1) character set (the first 256 -- characters), which is itself an extension of the ASCII character set -- (the first 128 characters). A character literal in Haskell has type -- Char. -- -- To convert a Char to or from the corresponding Int value -- defined by Unicode, use toEnum and fromEnum from the -- Enum class respectively (or equivalently ord and -- chr). data Char -- | Double-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- double-precision type. data Double 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 -- | Arbitrary precision integers. In contrast with fixed-size integral -- types such as Int, the Integer type represents the -- entire infinite range of integers. -- -- Integers are stored in a kind of sign-magnitude form, hence do not -- expect two's complement form when using bit operations. -- -- If the value is small (fit into an Int), IS constructor -- is used. Otherwise IP and IN constructors are used to -- store a BigNat representing respectively the positive or the -- negative value magnitude. -- -- Invariant: IP and IN are used iff value doesn't fit in -- IS data Integer -- | Natural number -- -- Invariant: numbers <= 0xffffffffffffffff use the NS -- constructor data Natural -- | The Maybe type encapsulates an optional value. A value of type -- Maybe a either contains a value of type a -- (represented as Just a), or it is empty (represented -- as Nothing). Using Maybe is a good way to deal with -- errors or exceptional cases without resorting to drastic measures such -- as error. -- -- The Maybe type is also a monad. It is a simple kind of error -- monad, where all errors are represented by Nothing. A richer -- error monad can be built using the Either type. data Maybe a Nothing :: Maybe a Just :: a -> Maybe a data Ordering LT :: Ordering EQ :: Ordering GT :: Ordering -- | Rational numbers, with numerator and denominator of some -- Integral type. -- -- Note that Ratio's instances inherit the deficiencies from the -- type parameter's. For example, Ratio Natural's Num -- instance has similar problems to Natural's. data Ratio a (:%) :: !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 types with lifted values. For example Int :: -- Type. type Type = Type -- | 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 -- | 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 -- | Reverse order of bytes in Word16. byteSwap16 :: Word16 -> Word16 -- | Reverse order of bytes in Word32. byteSwap32 :: Word32 -> Word32 -- | Reverse order of bytes in Word64. byteSwap64 :: Word64 -> Word64 -- | 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 -- | deepseq: fully evaluates the first argument, before returning -- the second. -- -- The name deepseq is used to illustrate the relationship to -- seq: where seq is shallow in the sense that it only -- evaluates the top level of its argument, deepseq traverses the -- entire data structure evaluating it completely. -- -- deepseq can be useful for forcing pending exceptions, -- eradicating space leaks, or forcing lazy I/O to happen. It is also -- useful in conjunction with parallel Strategies (see the -- parallel package). -- -- There is no guarantee about the ordering of evaluation. The -- implementation may evaluate the components of the structure in any -- order or in parallel. To impose an actual order on evaluation, use -- pseq from Control.Parallel in the parallel -- package. deepseq :: NFData a => a -> b -> b -- | a 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 -- | 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 set of values a. data Set a -- | 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 -- | 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 -- | Function composition. (.) :: (b -> c) -> (a -> b) -> a -> c infixr 9 . -- | Same as >>=, but with the arguments interchanged. (=<<) :: Monad m => (a -> m b) -> m a -> m b infixr 1 =<< -- | 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 -- | asTypeOf is a type-restricted version of const. It is -- usually used as an infix operator, and its typing forces its first -- argument (which is usually overloaded) to have the same type as the -- second. asTypeOf :: a -> a -> a -- | const x is a unary function which evaluates to x for -- all inputs. -- --
--   >>> const 42 "hello"
--   42
--   
-- --
--   >>> map (const 42) [0..3]
--   [42,42,42,42]
--   
const :: a -> b -> a -- | flip f takes its (first) two arguments in the reverse -- order of f. -- --
--   >>> flip (++) "hello" "world"
--   "worldhello"
--   
flip :: (a -> b -> c) -> b -> a -> c -- | Identity function. -- --
--   id x = x
--   
id :: a -> a -- | 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 -- | The fromEnum method restricted to the type Char. ord :: Char -> Int -- | 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 -- | Non-empty (and non-strict) list type. data NonEmpty a (:|) :: a -> [a] -> NonEmpty a infixr 5 :| -- | 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 -- | curry converts an uncurried function to a curried function. -- --

Examples

-- --
--   >>> curry fst 1 2
--   1
--   
curry :: ((a, b) -> c) -> a -> b -> c -- | 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 -- | 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 <$> -- | 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 () -- | 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` -- | 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 fromMaybe function takes a default value and a Maybe -- value. If the Maybe is Nothing, it returns the default -- value; otherwise, it returns the value contained in the Maybe. -- --

Examples

-- -- Basic usage: -- --
--   >>> fromMaybe "" (Just "Hello, World!")
--   "Hello, World!"
--   
-- --
--   >>> fromMaybe "" Nothing
--   ""
--   
-- -- Read an integer from a string using readMaybe. If we fail to -- parse an integer, we want to return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> fromMaybe 0 (readMaybe "5")
--   5
--   
--   >>> fromMaybe 0 (readMaybe "")
--   0
--   
fromMaybe :: a -> Maybe a -> a -- | The 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 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 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 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 maybe function takes a default value, a function, and a -- Maybe value. If the Maybe value is Nothing, the -- function returns the default value. Otherwise, it applies the function -- to the value inside the Just and returns the result. -- --

Examples

-- -- Basic usage: -- --
--   >>> maybe False odd (Just 3)
--   True
--   
-- --
--   >>> maybe False odd Nothing
--   False
--   
-- -- Read an integer from a string using readMaybe. If we succeed, -- return twice the integer; that is, apply (*2) to it. If -- instead we fail to parse an integer, return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> maybe 0 (*2) (readMaybe "5")
--   10
--   
--   >>> maybe 0 (*2) (readMaybe "")
--   0
--   
-- -- Apply show to a Maybe Int. If we have Just n, -- we want to show the underlying Int n. But if we have -- Nothing, we return the empty string instead of (for example) -- "Nothing": -- --
--   >>> maybe "" show (Just 5)
--   "5"
--   
--   >>> maybe "" show Nothing
--   ""
--   
maybe :: b -> (a -> b) -> Maybe a -> b -- | The 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] -- | break, applied to a predicate p and a list -- xs, returns a tuple where first element is longest prefix -- (possibly empty) of xs of elements that do not satisfy -- p and second element is the remainder of the list: -- --
--   >>> break (> 3) [1,2,3,4,1,2,3,4]
--   ([1,2,3],[4,1,2,3,4])
--   
--   >>> break (< 9) [1,2,3]
--   ([],[1,2,3])
--   
--   >>> break (> 9) [1,2,3]
--   ([1,2,3],[])
--   
-- -- break p is equivalent to span (not . -- p). break :: (a -> Bool) -> [a] -> ([a], [a]) -- | cycle ties a finite list into a circular one, or equivalently, -- the infinite repetition of the original list. It is the identity on -- infinite lists. -- --
--   >>> cycle []
--   *** Exception: Prelude.cycle: empty list
--   
--   >>> take 20 $ cycle [42]
--   [42,42,42,42,42,42,42,42,42,42...
--   
--   >>> take 20 $ cycle [2, 5, 7]
--   [2,5,7,2,5,7,2,5,7,2,5,7...
--   
cycle :: [a] -> [a] -- | drop n xs returns the suffix of xs after the -- first n elements, or [] if n >= length -- xs. -- --
--   >>> drop 6 "Hello World!"
--   "World!"
--   
--   >>> drop 3 [1,2,3,4,5]
--   [4,5]
--   
--   >>> drop 3 [1,2]
--   []
--   
--   >>> drop 3 []
--   []
--   
--   >>> drop (-1) [1,2]
--   [1,2]
--   
--   >>> drop 0 [1,2]
--   [1,2]
--   
-- -- It is an instance of the more general genericDrop, in which -- n may be of any integral type. drop :: Int -> [a] -> [a] -- | dropWhile p xs returns the suffix remaining after -- takeWhile p xs. -- --
--   >>> dropWhile (< 3) [1,2,3,4,5,1,2,3]
--   [3,4,5,1,2,3]
--   
--   >>> dropWhile (< 9) [1,2,3]
--   []
--   
--   >>> dropWhile (< 0) [1,2,3]
--   [1,2,3]
--   
dropWhile :: (a -> Bool) -> [a] -> [a] -- | iterate f x returns an infinite list of repeated -- applications of f to x: -- --
--   iterate f x == [x, f x, f (f x), ...]
--   
-- -- Note that iterate is lazy, potentially leading to thunk -- build-up if the consumer doesn't force each iterate. See -- iterate' for a strict variant of this function. -- --
--   >>> take 10 $ iterate not True
--   [True,False,True,False...
--   
--   >>> take 10 $ iterate (+3) 42
--   [42,45,48,51,54,57,60,63...
--   
iterate :: (a -> a) -> a -> [a] -- | repeat x is an infinite list, with x the -- value of every element. -- --
--   >>> take 20 $ repeat 17
--   [17,17,17,17,17,17,17,17,17...
--   
repeat :: a -> [a] -- | replicate n x is a list of length n with -- x the value of every element. It is an instance of the more -- general genericReplicate, in which n may be of any -- integral type. -- --
--   >>> replicate 0 True
--   []
--   
--   >>> replicate (-1) True
--   []
--   
--   >>> replicate 4 True
--   [True,True,True,True]
--   
replicate :: Int -> a -> [a] -- | reverse xs returns the elements of xs in -- reverse order. xs must be finite. -- --
--   >>> reverse []
--   []
--   
--   >>> reverse [42]
--   [42]
--   
--   >>> reverse [2,5,7]
--   [7,5,2]
--   
--   >>> reverse [1..]
--   * Hangs forever *
--   
reverse :: [a] -> [a] -- | <math>. scanl is similar to foldl, but returns a -- list of successive reduced values from the left: -- --
--   scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
--   
-- -- Note that -- --
--   last (scanl f z xs) == foldl f z xs
--   
-- --
--   >>> scanl (+) 0 [1..4]
--   [0,1,3,6,10]
--   
--   >>> scanl (+) 42 []
--   [42]
--   
--   >>> scanl (-) 100 [1..4]
--   [100,99,97,94,90]
--   
--   >>> scanl (\reversedString nextChar -> nextChar : reversedString) "foo" ['a', 'b', 'c', 'd']
--   ["foo","afoo","bafoo","cbafoo","dcbafoo"]
--   
--   >>> scanl (+) 0 [1..]
--   * Hangs forever *
--   
scanl :: (b -> a -> b) -> b -> [a] -> [b] -- | <math>. scanr is the right-to-left dual of scanl. -- Note that the order of parameters on the accumulating function are -- reversed compared to scanl. Also note that -- --
--   head (scanr f z xs) == foldr f z xs.
--   
-- --
--   >>> scanr (+) 0 [1..4]
--   [10,9,7,4,0]
--   
--   >>> scanr (+) 42 []
--   [42]
--   
--   >>> scanr (-) 100 [1..4]
--   [98,-97,99,-96,100]
--   
--   >>> scanr (\nextChar reversedString -> nextChar : reversedString) "foo" ['a', 'b', 'c', 'd']
--   ["abcdfoo","bcdfoo","cdfoo","dfoo","foo"]
--   
--   >>> force $ scanr (+) 0 [1..]
--   *** Exception: stack overflow
--   
scanr :: (a -> b -> b) -> b -> [a] -> [b] -- | 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]) -- | take n, applied to a list xs, returns the -- prefix of xs of length n, or xs itself if -- n >= length xs. -- --
--   >>> take 5 "Hello World!"
--   "Hello"
--   
--   >>> take 3 [1,2,3,4,5]
--   [1,2,3]
--   
--   >>> take 3 [1,2]
--   [1,2]
--   
--   >>> take 3 []
--   []
--   
--   >>> take (-1) [1,2]
--   []
--   
--   >>> take 0 [1,2]
--   []
--   
-- -- It is an instance of the more general genericTake, in which -- n may be of any integral type. take :: Int -> [a] -> [a] -- | takeWhile, applied to a predicate p and a list -- xs, returns the longest prefix (possibly empty) of -- xs of elements that satisfy p. -- --
--   >>> takeWhile (< 3) [1,2,3,4,1,2,3,4]
--   [1,2]
--   
--   >>> takeWhile (< 9) [1,2,3]
--   [1,2,3]
--   
--   >>> takeWhile (< 0) [1,2,3]
--   []
--   
takeWhile :: (a -> Bool) -> [a] -> [a] -- | unzip transforms a list of pairs into a list of first -- components and a list of second components. -- --
--   >>> unzip []
--   ([],[])
--   
--   >>> unzip [(1, 'a'), (2, 'b')]
--   ([1,2],"ab")
--   
unzip :: [(a, b)] -> ([a], [b]) -- | The unzip3 function takes a list of triples and returns three -- lists, analogous to unzip. -- --
--   >>> unzip3 []
--   ([],[],[])
--   
--   >>> unzip3 [(1, 'a', True), (2, 'b', False)]
--   ([1,2],"ab",[True,False])
--   
unzip3 :: [(a, b, c)] -> ([a], [b], [c]) -- | 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)] -- | <math>. zipWith generalises zip by zipping with -- the function given as the first argument, instead of a tupling -- function. -- --
--   zipWith (,) xs ys == zip xs ys
--   zipWith f [x1,x2,x3..] [y1,y2,y3..] == [f x1 y1, f x2 y2, f x3 y3..]
--   
-- -- For example, zipWith (+) is applied to two lists to -- produce the list of corresponding sums: -- --
--   >>> zipWith (+) [1, 2, 3] [4, 5, 6]
--   [5,7,9]
--   
-- -- zipWith is right-lazy: -- --
--   >>> 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] -- | The toEnum method restricted to the type Char. chr :: Int -> Char -- | raise a number to an integral power (^^) :: (Fractional a, Integral b) => a -> b -> a infixr 8 ^^ -- | 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 -- | lcm x y is the smallest positive integer that both -- x and y divide. lcm :: Integral a => a -> a -> a -- | Proxy is a type that holds no data, but has a phantom parameter -- of arbitrary type (or even kind). Its use is to provide type -- information, even though there is no value available of that type (or -- it may be too costly to create one). -- -- Historically, Proxy :: Proxy a is a safer -- alternative to the undefined :: a idiom. -- --
--   >>> Proxy :: Proxy (Void, Int -> Int)
--   Proxy
--   
-- -- Proxy can even hold types of higher kinds, -- --
--   >>> Proxy :: Proxy Either
--   Proxy
--   
-- --
--   >>> Proxy :: Proxy Functor
--   Proxy
--   
-- --
--   >>> Proxy :: Proxy complicatedStructure
--   Proxy
--   
data Proxy (t :: k) Proxy :: Proxy (t :: k) -- | 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 -- | 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]) -- | 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 -- |
--   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 -- | intercalate xs xss is equivalent to (concat -- (intersperse xs xss)). It inserts the list xs in -- between the lists in xss and concatenates the result. -- --
--   >>> intercalate ", " ["Lorem", "ipsum", "dolor"]
--   "Lorem, ipsum, dolor"
--   
intercalate :: [a] -> [[a]] -> [a] -- | <math>. The 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] -- | <math>. The isPrefixOf function takes two lists and -- returns True iff the first list is a prefix of the second. -- --
--   >>> "Hello" `isPrefixOf` "Hello World!"
--   True
--   
-- --
--   >>> "Hello" `isPrefixOf` "Wello Horld!"
--   False
--   
isPrefixOf :: Eq a => [a] -> [a] -> Bool -- | The sort function implements a stable sorting algorithm. It is -- a special case of sortBy, which allows the programmer to supply -- their own comparison function. -- -- Elements are arranged from lowest to highest, keeping duplicates in -- the order they appeared in the input. -- --
--   >>> sort [1,6,4,3,2,5]
--   [1,2,3,4,5,6]
--   
sort :: Ord a => [a] -> [a] -- | 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 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] -- | Map a function over all the elements of a container and concatenate -- the resulting lists. -- --

Examples

-- -- Basic usage: -- --
--   >>> concatMap (take 3) [[1..], [10..], [100..], [1000..]]
--   [1,2,3,10,11,12,100,101,102,1000,1001,1002]
--   
-- --
--   >>> concatMap (take 3) (Just [1..])
--   [1,2,3]
--   
concatMap :: Foldable t => (a -> [b]) -> t a -> [b] -- | The Const functor. newtype Const a (b :: k) Const :: a -> Const a (b :: k) [getConst] :: Const a (b :: k) -> a -- | Any type that you wish to throw or catch as an exception must be an -- instance of the Exception class. The simplest case is a new -- exception type directly below the root: -- --
--   data MyException = ThisException | ThatException
--       deriving Show
--   
--   instance Exception MyException
--   
-- -- The default method definitions in the Exception class do what -- we need in this case. You can now throw and catch -- ThisException and ThatException as exceptions: -- --
--   *Main> throw ThisException `catch` \e -> putStrLn ("Caught " ++ show (e :: MyException))
--   Caught ThisException
--   
-- -- In more complicated examples, you may wish to define a whole hierarchy -- of exceptions: -- --
--   ---------------------------------------------------------------------
--   -- Make the root exception type for all the exceptions in a compiler
--   
--   data SomeCompilerException = forall e . Exception e => SomeCompilerException e
--   
--   instance Show SomeCompilerException where
--       show (SomeCompilerException e) = show e
--   
--   instance Exception SomeCompilerException
--   
--   compilerExceptionToException :: Exception e => e -> SomeException
--   compilerExceptionToException = toException . SomeCompilerException
--   
--   compilerExceptionFromException :: Exception e => SomeException -> Maybe e
--   compilerExceptionFromException x = do
--       SomeCompilerException a <- fromException x
--       cast a
--   
--   ---------------------------------------------------------------------
--   -- Make a subhierarchy for exceptions in the frontend of the compiler
--   
--   data SomeFrontendException = forall e . Exception e => SomeFrontendException e
--   
--   instance Show SomeFrontendException where
--       show (SomeFrontendException e) = show e
--   
--   instance Exception SomeFrontendException where
--       toException = compilerExceptionToException
--       fromException = compilerExceptionFromException
--   
--   frontendExceptionToException :: Exception e => e -> SomeException
--   frontendExceptionToException = toException . SomeFrontendException
--   
--   frontendExceptionFromException :: Exception e => SomeException -> Maybe e
--   frontendExceptionFromException x = do
--       SomeFrontendException a <- fromException x
--       cast a
--   
--   ---------------------------------------------------------------------
--   -- Make an exception type for a particular frontend compiler exception
--   
--   data MismatchedParentheses = MismatchedParentheses
--       deriving Show
--   
--   instance Exception MismatchedParentheses where
--       toException   = frontendExceptionToException
--       fromException = frontendExceptionFromException
--   
-- -- We can now catch a MismatchedParentheses exception as -- MismatchedParentheses, SomeFrontendException or -- SomeCompilerException, but not other types, e.g. -- IOException: -- --
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: MismatchedParentheses))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeFrontendException))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeCompilerException))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: IOException))
--   *** Exception: MismatchedParentheses
--   
class (Typeable e, Show e) => Exception e toException :: Exception e => e -> SomeException fromException :: Exception e => SomeException -> Maybe e -- | Render this exception value in a human-friendly manner. -- -- Default implementation: show. displayException :: Exception e => e -> String -- | Pretty print a CallStack. prettyCallStack :: CallStack -> String -- | 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 -- | Return the current CallStack. -- -- Does *not* include the call-site of callStack. callStack :: HasCallStack => CallStack -- | Perform some computation without adding new entries to the -- CallStack. withFrozenCallStack :: HasCallStack => (HasCallStack => a) -> a -- | Identity functor and monad. (a non-strict monad) newtype Identity a Identity :: a -> Identity a [runIdentity] :: Identity a -> a -- | One or none. -- -- It is useful for modelling any computation that is allowed to fail. -- --

Examples

-- -- Using the Alternative instance of Except, the following -- functions: -- --
--   >>> canFail = throwError "it failed" :: Except String Int
--   
--   >>> final = return 42                :: Except String Int
--   
-- -- Can be combined by allowing the first function to fail: -- --
--   >>> runExcept $ canFail *> final
--   Left "it failed"
--   
--   >>> runExcept $ optional canFail *> final
--   Right 42
--   
optional :: Alternative f => f a -> f (Maybe a) -- | for is traverse with its arguments flipped. For a -- version that ignores the results see for_. for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b) -- | This generalizes the list-based filter function. filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a] -- | 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 -- | Extract the first element of the stream. head :: NonEmpty a -> a -- | 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] -- | 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 -- | If Void is uninhabited then any Functor that holds only -- values of type Void is holding no values. It is implemented in -- terms of fmap absurd. vacuous :: Functor f => f Void -> f a -- | Uninhabited data type data Void -- | 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 -- | 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 (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). liftM5 :: Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r -- | fix f is the least fixed point of the function -- f, i.e. the least defined x such that f x = -- x. -- -- For example, we can write the factorial function using direct -- recursion as -- --
--   >>> let fac n = if n <= 1 then 1 else n * fac (n-1) in fac 5
--   120
--   
-- -- This uses the fact that Haskell’s let introduces recursive -- bindings. We can rewrite this definition using fix, -- --
--   >>> fix (\rec n -> if n <= 1 then 1 else n * rec (n-1)) 5
--   120
--   
-- -- Instead of making a recursive call, we introduce a dummy parameter -- rec; when used within fix, this parameter then refers -- to fix’s argument, hence the recursion is reintroduced. fix :: (a -> a) -> a -- | 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) -- | Strict version of <$>. (<$!>) :: Monad m => (a -> b) -> m a -> m b infixl 4 <$!> -- | 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. -- -- '(bs >=> cs) a' can be understood as the -- do expression -- --
--   do b <- bs a
--      cs b
--   
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 >=> -- | Like foldM, but discards the result. foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m () -- | Repeat an action indefinitely. -- --

Examples

-- -- A common use of forever is to process input from network -- sockets, Handles, and channels (e.g. MVar and -- Chan). -- -- For example, here is how we might implement an echo server, -- using forever both to listen for client connections on a -- network socket and to echo client input on client connection handles: -- --
--   echoServer :: Socket -> IO ()
--   echoServer socket = forever $ do
--     client <- accept socket
--     forkFinally (echo client) (\_ -> hClose client)
--     where
--       echo :: Handle -> IO ()
--       echo client = forever $
--         hGetLine client >>= hPutStrLn client
--   
-- -- Note that "forever" isn't necessarily non-terminating. If the action -- is in a MonadPlus and short-circuits after some number -- of iterations. then forever actually returns -- mzero, effectively short-circuiting its caller. forever :: Applicative f => f a -> f b -- | 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]) -- | 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 -- | replicateM n act performs the action act -- n times, and then returns the list of results: -- --

Examples

-- --
--   >>> replicateM 3 (putStrLn "a")
--   a
--   a
--   a
--   
replicateM :: Applicative m => Int -> m a -> m [a] -- | Like replicateM, but discards the result. replicateM_ :: Applicative m => Int -> m a -> m () -- | The zipWithM function generalizes zipWith to arbitrary -- applicative functors. zipWithM :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m [c] -- | zipWithM_ is the extension of zipWithM which ignores the -- final result. zipWithM_ :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m () -- | Monads in which IO computations may be embedded. Any monad -- built by applying a sequence of monad transformers to the IO -- monad will be an instance of this class. -- -- Instances should satisfy the following laws, which state that -- liftIO is a transformer of monads: -- -- class Monad m => MonadIO (m :: Type -> Type) -- | Lift a computation from the IO monad. This allows us to run IO -- computations in any monadic stack, so long as it supports these kinds -- of operations (i.e. IO is the base monad for the stack). -- --

Example

-- --
--   import Control.Monad.Trans.State -- from the "transformers" library
--   
--   printState :: Show s => StateT s IO ()
--   printState = do
--     state <- get
--     liftIO $ print state
--   
-- -- Had we omitted liftIO, we would have ended up with -- this error: -- --
--   • Couldn't match type ‘IO’ with ‘StateT s IO’
--    Expected type: StateT s IO ()
--      Actual type: IO ()
--   
-- -- The important part here is the mismatch between StateT s IO -- () and IO (). -- -- Luckily, we know of a function that takes an IO a and -- returns an (m a): liftIO, enabling us to run -- the program and see the expected results: -- --
--   > evalStateT printState "hello"
--   "hello"
--   
--   > evalStateT printState 3
--   3
--   
liftIO :: MonadIO m => IO a -> m a -- | 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 () type Word62 = OddWord Word64 One One One One One Zero () type Word63 = OddWord Word64 One One One One One One () -- | 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 -- | The class of types that can be converted to a hash value. -- -- Minimal implementation: hashWithSalt. -- -- Note: the hash is not guaranteed to be stable across library -- versions, operating systems or architectures. For stable hashing use -- named hashes: SHA256, CRC32 etc. -- -- If you are looking for Hashable instance in time -- package, check time-compat class 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 -- | 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 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 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 -- | 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` -- | 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. newtype Option a Option :: Maybe a -> Option a [getOption] :: Option a -> Maybe a -- | Repeat a value n times. -- --
--   mtimesDefault n a = a <> a <> ... <> a  -- using <> (n-1) times
--   
-- -- Implemented using stimes and mempty. -- -- This is a suitable definition for an mtimes member of -- Monoid. mtimesDefault :: (Integral b, Monoid a) => b -> a -> a -- | A generalization of cycle to an arbitrary Semigroup. May -- fail to terminate for some values in some semigroups. cycle1 :: Semigroup m => m -> m -- | 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] -- | 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]) -- | The mapAccumR function behaves like a combination of -- fmap and foldr; it applies a function to each element of -- a structure, passing an accumulating parameter from right to left, and -- returning a final value of this accumulator together with the new -- structure. -- --

Examples

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

Examples

-- -- Basic usage: -- --
--   >>> mapAccumL (\a b -> (a + b, a)) 0 [1..10]
--   (55,[0,1,3,6,10,15,21,28,36,45])
--   
-- --
--   >>> mapAccumL (\a b -> (a <> show b, a)) "0" [1..5]
--   ("012345",["0","01","012","0123","01234"])
--   
mapAccumL :: Traversable t => (s -> a -> (s, b)) -> s -> t a -> (s, t b) -- | This function may be used as a value for foldMap in a -- Foldable instance. -- --
--   foldMapDefault f ≡ getConst . traverse (Const . f)
--   
foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m -- | This function may be used as a value for fmap in a -- Functor instance, provided that traverse is defined. -- (Using fmapDefault with a Traversable instance defined -- only by sequenceA will result in infinite recursion.) -- --
--   fmapDefault f ≡ runIdentity . traverse (Identity . f)
--   
fmapDefault :: Traversable t => (a -> b) -> t a -> t b -- | Lists, but with an Applicative functor based on zipping. newtype ZipList a ZipList :: [a] -> ZipList a [getZipList] :: ZipList a -> [a] -- | 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 &&& stdin :: Handle stderr :: Handle -- | Shared memory locations that support atomic memory transactions. data TVar a -- | A monad supporting atomic memory transactions. data STM a -- | 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 mutable variable in the IO monad data IORef a -- | Pretty print a SrcLoc. prettySrcLoc :: SrcLoc -> String -- | Right-to-left monadic fold over the elements of a structure. -- -- Given a structure t with elements (a, b, c, ..., x, -- y), the result of a fold with an operator function f is -- equivalent to: -- --
--   foldrM f z t = do
--       yy <- f y z
--       xx <- f x yy
--       ...
--       bb <- f b cc
--       aa <- f a bb
--       return aa -- Just @return z@ when the structure is empty
--   
-- -- For a Monad m, given two functions f1 :: a -> m b -- and f2 :: b -> m c, their Kleisli composition (f1 -- >=> f2) :: a -> m c is defined by: -- --
--   (f1 >=> f2) a = f1 a >>= f2
--   
-- -- Another way of thinking about foldrM is that it amounts to an -- application to z of a Kleisli composition: -- --
--   foldrM f z t = f y >=> f x >=> ... >=> f b >=> f a $ z
--   
-- -- The monadic effects of foldrM are sequenced from right to -- left, and e.g. folds of infinite lists will diverge. -- -- If at some step the bind operator (>>=) -- short-circuits (as with, e.g., mzero in a MonadPlus), -- the evaluated effects will be from a tail of the element sequence. If -- you want to evaluate the monadic effects in left-to-right order, or -- perhaps be able to short-circuit after an initial sequence of -- elements, you'll need to use foldlM instead. -- -- If the monadic effects don't short-circuit, the outermost application -- of f is to the leftmost element a, so that, ignoring -- effects, the result looks like a right fold: -- --
--   a `f` (b `f` (c `f` (... (x `f` (y `f` z))))).
--   
-- --

Examples

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

Examples

-- -- Basic usage: -- --
--   >>> let f a e = do { print e ; return $ e : a }
--   
--   >>> foldlM f [] [0..3]
--   0
--   1
--   2
--   3
--   [3,2,1,0]
--   
foldlM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | The transpose function transposes the rows and columns of its -- argument. For example, -- --
--   >>> transpose [[1,2,3],[4,5,6]]
--   [[1,4],[2,5],[3,6]]
--   
-- -- If some of the rows are shorter than the following rows, their -- elements are skipped: -- --
--   >>> transpose [[10,11],[20],[],[30,31,32]]
--   [[10,20,30],[11,31],[32]]
--   
transpose :: [[a]] -> [[a]] -- | <math>. The tails function returns all final segments of -- the argument, longest first. For example, -- --
--   >>> tails "abc"
--   ["abc","bc","c",""]
--   
-- -- Note that tails has the following strictness property: -- tails _|_ = _|_ : _|_ tails :: [a] -> [[a]] -- | The subsequences function returns the list of all subsequences -- of the argument. -- --
--   >>> subsequences "abc"
--   ["","a","b","ab","c","ac","bc","abc"]
--   
subsequences :: [a] -> [[a]] -- | Sort a list by comparing the results of a key function applied to each -- element. sortOn f is equivalent to sortBy (comparing -- f), but has the performance advantage of only evaluating -- f once for each element in the input list. This is called the -- decorate-sort-undecorate paradigm, or Schwartzian transform. -- -- Elements are arranged from lowest to highest, keeping duplicates in -- the order they appeared in the input. -- --
--   >>> sortOn fst [(2, "world"), (4, "!"), (1, "Hello")]
--   [(1,"Hello"),(2,"world"),(4,"!")]
--   
sortOn :: Ord b => (a -> b) -> [a] -> [a] -- | The permutations function returns the list of all permutations -- of the argument. -- --
--   >>> permutations "abc"
--   ["abc","bac","cba","bca","cab","acb"]
--   
permutations :: [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 genericTake function is an overloaded version of -- take, which accepts any Integral value as the number of -- elements to take. genericTake :: Integral i => i -> [a] -> [a] -- | The genericSplitAt function is an overloaded version of -- splitAt, which accepts any Integral value as the -- position at which to split. genericSplitAt :: Integral i => i -> [a] -> ([a], [a]) -- | The genericReplicate function is an overloaded version of -- replicate, which accepts any Integral value as the -- number of repetitions to make. genericReplicate :: Integral i => i -> a -> [a] -- | <math>. The genericLength function is an overloaded -- version of length. In particular, instead of returning an -- Int, it returns any type which is an instance of Num. It -- is, however, less efficient than length. -- --
--   >>> genericLength [1, 2, 3] :: Int
--   3
--   
--   >>> genericLength [1, 2, 3] :: Float
--   3.0
--   
genericLength :: Num i => [a] -> i -- | The 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] -- | Maybe monoid returning the rightmost non-Nothing value. -- -- Last a is isomorphic to Dual (First -- a), and thus to Dual (Alt Maybe a) -- --
--   >>> getLast (Last (Just "hello") <> Last Nothing <> Last (Just "world"))
--   Just "world"
--   
newtype Last a Last :: Maybe a -> Last a [getLast] :: Last a -> Maybe a -- | 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"
--   
newtype First a First :: Maybe a -> First a [getFirst] :: First a -> Maybe a -- | Monoid under addition. -- --
--   >>> getSum (Sum 1 <> Sum 2 <> mempty)
--   3
--   
newtype Sum a Sum :: a -> Sum a [getSum] :: Sum a -> a -- | Monoid under multiplication. -- --
--   >>> getProduct (Product 3 <> Product 4 <> mempty)
--   12
--   
newtype Product a Product :: a -> Product a [getProduct] :: Product a -> a -- | The monoid of endomorphisms under composition. -- --
--   >>> let computation = Endo ("Hello, " ++) <> Endo (++ "!")
--   
--   >>> appEndo computation "Haskell"
--   "Hello, Haskell!"
--   
newtype Endo a Endo :: (a -> a) -> Endo a [appEndo] :: Endo a -> a -> a -- | The dual of a Monoid, obtained by swapping the arguments of -- mappend. -- --
--   >>> getDual (mappend (Dual "Hello") (Dual "World"))
--   "WorldHello"
--   
newtype Dual a Dual :: a -> Dual a [getDual] :: Dual a -> a -- | Monoid under <|>. -- --
--   >>> getAlt (Alt (Just 12) <> Alt (Just 24))
--   Just 12
--   
-- --
--   >>> getAlt $ Alt Nothing <> Alt (Just 24)
--   Just 24
--   
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 -- | This is a valid definition of stimes for a Monoid. -- -- Unlike the default definition of stimes, it is defined for 0 -- and so it should be preferred where possible. stimesMonoid :: (Integral b, Monoid a) => b -> a -> a -- | This is a valid definition of stimes for an idempotent -- Semigroup. -- -- When x <> x = x, this definition should be preferred, -- because it works in <math> rather than <math>. stimesIdempotent :: Integral b => b -> a -> a -- | The Down type allows you to reverse sort order conveniently. A -- value of type Down a contains a value of type -- a (represented as Down a). -- -- If a has an Ord instance associated with it -- then comparing two values thus wrapped will give you the opposite of -- their normal sort order. This is particularly useful when sorting in -- generalised list comprehensions, as in: then sortWith by -- Down x. -- --
--   >>> compare True False
--   GT
--   
-- --
--   >>> compare (Down True) (Down False)
--   LT
--   
-- -- If a has a Bounded instance then the wrapped -- instance also respects the reversed ordering by exchanging the values -- of minBound and maxBound. -- --
--   >>> minBound :: Int
--   -9223372036854775808
--   
-- --
--   >>> minBound :: Down Int
--   Down 9223372036854775807
--   
-- -- All other instances of Down a behave as they do for -- a. newtype Down a Down :: a -> Down a [getDown] :: Down a -> a -- | This type represents unknown type-level natural numbers. data SomeNat SomeNat :: Proxy n -> SomeNat -- | Convert an integer into an unknown type-level natural. someNatVal :: Natural -> SomeNat natVal :: forall (n :: Nat) proxy. KnownNat n => proxy n -> Natural -- | 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] -- | 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 -- | See openFile data IOMode ReadMode :: IOMode WriteMode :: IOMode AppendMode :: IOMode ReadWriteMode :: IOMode underflowError :: 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 ratioZeroDenominatorError :: a ratioPrec1 :: Int ratioPrec :: Int overflowError :: a numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a] numericEnumFromThenTo :: (Ord a, Fractional a) => a -> a -> a -> [a] numericEnumFromThen :: Fractional a => a -> a -> [a] numericEnumFrom :: Fractional a => 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 notANumber :: Rational -- | Convert an Int into a Natural, throwing an underflow exception for -- negative values. naturalFromInt :: Int -> Natural integralEnumFromTo :: Integral a => a -> a -> [a] integralEnumFromThenTo :: Integral a => a -> a -> a -> [a] integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a] integralEnumFrom :: (Integral a, Bounded a) => a -> [a] infinity :: Rational divZeroError :: 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 (^^%^^) :: Integral a => Rational -> a -> Rational (^%^) :: Integral a => Rational -> a -> Rational boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a] boundedEnumFrom :: (Enum a, Bounded a) => a -> [a] -- | Case analysis for the Bool type. bool x y p -- evaluates to x when p is False, and evaluates -- to y when p is True. -- -- This is equivalent to if p then y else x; that is, one can -- think of it as an if-then-else construct with its arguments reordered. -- --

Examples

-- -- Basic usage: -- --
--   >>> bool "foo" "bar" True
--   "bar"
--   
--   >>> bool "foo" "bar" False
--   "foo"
--   
-- -- Confirm that bool x y p and if p then y else -- x are equivalent: -- --
--   >>> let p = True; x = "bar"; y = "foo"
--   
--   >>> bool x y p == if p then y else x
--   True
--   
--   >>> let p = False
--   
--   >>> bool x y p == if p then y else x
--   True
--   
bool :: a -> a -> Bool -> a -- | & 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 & -- | 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 <&> -- | 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 $> -- | Swap the components of a pair. swap :: (a, b) -> (b, 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] minInt :: Int maxInt :: Int -- | 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 <**> -- | 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 -- | Extract a list of call-sites from the CallStack. -- -- The list is ordered by most recent call. getCallStack :: CallStack -> [([Char], SrcLoc)] -- | This is a valid definition of stimes for an idempotent -- Monoid. -- -- When mappend x x = x, this definition should be preferred, -- because it works in <math> rather than <math> stimesIdempotentMonoid :: (Integral b, Monoid a) => b -> a -> a -- | The 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 -- | 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 $!! -- | The inverse of ExceptT. runExceptT :: ExceptT e m a -> m (Either e 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 -- | 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 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 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) -- | 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) -- | The (open) type family IntBaseType encodes type-level -- information about the value range of an integral type. -- -- This module also provides type family instances for the standard -- Haskell 2010 integral types (including Foreign.C.Types) as well -- as the Natural type. -- -- Here's a simple example for registering a custom type with the -- Data.IntCast facilities: -- --
--   -- user-implemented unsigned 4-bit integer
--   data Nibble = …
--   
--   -- declare meta-information
--   type instance IntBaseType Nibble = FixedWordTag 4
--   
--   -- user-implemented signed 7-bit integer
--   data MyInt7 = …
--   
--   -- declare meta-information
--   type instance IntBaseType MyInt7 = FixedIntTag 7
--   
-- -- The type-level predicate IsIntSubType provides a partial -- ordering based on the types above. See also intCast. type family IntBaseType a :: IntBaseTypeK -- | 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 -- | Retrieve the first value targeted by a Fold or Traversal -- (or Just the result from a Getter or Lens) into -- the current state. -- --
--   preuse = use . pre
--   
-- --
--   preuse :: MonadState s m => Getter s a     -> m (Maybe a)
--   preuse :: MonadState s m => Fold s a       -> m (Maybe a)
--   preuse :: MonadState s m => Lens' s a      -> m (Maybe a)
--   preuse :: MonadState s m => Iso' s a       -> m (Maybe a)
--   preuse :: MonadState s m => Traversal' s a -> m (Maybe a)
--   
preuse :: MonadState s m => Getting (First a) s a -> m (Maybe a) -- | Retrieve the first value targeted by a Fold or Traversal -- (or Just the result from a Getter or Lens). See -- also firstOf and ^?, which are similar with some subtle -- differences (explained below). -- --
--   listToMaybe . toListpreview folded
--   
-- --
--   preview = view . pre
--   
-- -- Unlike ^?, this function uses a MonadReader to read the -- value to be focused in on. This allows one to pass the value as the -- last argument by using the MonadReader instance for (->) -- s However, it may also be used as part of some deeply nested -- transformer stack. -- -- preview uses a monoidal value to obtain the result. This means -- that it generally has good performance, but can occasionally cause -- space leaks or even stack overflows on some data types. There is -- another function, firstOf, which avoids these issues at the -- cost of a slight constant performance cost and a little less -- flexibility. -- -- It may be helpful to think of preview as having one of the -- following more specialized types: -- --
--   preview :: Getter s a     -> s -> Maybe a
--   preview :: Fold s a       -> s -> Maybe a
--   preview :: Lens' s a      -> s -> Maybe a
--   preview :: Iso' s a       -> s -> Maybe a
--   preview :: Traversal' s a -> s -> Maybe a
--   
-- --
--   preview :: MonadReader s m => Getter s a     -> m (Maybe a)
--   preview :: MonadReader s m => Fold s a       -> m (Maybe a)
--   preview :: MonadReader s m => Lens' s a      -> m (Maybe a)
--   preview :: MonadReader s m => Iso' s a       -> m (Maybe a)
--   preview :: MonadReader s m => Traversal' s a -> m (Maybe a)
--   
preview :: MonadReader s m => Getting (First a) s a -> m (Maybe a) -- | A convenient infix (flipped) version of toListOf. -- --
--   >>> [[1,2],[3]]^..id
--   [[[1,2],[3]]]
--   
--   >>> [[1,2],[3]]^..traverse
--   [[1,2],[3]]
--   
--   >>> [[1,2],[3]]^..traverse.traverse
--   [1,2,3]
--   
-- --
--   >>> (1,2)^..both
--   [1,2]
--   
-- --
--   toList xs ≡ xs ^.. folded
--   (^..) ≡ flip toListOf
--   
-- --
--   (^..) :: s -> Getter s a     -> a :: s -> Fold s a       -> a :: s -> Lens' s a      -> a :: s -> Iso' s a       -> a :: s -> Traversal' s a -> a :: s -> Prism' s a     -> [a]
--   
(^..) :: s -> Getting (Endo [a]) s a -> [a] infixl 8 ^.. -- | Use the target of a Lens, Iso, or Getter in the -- current state, or use a summary of a Fold or Traversal -- that points to a monoidal value. -- --
--   >>> evalState (use _1) (a,b)
--   a
--   
-- --
--   >>> evalState (use _1) ("hello","world")
--   "hello"
--   
-- --
--   use :: MonadState s m             => Getter s a     -> m a
--   use :: (MonadState s m, Monoid r) => Fold s r       -> m r
--   use :: MonadState s m             => Iso' s a       -> m a
--   use :: MonadState s m             => Lens' s a      -> m a
--   use :: (MonadState s m, Monoid r) => Traversal' s r -> m r
--   
use :: MonadState s m => Getting a s a -> m a -- | View the value pointed to by a Getter, Iso or -- Lens or the result of folding over all the results of a -- Fold or Traversal that points at a monoidal value. -- --
--   view . toid
--   
-- --
--   >>> view (to f) a
--   f a
--   
-- --
--   >>> view _2 (1,"hello")
--   "hello"
--   
-- --
--   >>> view (to succ) 5
--   6
--   
-- --
--   >>> view (_2._1) ("hello",("world","!!!"))
--   "world"
--   
-- -- As view is commonly used to access the target of a -- Getter or obtain a monoidal summary of the targets of a -- Fold, It may be useful to think of it as having one of these -- more restricted signatures: -- --
--   view ::             Getter s a     -> s -> a
--   view :: Monoid m => Fold s m       -> s -> m
--   view ::             Iso' s a       -> s -> a
--   view ::             Lens' s a      -> s -> a
--   view :: Monoid m => Traversal' s m -> s -> m
--   
-- -- In a more general setting, such as when working with a Monad -- transformer stack you can use: -- --
--   view :: MonadReader s m             => Getter s a     -> m a
--   view :: (MonadReader s m, Monoid a) => Fold s a       -> m a
--   view :: MonadReader s m             => Iso' s a       -> m a
--   view :: MonadReader s m             => Lens' s a      -> m a
--   view :: (MonadReader s m, Monoid a) => Traversal' s a -> m a
--   
view :: MonadReader s m => Getting a s a -> m a -- | Access the 1st field of a tuple (and possibly change its type). -- --
--   >>> (1,2)^._1
--   1
--   
-- --
--   >>> _1 .~ "hello" $ (1,2)
--   ("hello",2)
--   
-- --
--   >>> (1,2) & _1 .~ "hello"
--   ("hello",2)
--   
-- --
--   >>> _1 putStrLn ("hello","world")
--   hello
--   ((),"world")
--   
-- -- This can also be used on larger tuples as well: -- --
--   >>> (1,2,3,4,5) & _1 +~ 41
--   (42,2,3,4,5)
--   
-- --
--   _1 :: Lens (a,b) (a',b) a a'
--   _1 :: Lens (a,b,c) (a',b,c) a a'
--   _1 :: Lens (a,b,c,d) (a',b,c,d) a a'
--   ...
--   _1 :: Lens (a,b,c,d,e,f,g,h,i) (a',b,c,d,e,f,g,h,i) a a'
--   
_1 :: Field1 s t a b => Lens s t a b -- | Access the 2nd field of a tuple. -- --
--   >>> _2 .~ "hello" $ (1,(),3,4)
--   (1,"hello",3,4)
--   
-- --
--   >>> (1,2,3,4) & _2 *~ 3
--   (1,6,3,4)
--   
-- --
--   >>> _2 print (1,2)
--   2
--   (1,())
--   
-- --
--   anyOf _2 :: (s -> Bool) -> (a, s) -> Bool
--   traverse . _2 :: (Applicative f, Traversable t) => (a -> f b) -> t (s, a) -> f (t (s, b))
--   foldMapOf (traverse . _2) :: (Traversable t, Monoid m) => (s -> m) -> t (b, s) -> m
--   
_2 :: Field2 s t a b => Lens s t a b -- | Access the 3rd field of a tuple. _3 :: Field3 s t a b => Lens s t a b -- | Access the 4th field of a tuple. _4 :: Field4 s t a b => Lens s t a b -- | Access the 5th field of a tuple. _5 :: Field5 s t a b => Lens s t a b -- | Replace the target of a Lens or all of the targets of a -- Setter or Traversal with a constant value. -- -- This is an infix version of set, provided for consistency with -- (.=). -- --
--   f <$ a ≡ mapped .~ f $ a
--   
-- --
--   >>> (a,b,c,d) & _4 .~ e
--   (a,b,c,e)
--   
-- --
--   >>> (42,"world") & _1 .~ "hello"
--   ("hello","world")
--   
-- --
--   >>> (a,b) & both .~ c
--   (c,c)
--   
-- --
--   (.~) :: Setter s t a b    -> b -> s -> t
--   (.~) :: Iso s t a b       -> b -> s -> t
--   (.~) :: Lens s t a b      -> b -> s -> t
--   (.~) :: Traversal s t a b -> b -> s -> t
--   
(.~) :: ASetter s t a b -> b -> s -> t infixr 4 .~ -- | Replace the target of a Lens or all of the targets of a -- Setter or Traversal with a constant value. -- --
--   (<$) ≡ set mapped
--   
-- --
--   >>> set _2 "hello" (1,())
--   (1,"hello")
--   
-- --
--   >>> set mapped () [1,2,3,4]
--   [(),(),(),()]
--   
-- -- Note: Attempting to set a Fold or Getter will -- fail at compile time with an relatively nice error message. -- --
--   set :: Setter s t a b    -> b -> s -> t
--   set :: Iso s t a b       -> b -> s -> t
--   set :: Lens s t a b      -> b -> s -> t
--   set :: Traversal s t a b -> b -> s -> t
--   
set :: ASetter s t a b -> b -> s -> t -- | Modify the target of a Lens or all the targets of a -- Setter or Traversal with a function. -- --
--   fmapover mapped
--   fmapDefaultover traverse
--   sets . overid
--   over . setsid
--   
-- -- Given any valid Setter l, you can also rely on the -- law: -- --
--   over l f . over l g = over l (f . g)
--   
-- -- e.g. -- --
--   >>> over mapped f (over mapped g [a,b,c]) == over mapped (f . g) [a,b,c]
--   True
--   
-- -- Another way to view over is to say that it transforms a -- Setter into a "semantic editor combinator". -- --
--   >>> over mapped f (Just a)
--   Just (f a)
--   
-- --
--   >>> over mapped (*10) [1,2,3]
--   [10,20,30]
--   
-- --
--   >>> over _1 f (a,b)
--   (f a,b)
--   
-- --
--   >>> over _1 show (10,20)
--   ("10",20)
--   
-- --
--   over :: Setter s t a b -> (a -> b) -> s -> t
--   over :: ASetter s t a b -> (a -> b) -> s -> t
--   
over :: ASetter s t a b -> (a -> b) -> s -> t -- | A Lens is actually a lens family as described in -- http://comonad.com/reader/2012/mirrored-lenses/. -- -- With great power comes great responsibility and a Lens is -- subject to the three common sense Lens laws: -- -- 1) You get back what you put in: -- --
--   view l (set l v s)  ≡ v
--   
-- -- 2) Putting back what you got doesn't change anything: -- --
--   set l (view l s) s  ≡ s
--   
-- -- 3) Setting twice is the same as setting once: -- --
--   set l v' (set l v s) ≡ set l v' s
--   
-- -- These laws are strong enough that the 4 type parameters of a -- Lens cannot vary fully independently. For more on how they -- interact, read the "Why is it a Lens Family?" section of -- http://comonad.com/reader/2012/mirrored-lenses/. -- -- There are some emergent properties of these laws: -- -- 1) set l s must be injective for every s This -- is a consequence of law #1 -- -- 2) set l must be surjective, because of law #2, which -- indicates that it is possible to obtain any v from some -- s such that set s v = s -- -- 3) Given just the first two laws you can prove a weaker form of law #3 -- where the values v that you are setting match: -- --
--   set l v (set l v s) ≡ set l v s
--   
-- -- Every Lens can be used directly as a Setter or -- Traversal. -- -- You can also use a Lens for Getting as if it were a -- Fold or Getter. -- -- Since every Lens is a valid Traversal, the -- Traversal laws are required of any Lens you create: -- --
--   l purepure
--   fmap (l f) . l g ≡ getCompose . l (Compose . fmap f . g)
--   
-- --
--   type Lens s t a b = forall f. Functor f => LensLike f s t a b
--   
type Lens s t a b = forall (f :: Type -> Type). Functor f => a -> f b -> s -> f t -- |
--   type Lens' = Simple Lens
--   
type Lens' s a = Lens s s a a -- | A Traversal can be used directly as a Setter or a -- Fold (but not as a Lens) and provides the ability to -- both read and update multiple fields, subject to some relatively weak -- Traversal laws. -- -- These have also been known as multilenses, but they have the signature -- and spirit of -- --
--   traverse :: Traversable f => Traversal (f a) (f b) a b
--   
-- -- and the more evocative name suggests their application. -- -- Most of the time the Traversal you will want to use is just -- traverse, but you can also pass any Lens or Iso -- as a Traversal, and composition of a Traversal (or -- Lens or Iso) with a Traversal (or Lens or -- Iso) using (.) forms a valid Traversal. -- -- The laws for a Traversal t follow from the laws for -- Traversable as stated in "The Essence of the Iterator Pattern". -- --
--   t purepure
--   fmap (t f) . t g ≡ getCompose . t (Compose . fmap f . g)
--   
-- -- One consequence of this requirement is that a Traversal needs -- to leave the same number of elements as a candidate for subsequent -- Traversal that it started with. Another testament to the -- strength of these laws is that the caveat expressed in section 5.5 of -- the "Essence of the Iterator Pattern" about exotic Traversable -- instances that traverse the same entry multiple times was -- actually already ruled out by the second law in that same paper! type Traversal s t a b = forall (f :: Type -> Type). Applicative f => a -> f b -> s -> f t -- |
--   type Traversal' = Simple Traversal
--   
type Traversal' s a = Traversal s s a a -- | Infix application. -- --
--   f :: Either String $ Maybe Int
--   =
--   f :: Either String (Maybe Int)
--   
type (f :: k1 -> k) $ (a :: k1) = f a infixr 2 $ -- | undefined that leaves a warning in code on every usage. undefined :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => a -- | error that takes Text as an argument. error :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => Text -> a -- | 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 -- | 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]) -- | Statically safe converter between Integral types, which is just -- intCast under the hood. -- -- It is used to turn the value of type a into the value of type -- b such that a is subtype of b. It is needed -- to prevent silent unsafe conversions. -- --
--   >>> fromIntegral @Int @Word 1
--   ...
--   ... error:
--   ... Can not safely cast 'Int' to 'Word':
--   ... 'Int' is not a subtype of 'Word'
--   ...
--   
--   >>> fromIntegral @Word @Natural 1
--   1
--   
fromIntegral :: (Integral a, Integral b, CheckIntSubType a b) => a -> b -- | Similar to unsafe converter, but with the use of monadic -- fail and returning the result wrapped in a monad. unsafeM :: (MonadFail m, Buildable a) => Either a b -> m b -- | Unsafe converter from Either, which uses buildable Left -- to throw an exception with error. -- -- It is primarily needed for making unsafe counter-parts of safe -- functions. In particular, for replacing unsafeFName x = either -- (error . pretty) id constructors and converters, which produce -- many similar functions at the call site, with unsafe . fName $ -- x. unsafe :: (HasCallStack, Buildable a) => Either a b -> b -- | A version of show that requires the value to have a -- human-readable Show instance. show :: forall b a. (PrettyShow a, Show a, IsString b) => a -> b -- | An open type family for types having a human-readable Show -- representation. The kind is Constraint in case we need to -- further constrain the instance, and also for convenience to avoid -- explicitly writing ~ 'True everywhere. type family PrettyShow a -- | Statically safe converter between Integral types checking for -- overflow/underflow. Returns Right value if conversion does -- not produce overflow/underflow and Left ArithException with -- corresponding ArithException -- (Overflow/Underflow) otherwise. -- -- Note the function is strict in its argument. -- --
--   >>> fromIntegralNoOverflow @Int @Word 123
--   Right 123
--   
--   >>> fromIntegralNoOverflow @Int @Word (-123)
--   Left arithmetic underflow
--   
--   >>> fromIntegralNoOverflow @Int @Integer (-123)
--   Right (-123)
--   
--   >>> fromIntegralNoOverflow @Int @Natural (-123)
--   Left arithmetic underflow
--   
--   >>> fromIntegralNoOverflow @Int @Int8 127
--   Right 127
--   
--   >>> fromIntegralNoOverflow @Int @Int8 128
--   Left arithmetic overflow
--   
fromIntegralNoOverflow :: (Integral a, Integral b) => a -> Either ArithException b -- | Runtime-safe converter between Integral types, which is just -- fromIntegral under the hood. -- -- It is needed to semantically distinguish usages, where overflow is -- intended, from those that have to fail on overflow. E.g. Int8 -- -> Word8 with intended bits reinterpretation from lossy -- Integer -> Int. -- --
--   >>> fromIntegralOverflowing @Int8 @Word8 (-1)
--   255
--   
--   >>> fromIntegralOverflowing @Natural @Int8 450
--   -62
--   
-- -- Please note that like fromIntegral from base, this -- will throw on some conversions! -- --
--   >>> fromIntegralOverflowing @Int @Natural (-1)
--   *** Exception: arithmetic underflow
--   
-- -- See fromIntegralNoOverflow for an alternative that doesn't -- throw. fromIntegralOverflowing :: (Integral a, Num b) => a -> b -- | Statically safe converter between Integral and RealFrac -- types. Could be applied to cast common types like Float, -- Double and Scientific. -- -- It is primarily needed to replace usages of fromIntegral, which -- are safe actually as integral numbers are being casted to fractional -- ones. fromIntegralToRealFrac :: (Integral a, RealFrac b, CheckIntSubType a Integer) => a -> b -- | Statically safe converter between Integral types, which is just -- intCastMaybe under the hood. Unlike fromIntegral accept -- any a and b. Return Just value if -- conversion is possible at runtime and Nothing otherwise. fromIntegralMaybe :: (Integral a, Integral b, Bits a, Bits b) => a -> Maybe b -- | Constraint synonym equivalent to IsIntSubType a b ~ -- 'True, but with better error messages type CheckIntSubType a b = (CheckIntSubTypeErrors a b IsIntSubType a b, IsIntSubType a b ~ 'True) -- | A version of all that works on NonEmpty, thus doesn't -- require BooleanMonoid instance. -- --
--   >>> all1 (\x -> if x > 50 then Yay else Nay) $ 100 :| replicate 10 51
--   Yay
--   
all1 :: Boolean b => (a -> b) -> NonEmpty a -> b -- | A version of any that works on NonEmpty, thus doesn't -- require BooleanMonoid instance. -- --
--   >>> any1 (\x -> if x > 50 then Yay else Nay) $ 50 :| replicate 10 0
--   Nay
--   
any1 :: Boolean b => (a -> b) -> NonEmpty a -> b -- | Generalized all. -- --
--   >>> all (\x -> if x > 50 then Yay else Nay) [1..100]
--   Nay
--   
all :: (Container c, BooleanMonoid b) => (Element c -> b) -> c -> b -- | Generalized any. -- --
--   >>> any (\x -> if x > 50 then Yay else Nay) [1..100]
--   Yay
--   
any :: (Container c, BooleanMonoid b) => (Element c -> b) -> c -> b -- | A version of and that works on NonEmpty, thus doesn't -- require BooleanMonoid instance. -- --
--   >>> and1 $ Yay :| [Nay]
--   Nay
--   
and1 :: Boolean a => NonEmpty a -> a -- | A version of or that works on NonEmpty, thus doesn't -- require BooleanMonoid instance. -- --
--   >>> or1 $ Yay :| [Nay]
--   Yay
--   
or1 :: Boolean a => NonEmpty a -> a -- | Generalized boolean operators. -- -- This is useful for defining things that behave like booleans, e.g. -- predicates, or EDSL for predicates. -- --
--   >>> Yay && Nay
--   Nay
--   
--   >>> and1 $ Yay :| replicate 9 Yay
--   Yay
--   
-- -- There are also instances for these types lifted into IO and -- (->) a: -- --
--   >>> (const Yay) && (const Nay) $ ()
--   Nay
--   
--   >>> (const Yay) || (const Nay) $ ()
--   Yay
--   
class Boolean a -- | Generalized True and False. -- -- This is useful to complete the isomorphism between regular and -- generalized booleans. It's a separate class because not all -- boolean-like things form a monoid. -- --
--   >>> or $ replicate 10 Nay
--   Nay
--   
class Boolean a => BooleanMonoid a false :: BooleanMonoid a => a true :: BooleanMonoid a => a -- | A generalized version of All monoid wrapper. -- --
--   >>> All Nay <> All Nay
--   All {getAll = Nay}
--   
--   >>> All Yay <> All Nay
--   All {getAll = Nay}
--   
--   >>> All Yay <> All Yay
--   All {getAll = Yay}
--   
newtype All a All :: a -> All a [getAll] :: All a -> a -- | A generalized version of Any monoid wrapper. -- --
--   >>> Any Nay <> Any Nay
--   Any {getAny = Nay}
--   
--   >>> Any Yay <> Any Nay
--   Any {getAny = Yay}
--   
--   >>> Any Yay <> Any Yay
--   Any {getAny = Yay}
--   
newtype Any a Any :: a -> Any a [getAny] :: Any a -> a -- | A newtype for deriving a Boolean instance for any -- Applicative type constructor using DerivingVia. newtype ApplicativeBoolean (f :: k -> Type) (bool :: k) ApplicativeBoolean :: f bool -> ApplicativeBoolean (f :: k -> Type) (bool :: k) -- | Shorter alias for pure (). -- --
--   >>> pass :: Maybe ()
--   Just ()
--   
pass :: Applicative f => f () -- | Similar to some, but reflects in types that a non-empty list is -- returned. someNE :: Alternative f => f a -> f (NonEmpty a) -- | 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 $! -- | 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 -- | 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 <<$>> -- | Lifted to MonadIO version of newEmptyMVar. newEmptyMVar :: MonadIO m => m (MVar a) -- | Lifted to MonadIO version of newMVar. newMVar :: MonadIO m => a -> m (MVar a) -- | Lifted to MonadIO version of putMVar. putMVar :: MonadIO m => MVar a -> a -> m () -- | Lifted to MonadIO version of readMVar. readMVar :: 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 takeMVar. takeMVar :: MonadIO m => MVar a -> m a -- | Lifted to MonadIO version of tryPutMVar. tryPutMVar :: MonadIO m => MVar a -> a -> m Bool -- | Lifted to MonadIO version of tryReadMVar. tryReadMVar :: MonadIO m => MVar a -> m (Maybe a) -- | Lifted to MonadIO version of tryTakeMVar. tryTakeMVar :: MonadIO m => MVar a -> m (Maybe a) -- | Lifted to MonadIO version of atomically. atomically :: MonadIO m => STM a -> m a -- | Lifted to MonadIO version of newTVarIO. newTVarIO :: MonadIO m => a -> m (TVar a) -- | Lifted to MonadIO version of readTVarIO. readTVarIO :: MonadIO m => TVar a -> m a -- | Like modifyMVar, but modification is specified as a -- State computation. -- -- This method is strict in produced s value. updateMVar' :: MonadIO m => MVar s -> StateT s IO a -> m a -- | Like 'modifyTVar'', but modification is specified as a State -- monad. updateTVar' :: TVar s -> StateT s STM a -> STM a -- | Lifted version of exitWith. exitWith :: MonadIO m => ExitCode -> m a -- | Lifted version of exitFailure. exitFailure :: MonadIO m => m a -- | Lifted version of exitSuccess. exitSuccess :: MonadIO m => m a -- | 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 appendFile. appendFile :: MonadIO m => FilePath -> Text -> m () -- | Lifted version of getLine. getLine :: MonadIO m => m Text -- | Lifted version of openFile. -- -- See also withFile for more information. openFile :: MonadIO m => FilePath -> IOMode -> m Handle -- | Close a file handle -- -- See also withFile for more information. hClose :: MonadIO m => Handle -> m () -- | 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 -- | Lifted version of newIORef. newIORef :: MonadIO m => a -> m (IORef a) -- | Lifted version of readIORef. readIORef :: MonadIO m => IORef a -> m a -- | Lifted version of writeIORef. writeIORef :: MonadIO m => IORef a -> a -> m () -- | 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 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 atomicWriteIORef. atomicWriteIORef :: MonadIO m => IORef a -> a -> 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 () -- | Monadic version of whenJust. whenJustM :: Monad m => m (Maybe a) -> (a -> m ()) -> m () -- | 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 -- | 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 () -- | Monadic version of whenNothing. whenNothingM :: Monad m => m (Maybe a) -> m a -> m a -- | Monadic version of whenNothingM_. whenNothingM_ :: Monad m => m (Maybe a) -> m () -> m () -- | 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 -- | 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 -- | Maps left part of Either to Maybe. -- --
--   >>> leftToMaybe (Left True)
--   Just True
--   
--   >>> leftToMaybe (Right "aba")
--   Nothing
--   
leftToMaybe :: Either l r -> Maybe l -- | Maps right part of Either to Maybe. -- --
--   >>> rightToMaybe (Left True)
--   Nothing
--   
--   >>> rightToMaybe (Right "aba")
--   Just "aba"
--   
rightToMaybe :: Either l r -> Maybe 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 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 -- | Monadic version of whenLeft. whenLeftM :: Monad m => m (Either l r) -> (l -> m ()) -> m () -- | Monadic version of whenRight. whenRightM :: Monad m => m (Either l r) -> (r -> m ()) -> m () -- | Shorter and more readable alias for flip runReaderT. usingReaderT :: r -> ReaderT r m a -> m a -- | Shorter and more readable alias for flip runReader. usingReader :: r -> Reader r a -> a -- | Shorter and more readable alias for flip runStateT. usingStateT :: s -> StateT s m a -> m (a, s) -- | Shorter and more readable alias for flip runState. usingState :: s -> State s a -> (a, s) -- | 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 -- | 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 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 execState. It's not shorter but sometimes more -- readable. Done by analogy with using* functions family. executingState :: s -> State s a -> s -- | Lift a Maybe to the MaybeT monad hoistMaybe :: forall (m :: Type -> Type) a. Applicative m => Maybe a -> MaybeT m a -- | Lift a Either to the ExceptT monad hoistEither :: forall (m :: Type -> Type) e a. Applicative m => Either e a -> ExceptT e m a -- | Extracts Monoid value from Maybe returning mempty -- if Nothing. -- --
--   >>> maybeToMonoid (Just [1,2,3] :: Maybe [Int])
--   [1,2,3]
--   
--   >>> maybeToMonoid (Nothing :: Maybe [Int])
--   []
--   
maybeToMonoid :: Monoid m => Maybe m -> m -- | 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 type family OneItem x -- | 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 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 notElem :: Container t => Element t -> t -> Bool find :: Container t => (Element t -> Bool) -> t -> Maybe (Element t) safeHead :: Container t => t -> Maybe (Element t) safeMaximum :: Container t => t -> Maybe (Element t) safeMinimum :: Container t => t -> Maybe (Element t) safeFoldr1 :: Container t => (Element t -> Element t -> Element t) -> t -> Maybe (Element t) safeFoldl1 :: Container t => (Element t -> Element t -> Element t) -> t -> Maybe (Element 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 -- | Type class for data types that can be constructed from a list. class FromList l where { type family ListElement l; type family FromListC l; type ListElement l = Item l; type FromListC l = (); } -- | Make a value from list. -- -- For simple types like '[]' and Set: -- --
--   toList . fromList ≡ id
--   fromList . toList ≡ id
--   
--   
-- -- For map-like types: -- --
--   toPairs . fromList ≡ id
--   fromList . toPairs ≡ id
--   
--   
fromList :: FromList l => [ListElement l] -> l type family ListElement l type family FromListC l -- | 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] -- | 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 -- | 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 -- | 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 -- | Constrained to Container version of traverse_. -- --
--   >>> traverse_ putTextLn ["foo", "bar"]
--   foo
--   bar
--   
traverse_ :: (Container t, Applicative f) => (Element t -> f b) -> t -> f () -- | 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 mapM_. -- --
--   >>> mapM_ print [True, False]
--   True
--   False
--   
mapM_ :: (Container t, Monad m) => (Element t -> m b) -> t -> m () -- | 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 sequenceA_. -- --
--   >>> sequenceA_ [putTextLn "foo", print True]
--   foo
--   True
--   
sequenceA_ :: (Container t, Applicative f, Element t ~ f a) => t -> f () -- | 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 asum. -- --
--   >>> asum [Nothing, Just [False, True], Nothing, Just [True]]
--   Just [False,True]
--   
asum :: (Container t, Alternative f, Element t ~ f a) => t -> f a -- | 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 -- | 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 -- | 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 -- | 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 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 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 -- | 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]) -- | 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 () -- | Monadic version of whenNotNull. whenNotNullM :: Monad m => m [a] -> (NonEmpty a -> m ()) -> m () -- | A variant of foldl that has no base case, and thus may only -- be applied to NonEmpty. -- --
--   >>> foldl1 (+) (1 :| [2,3,4,5])
--   15
--   
foldl1 :: (a -> a -> a) -> NonEmpty a -> a -- | A variant of foldr that has no base case, and thus may only -- be applied to NonEmpty. -- --
--   >>> foldr1 (+) (1 :| [2,3,4,5])
--   15
--   
foldr1 :: (a -> a -> a) -> NonEmpty a -> a -- | The least element of a NonEmpty with respect to the given -- comparison function. minimumBy :: (a -> a -> Ordering) -> NonEmpty a -> a -- | The least element of a NonEmpty. -- --
--   >>> minimum (1 :| [2,3,4,5])
--   1
--   
minimum :: Ord a => NonEmpty a -> a -- | The largest element of a NonEmpty with respect to the given -- comparison function. maximumBy :: (a -> a -> Ordering) -> NonEmpty a -> a -- | The largest element of a NonEmpty. -- --
--   >>> maximum (1 :| [2,3,4,5])
--   5
--   
maximum :: Ord a => NonEmpty a -> a -- | 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 -- | 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 -- | Generate a pure value which, when forced, will synchronously throw the -- exception wrapped into Bug data type. bug :: (HasCallStack, Exception e) => e -> a -- | Throws error for Maybe if Nothing is given. Operates -- over MonadError. note :: MonadError e m => e -> Maybe a -> m a -- | Lifted alias for evaluate with clearer name. evaluateWHNF :: MonadIO m => a -> m a -- | Like evaluateWNHF but discards value. evaluateWHNF_ :: MonadIO m => a -> m () -- | Alias for evaluateWHNF . force with clearer name. evaluateNF :: (NFData a, MonadIO m) => a -> m a -- | Alias for evaluateWHNF . rnf. Similar to evaluateNF -- but discards resulting value. evaluateNF_ :: (NFData a, MonadIO m) => a -> 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 () -- | 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 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 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 () -- | 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] -- | 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 ordNub but also sorts a list. -- --
--   >>> sortNub [3, 3, 3, 2, 2, -1, 1]
--   [-1,1,2,3]
--   
sortNub :: Ord a => [a] -> [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] -- | Support class to overload writing of string like values. class Print a -- | Write a string like value a to a supplied Handle. hPutStr :: (Print a, MonadIO m) => Handle -> 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 to stdout/. putStr :: (Print a, MonadIO m) => a -> m () -- | Write a string like value to stdout appending a newline -- character. putStrLn :: (Print a, MonadIO m) => a -> m () -- | Lifted version of print. print :: forall a m. (MonadIO m, Show a) => a -> m () -- | Lifted version of hPrint hPrint :: (MonadIO m, Show a) => Handle -> a -> m () -- | Specialized to Text version of putStr or forcing type -- inference. putText :: 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. putLText :: MonadIO m => Text -> m () -- | Specialized to Text version of putStrLn or forcing type -- inference. putLTextLn :: MonadIO m => Text -> m () -- | Similar to undefined but data type. data Undefined Undefined :: Undefined -- | Version of trace that leaves a warning and takes Text. trace :: Text -> a -> a -- | Version of traceShow that leaves a warning. traceShow :: Show a => a -> b -> b -- | Version of traceShowId that leaves a warning. traceShowId :: Show a => 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. Useful to tag -- printed data, for instance: -- --
--   traceShowIdWith ("My data: ", ) (veryLargeExpression)
--   
traceShowIdWith :: Show s => (a -> s) -> a -> a -- | Version of traceShowM that leaves a warning. traceShowM :: (Show a, Monad m) => a -> m () -- | Version of traceM that leaves a warning and takes Text. traceM :: Monad m => Text -> m () -- | Version of traceId that leaves a warning. traceId :: Text -> Text -- | Type class for converting other strings to String. class ToString a toString :: ToString a => a -> String -- | Type class for converting other strings to Text. class ToLText a toLText :: ToLText a => a -> Text -- | Type class for converting other strings to Text. class ToText a toText :: ToText a => a -> Text -- | 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 synonym for ByteString. type LByteString = ByteString -- | Type synonym for Text. type LText = Text -- | 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 -- | 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 -- | 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 ... -- | 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 -- | Replace an invalid input byte with the Unicode replacement character -- U+FFFD. lenientDecode :: OnDecodeError -- | Throw a UnicodeException if decoding fails. strictDecode :: OnDecodeError -- | A handler for a decoding error. type OnDecodeError = OnError Word8 Char -- | Function type for handling a coding error. It is supplied with two -- inputs: -- -- -- -- If the handler returns a value wrapped with Just, that value -- will be used in the output as the replacement for the invalid input. -- If it returns Nothing, no value will be used in the output. -- -- Should the handler need to abort processing, it should use -- error or throw an exception (preferably a -- UnicodeException). It may use the description provided to -- construct a more helpful error report. type OnError a b = String -> Maybe a -> Maybe b -- | An exception type for representing Unicode encoding errors. data UnicodeException -- | 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 -- | O(n) Breaks a Text up into a list of Texts at -- newline Chars. The resulting strings do not contain newlines. lines :: Text -> [Text] -- | O(n) Joins lines, after appending a terminating newline to -- each. unlines :: [Text] -> Text -- | O(n) Joins words using single space characters. unwords :: [Text] -> Text -- | O(n) Breaks a Text up into a list of words, delimited by -- Chars representing white space. words :: Text -> [Text] -- | O(c) Convert a strict Text into a lazy Text. fromStrict :: Text -> Text -- | Strict version of modifyTVar. modifyTVar' :: TVar a -> (a -> a) -> STM () -- | Synonym for throw throwM :: (MonadThrow m, Exception e) => e -> m a -- | Same as upstream catch, but will not catch asynchronous -- exceptions catch :: (MonadCatch m, Exception e) => m a -> (e -> m a) -> m a -- | catch specialized to catch all synchronous exception catchAny :: MonadCatch m => m a -> (SomeException -> m a) -> m a -- | Flipped version of catchAny handleAny :: MonadCatch m => (SomeException -> m a) -> m a -> m a -- | Same as upstream try, but will not catch asynchronous -- exceptions try :: (MonadCatch m, Exception e) => m a -> m (Either e a) -- | try specialized to catch all synchronous exceptions tryAny :: MonadCatch m => m a -> m (Either SomeException a) -- | Async safe version of onException onException :: MonadMask m => m a -> m b -> m a -- | Async safe version of bracket bracket :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c -- | Async safe version of bracket_ bracket_ :: MonadMask m => m a -> m b -> m c -> m c -- | Async safe version of finally finally :: MonadMask m => m a -> m b -> m a -- | Async safe version of bracketOnError bracketOnError :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c -- | withState f m executes action m on a state -- modified by applying f. -- -- withState :: (s -> s) -> State s a -> State s 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 state, discarding the final value. -- -- execStateT :: Monad m => StateT s m a -> s -> m s -- | Evaluate a state computation with the given initial state and return -- the final state, discarding the final value. -- -- execState :: State s a -> s -> s -- | Evaluate a state computation with the given initial state and return -- the final 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 value, discarding the final state. -- -- evalState :: State s a -> s -> a -- | Runs a Reader and extracts the final value from it. (The -- inverse of reader.) runReader :: Reader r a -> r -> a -- | A variant of modify in which the computation is strict in the -- new state. modify' :: MonadState s m => (s -> s) -> m () -- | SomeIndigoState existential and utilities to work with it. module Indigo.Common.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.Common.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), HasDupableGetters (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 (Morley.Michelson.Typed.Haskell.Instr.Product.InstrSetFieldC dt fname, Morley.Michelson.Typed.Haskell.Instr.Product.InstrGetFieldC dt fname, Morley.Michelson.Typed.Haskell.Instr.Product.GetFieldType dt fname GHC.Types.~ ftype, Indigo.Common.Field.AccessFieldC dt fname, GHC.TypeLits.KnownSymbol fname, Lorentz.Constraints.Scopes.KnownValue ftype, Lorentz.Constraints.Scopes.KnownValue dt) => Indigo.Common.Field.HasField dt fname ftype -- | Expr data type and its generalizations module Indigo.Common.Expr 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 r, KnownValue r) => Expr n -> Expr m -> Expr r [Sub] :: (ArithOpHs Sub n m r, KnownValue r) => Expr n -> Expr m -> Expr r [Mul] :: (ArithOpHs Mul n m r, KnownValue r) => Expr n -> Expr m -> Expr r [Div] :: (KnownValue ratio, ArithOpHs EDiv n m (Maybe (ratio, reminder))) => Expr n -> Expr m -> Proxy reminder -> Expr ratio [Mod] :: (KnownValue reminder, ArithOpHs EDiv n m (Maybe (ratio, reminder))) => Expr n -> Expr m -> Proxy ratio -> Expr reminder [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 r, KnownValue r) => Expr n -> Expr m -> Expr r [Lsr] :: (ArithOpHs Lsr n m r, KnownValue r) => Expr n -> Expr m -> Expr r [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 r, KnownValue r) => Expr n -> Expr m -> Expr r [Xor] :: (ArithOpHs Xor n m r, KnownValue r) => Expr n -> Expr m -> Expr r [And] :: (ArithOpHs And n m r, KnownValue r) => Expr n -> Expr m -> Expr r [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, Dupable key, IsError err, Buildable 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), RecordToList (ConstructorFieldTypes dt), KnownValue dt) => Proxy dt -> Rec Expr (ConstructorFieldTypes dt) -> Expr dt [ConstructWithoutNamed] :: ComplexObjectC dt => Proxy 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 (Packed a) [Unpack] :: NiceUnpackedValue a => Expr (Packed a) -> Expr (Maybe a) [PackRaw] :: NicePackedValue a => Expr a -> Expr ByteString [UnpackRaw] :: 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, IsoValue (ContractRef p), ToTAddress p vd addr, ToT addr ~ ToT Address) => Proxy vd -> Expr addr -> Expr (Maybe (ContractRef p)) [Self] :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p, IsoValue (ContractRef p), IsNotInView) => Expr (ContractRef p) [SelfAddress] :: Expr Address [ContractAddress] :: Expr (ContractRef p) -> Expr Address [ContractCallingUnsafe] :: (NiceParameter arg, IsoValue (ContractRef arg)) => EpName -> Expr Address -> Expr (Maybe (ContractRef arg)) [RunFutureContract] :: (NiceParameter p, IsoValue (ContractRef p)) => Expr (FutureContract p) -> Expr (Maybe (ContractRef p)) [ImplicitAccount] :: Expr KeyHash -> Expr (ContractRef ()) [ConvertEpAddressToContract] :: (NiceParameter p, IsoValue (ContractRef 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] :: BytesLike bs => Expr PublicKey -> Expr (TSignature bs) -> Expr bs -> Expr Bool [Sha256] :: BytesLike bs => Expr bs -> Expr (Hash Sha256 bs) [Sha512] :: BytesLike bs => Expr bs -> Expr (Hash Sha512 bs) [Blake2b] :: BytesLike bs => Expr bs -> Expr (Hash Blake2b bs) [Sha3] :: BytesLike bs => Expr bs -> Expr (Hash Sha3 bs) [Keccak] :: BytesLike bs => Expr bs -> Expr (Hash Keccak bs) [HashKey] :: Expr PublicKey -> Expr KeyHash [ChainId] :: Expr ChainId [Level] :: Expr Natural [Now] :: Expr Timestamp [Amount] :: Expr Mutez [Balance] :: Expr Mutez [Sender] :: Expr Address [VotingPower] :: Expr KeyHash -> Expr Natural [TotalVotingPower] :: Expr Natural [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 r = (exN :~> n, exM :~> m, ArithOpHs a n m r, KnownValue r) 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 ratio reminder = (exN :~> n, exM :~> m, KnownValue ratio, ArithOpHs EDiv n m (Maybe (ratio, reminder))) type IsModExpr exN exM n m ratio reminder = (exN :~> n, exM :~> m, KnownValue reminder, ArithOpHs EDiv n m (Maybe (ratio, reminder))) 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.Common.Expr.ToExpr' (Indigo.Common.Expr.Decide x) x => Indigo.Common.Expr.ToExpr x instance Lorentz.Constraints.Scopes.KnownValue a => Indigo.Common.Expr.ToExpr' 'Indigo.Common.Expr.VarD (Indigo.Common.Var.Var a) instance Lorentz.Constraints.Scopes.NiceConstant a => Indigo.Common.Expr.ToExpr' 'Indigo.Common.Expr.ValD a instance Indigo.Common.Expr.ToExpr' 'Indigo.Common.Expr.ObjManD (Indigo.Common.Expr.ObjectManipulation a) instance Indigo.Common.Expr.ToExpr' 'Indigo.Common.Expr.ExprD (Indigo.Common.Expr.Expr a) instance Formatting.Buildable.Buildable (Indigo.Common.Expr.Expr a) instance Formatting.Buildable.Buildable (Indigo.Common.Expr.ObjectManipulation a) -- | 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.Frontend.Expr constExpr :: forall a. 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 r => exN -> exM -> Expr r sub :: IsArithExpr exN exM Sub n m r => exN -> exM -> Expr r mul :: IsArithExpr exN exM Mul n m r => exN -> exM -> Expr r div :: forall reminder exN exM n m ratio. IsDivExpr exN exM n m ratio reminder => exN -> exM -> Expr ratio mod :: forall ratio exN exM n m reminder. IsModExpr exN exM n m ratio reminder => exN -> exM -> Expr reminder neg :: IsUnaryArithExpr exN Neg n => exN -> Expr (UnaryArithResHs Neg n) abs :: IsUnaryArithExpr exN Abs n => exN -> Expr (UnaryArithResHs Abs n) even :: (ParityExpr n m, ArithOpHs EDiv n m r, exN :~> n) => exN -> Expr Bool odd :: (ParityExpr n m, ArithOpHs EDiv n m r, exN :~> n) => exN -> Expr Bool (+) :: IsArithExpr exN exM Add n m r => exN -> exM -> Expr r infixl 6 + (-) :: IsArithExpr exN exM Sub n m r => exN -> exM -> Expr r infixl 6 - (*) :: IsArithExpr exN exM Mul n m r => exN -> exM -> Expr r infixl 7 * (/) :: forall reminder exN exM n m ratio. IsDivExpr exN exM n m ratio reminder => exN -> exM -> Expr ratio infixl 7 / (%) :: forall ratio exN exM n m reminder. IsModExpr exN exM n m ratio reminder => exN -> exM -> Expr reminder 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 r => exN -> exM -> Expr r lsr :: IsArithExpr exN exM Lsr n m r => exN -> exM -> Expr r and :: IsArithExpr exN exM And n m r => exN -> exM -> Expr r or :: IsArithExpr exN exM Or n m r => exN -> exM -> Expr r xor :: IsArithExpr exN exM Xor n m r => exN -> exM -> Expr r not :: IsUnaryArithExpr exN Not n => exN -> Expr (UnaryArithResHs Not n) (<<<) :: IsArithExpr exN exM Lsl n m r => exN -> exM -> Expr r infixl 8 <<< (>>>) :: IsArithExpr exN exM Lsr n m r => exN -> exM -> Expr r infixl 8 >>> (&&) :: IsArithExpr exN exM And n m r => exN -> exM -> Expr r infixr 3 && (||) :: IsArithExpr exN exM Or n m r => exN -> exM -> Expr r infixr 2 || (^) :: IsArithExpr exN exM Xor n m r => exN -> exM -> Expr r infixr 2 ^ pack :: (ex :~> a, NicePackedValue a) => ex -> Expr (Packed a) unpack :: (NiceUnpackedValue a, exb :~> Packed a) => exb -> Expr (Maybe a) packRaw :: (ex :~> a, NicePackedValue a) => ex -> Expr ByteString unpackRaw :: (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, Dupable key, IsError err, Buildable 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, Dupable key, IsError err, Buildable 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), RecordToList (ConstructorFieldTypes dt), fields ~ Rec Expr (ConstructorFieldTypes dt), RecFromTuple fields) => IsoRecTuple fields -> Expr dt constructRec :: (InstrConstructC dt, RMap (ConstructorFieldTypes dt), RecordToList (ConstructorFieldTypes dt), KnownValue dt) => Rec Expr (ConstructorFieldTypes dt) -> Expr dt contract :: forall p vd addr exAddr. (NiceParameterFull p, NoExplicitDefaultEntrypoint p, IsoValue (ContractRef p), ToTAddress p vd addr, ToT addr ~ ToT Address, exAddr :~> addr) => exAddr -> Expr (Maybe (ContractRef p)) self :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p, IsoValue (ContractRef p), IsNotInView) => Expr (ContractRef p) selfAddress :: Expr Address contractAddress :: exc :~> ContractRef p => exc -> Expr Address contractCallingUnsafe :: (NiceParameter arg, IsoValue (ContractRef arg), exAddr :~> Address) => EpName -> exAddr -> Expr (Maybe (ContractRef arg)) contractCallingString :: (NiceParameter arg, IsoValue (ContractRef arg), exAddr :~> Address) => MText -> exAddr -> Expr (Maybe (ContractRef arg)) runFutureContract :: (NiceParameter p, IsoValue (ContractRef p), conExpr :~> FutureContract p) => conExpr -> Expr (Maybe (ContractRef p)) implicitAccount :: exkh :~> KeyHash => exkh -> Expr (ContractRef ()) convertEpAddressToContract :: (NiceParameter p, IsoValue (ContractRef 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 :~> bs, BytesLike bs) => hashExpr -> Expr (Hash Blake2b bs) sha256 :: (hashExpr :~> bs, BytesLike bs) => hashExpr -> Expr (Hash Sha256 bs) sha512 :: (hashExpr :~> bs, BytesLike bs) => hashExpr -> Expr (Hash Sha512 bs) sha3 :: (hashExpr :~> bs, BytesLike bs) => hashExpr -> Expr (Hash Sha3 bs) keccak :: (hashExpr :~> bs, BytesLike bs) => hashExpr -> Expr (Hash Keccak bs) hashKey :: keyExpr :~> PublicKey => keyExpr -> Expr KeyHash chainId :: Expr ChainId balance :: Expr Mutez level :: Expr Natural votingPower :: keyExpr :~> KeyHash => keyExpr -> Expr Natural totalVotingPower :: Expr Natural checkSignature :: (pkExpr :~> PublicKey, sigExpr :~> TSignature bs, hashExpr :~> bs, BytesLike bs) => pkExpr -> sigExpr -> hashExpr -> Expr Bool instance (Lorentz.Constraints.Scopes.NiceComparable k, Lorentz.Constraints.Scopes.KnownValue v) => Indigo.Frontend.Expr.ExprRemovable (Morley.Michelson.Typed.Haskell.Value.BigMap k v) instance (Lorentz.Constraints.Scopes.NiceComparable k, Lorentz.Constraints.Scopes.KnownValue v) => Indigo.Frontend.Expr.ExprRemovable (Data.Map.Internal.Map k v) instance Lorentz.Constraints.Scopes.NiceComparable a => Indigo.Frontend.Expr.ExprRemovable (Data.Set.Internal.Set a) instance (Lorentz.Constraints.Scopes.NiceComparable k, exKey Indigo.Common.Expr.:~> k, exValue Indigo.Common.Expr.:~> v) => Indigo.Frontend.Expr.ExprInsertable (Morley.Michelson.Typed.Haskell.Value.BigMap k v) (exKey, exValue) instance (Lorentz.Constraints.Scopes.NiceComparable k, exKey Indigo.Common.Expr.:~> k, exValue Indigo.Common.Expr.:~> v) => Indigo.Frontend.Expr.ExprInsertable (Data.Map.Internal.Map k v) (exKey, exValue) instance (Lorentz.Constraints.Scopes.NiceComparable a, exKey Indigo.Common.Expr.:~> a) => Indigo.Frontend.Expr.ExprInsertable (Data.Set.Internal.Set a) exKey instance Lorentz.Constraints.Scopes.KnownValue v => Indigo.Frontend.Expr.ExprMagma (Morley.Michelson.Typed.Haskell.Value.BigMap k v) instance Lorentz.Constraints.Scopes.KnownValue v => Indigo.Frontend.Expr.ExprMagma (Data.Map.Internal.Map k v) instance Indigo.Frontend.Expr.ExprMagma (Data.Set.Internal.Set k) instance Indigo.Frontend.Expr.ParityExpr GHC.Num.Integer.Integer GHC.Num.Integer.Integer instance Indigo.Frontend.Expr.ParityExpr GHC.Num.Natural.Natural GHC.Num.Natural.Natural instance Indigo.Frontend.Expr.ParityExpr Morley.Tezos.Core.Mutez Morley.Tezos.Core.Mutez -- | Expr compilation module Indigo.Backend.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 -- | 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) -- | Pretty printing of statements like "var := statement" prettyAssign' :: ReturnableValue' retKind ret => RetVars' retKind ret -> Text -> Text -- | Prettify ret value prettyRet' :: ReturnableValue' retKind ret => ret -> Text 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 => (StackVars xs -> MetaData xs) -> 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) prettyAssign :: forall ret. ReturnableValue ret => RetVars ret -> Text -> Text condStmtPretty :: forall ret x. ReturnableValue ret => RetVars ret -> Text -> Expr x -> Text prettyRet :: forall ret. ReturnableValue ret => ret -> Text 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, Formatting.Buildable.Buildable (Indigo.Backend.Scope.RetVars' 'Indigo.Backend.Scope.Tuple (x, y))) => Indigo.Backend.Scope.ReturnableValue' 'Indigo.Backend.Scope.Tuple (x, y) instance (Indigo.Backend.Scope.KnownValueExpr x, Indigo.Backend.Scope.KnownValueExpr y, Formatting.Buildable.Buildable (Indigo.Backend.Scope.RetVars' 'Indigo.Backend.Scope.Tuple (x, 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, Formatting.Buildable.Buildable (Indigo.Backend.Scope.RetVars' 'Indigo.Backend.Scope.Tuple (x, y, 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, Formatting.Buildable.Buildable (Indigo.Backend.Scope.RetVars' 'Indigo.Backend.Scope.Tuple (x, y, 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 () -- | 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.Backend.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 statements for variable manipulation: assignment, replacement, -- update. module Indigo.Backend.Var -- | Assign the given variable to the value resulting from the given -- expression. assignVar :: forall x inp. 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 -- | 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, KnownList 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 = WrappedLambda (arg : extra) (RetOutStack res ++ extra) -- | Backend failing statements of Indigo. module Indigo.Backend.Error failWith :: NiceConstant a => Expr a -> IndigoState s t never :: Expr Never -> IndigoState s t failUsing_ :: (IsError x, Buildable x) => x -> IndigoState s t failCustom :: forall tag err s t. (MustHaveErrorArg tag (MText, err), CustomErrorHasDoc tag, NiceConstant err) => Label tag -> Expr err -> IndigoState s t failCustom_ :: forall tag s t. (MustHaveErrorArg tag (MText, ()), CustomErrorHasDoc tag) => Label tag -> IndigoState s t failCustomNoArg :: forall tag s t. (MustHaveErrorArg tag MText, CustomErrorHasDoc tag) => Label tag -> IndigoState s t failUnexpected_ :: MText -> IndigoState s t -- | 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-statement that 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 ('Morley.Michelson.Typed.Haskell.Instr.Sum.CaseClauseParam ctor ('Morley.Michelson.Typed.Haskell.Instr.Sum.OneField x))) -- | StatementF functor datatype for Freer monad -- -- This defines the AST of the syntactical constructs of Indigo. -- -- Despite being a part of the "front-end", this module is considered -- internal implementation detail. It's not intended to be used by the -- end-user and hence is not re-exported. module Indigo.Frontend.Internal.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 () -- | Constructor wrapper which holds IndigoM function among with -- the callstack of caller side. -- -- The another option could be to add HasCallStack to -- Instr constructor of Program but this would have -- held only a CallStack of separate primitive statement (unlike -- updateStorageField, etc). The idea is to be able to have -- correspondence between original Indigo code and the generated -- Michelson assembler and vice versa to perform quick navigation and -- analyze, so it's better to have call stack for non-primitive frontend -- statements. [CalledFrom] :: CallStack -> freer a -> StatementF freer a [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] :: DocItem di => (SubDoc -> di) -> freer () -> StatementF freer () [ContractGeneral] :: freer () -> StatementF freer () [FinalizeParamCallingDoc] :: (NiceParameterFull cp, RequireSumType cp, HasCallStack) => (Var cp -> freer ()) -> Expr cp -> StatementF freer () [TransferTokens] :: (NiceParameter p, HasSideEffects, IsNotInView) => Expr p -> Expr Mutez -> Expr (ContractRef p) -> StatementF freer () [SetDelegate] :: (HasSideEffects, IsNotInView) => Expr (Maybe KeyHash) -> StatementF freer () [CreateContract] :: (IsObject st, NiceStorage st, NiceParameterFull param, HasSideEffects, NiceViewsDescriptor vd, Typeable vd, IsNotInView) => Contract param st vd -> Expr (Maybe KeyHash) -> Expr Mutez -> Expr st -> StatementF freer (Var Address) [SelfCalling] :: (NiceParameterFull p, KnownValue (GetEntrypointArgCustom p mname), IsoValue (ContractRef (GetEntrypointArgCustom p mname)), IsNotInView) => Proxy p -> EntrypointRef mname -> StatementF freer (Var (ContractRef (GetEntrypointArgCustom p mname))) [ContractCalling] :: (HasEntrypointArg cp epRef epArg, ToTAddress cp vd addr, ToT addr ~ ToT Address, KnownValue epArg, IsoValue (ContractRef epArg)) => Proxy (cp, vd) -> epRef -> Expr addr -> StatementF freer (Var (Maybe (ContractRef epArg))) [Emit] :: (HasSideEffects, NicePackedValue a, HasAnnotation a) => FieldAnn -> Expr a -> StatementF freer () [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, IsNotInView) => 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) 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] () -- | Indigo compiler back-end helpers. -- -- For reference, "back-end" refers to the part of the compiler pipeline -- that comes after the intermediate representation. In our case, -- intermediate representation is defined in -- Indigo.Frontend.Internal.Statement. -- -- Essentially these definitions simplify target code generation. This is -- not intended to be exported from Indigo. 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 :: forall l r inp. (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), IsoValue (ContractRef (GetEntrypointArgCustom p mname)), IsNotInView) => EntrypointRef mname -> Var (ContractRef (GetEntrypointArgCustom p mname)) -> IndigoState inp (ContractRef (GetEntrypointArgCustom p mname) : inp) contractCalling :: forall cp vd inp epRef epArg addr. (HasEntrypointArg cp epRef epArg, ToTAddress cp vd addr, ToT addr ~ ToT Address, HasNoOp (ToT epArg), HasNoNestedBigMaps (ToT epArg), 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 :: DocItem di => (SubDoc -> di) -> SomeIndigoState i -> SomeIndigoState i -- | Insert documentation of the contract storage type. The type should be -- passed using type applications. -- | Deprecated: Use `doc (dStorage @storage)` instead. docStorage :: forall storage s. TypeHasDoc storage => IndigoState s s -- | Give a name to the given contract. Apply it to the whole contract -- code. -- | Deprecated: Use `docGroup name` instead. 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. -- | Deprecated: Use `docGroup DGeneralInfoSection` instead. contractGeneral :: SomeIndigoState i -> SomeIndigoState i -- | Attach default general info to the contract documentation. contractGeneralDefault :: IndigoState s s transferTokens :: (NiceParameter p, HasSideEffects, IsNotInView) => Expr p -> Expr Mutez -> Expr (ContractRef p) -> IndigoState inp inp setDelegate :: (HasSideEffects, IsNotInView) => Expr (Maybe KeyHash) -> IndigoState inp inp createContract :: (HasSideEffects, NiceStorage s, NiceParameterFull p, NiceViewsDescriptor vd, Typeable vd, IsNotInView) => Contract p s vd -> Expr (Maybe KeyHash) -> Expr Mutez -> Expr s -> Var Address -> IndigoState inp (Address : inp) emit :: (HasSideEffects, NicePackedValue a, HasAnnotation a) => FieldAnn -> Expr a -> IndigoState inp 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 -- | Instruction datatype. module Indigo.Compilation.Sequential.Types -- | 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 [Comment] :: Text -> 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] :: forall di. DocItem di => (SubDoc -> di) -> Block -> Instruction [ContractGeneral] :: Block -> Instruction [FinalizeParamCallingDoc] :: (NiceParameterFull cp, RequireSumType cp) => Var cp -> Block -> Expr cp -> Instruction [TransferTokens] :: (NiceParameter p, HasSideEffects, IsNotInView) => Expr p -> Expr Mutez -> Expr (ContractRef p) -> Instruction [SetDelegate] :: (HasSideEffects, IsNotInView) => Expr (Maybe KeyHash) -> Instruction [CreateContract] :: (HasSideEffects, NiceStorage s, NiceParameterFull p, NiceViewsDescriptor vd, Typeable vd, IsNotInView) => Contract p s vd -> Expr (Maybe KeyHash) -> Expr Mutez -> Expr s -> Var Address -> Instruction [SelfCalling] :: (NiceParameterFull p, KnownValue (GetEntrypointArgCustom p mname), IsoValue (ContractRef (GetEntrypointArgCustom p mname)), IsNotInView) => Proxy p -> EntrypointRef mname -> Var (ContractRef (GetEntrypointArgCustom p mname)) -> Instruction [ContractCalling] :: (HasEntrypointArg cp epRef epArg, ToTAddress cp vd addr, ToT addr ~ ToT Address, KnownValue epArg, IsoValue (ContractRef epArg)) => Proxy (cp, vd) -> epRef -> Expr addr -> Var (Maybe (ContractRef epArg)) -> Instruction [Emit] :: (HasSideEffects, NicePackedValue a, HasAnnotation a) => FieldAnn -> Expr a -> 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 newtype SequentialHooks SequentialHooks :: (CallStack -> Block -> State InstrCollector ()) -> SequentialHooks [shStmtHook] :: SequentialHooks -> CallStack -> Block -> State InstrCollector () -- | Data type internally used to collect Instructions from -- IndigoM data InstrCollector InstrCollector :: RefId -> Block -> SequentialHooks -> InstrCollector [nextRef] :: InstrCollector -> RefId [instrList] :: InstrCollector -> Block [seqHooks] :: InstrCollector -> SequentialHooks stmtHookL :: Lens' SequentialHooks (CallStack -> Block -> State InstrCollector ()) instance GHC.Base.Semigroup Indigo.Compilation.Sequential.Types.SequentialHooks instance GHC.Base.Monoid Indigo.Compilation.Sequential.Types.SequentialHooks -- | 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 [Comment] :: Text -> 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] :: forall di. DocItem di => (SubDoc -> di) -> Block -> Instruction [ContractGeneral] :: Block -> Instruction [FinalizeParamCallingDoc] :: (NiceParameterFull cp, RequireSumType cp) => Var cp -> Block -> Expr cp -> Instruction [TransferTokens] :: (NiceParameter p, HasSideEffects, IsNotInView) => Expr p -> Expr Mutez -> Expr (ContractRef p) -> Instruction [SetDelegate] :: (HasSideEffects, IsNotInView) => Expr (Maybe KeyHash) -> Instruction [CreateContract] :: (HasSideEffects, NiceStorage s, NiceParameterFull p, NiceViewsDescriptor vd, Typeable vd, IsNotInView) => Contract p s vd -> Expr (Maybe KeyHash) -> Expr Mutez -> Expr s -> Var Address -> Instruction [SelfCalling] :: (NiceParameterFull p, KnownValue (GetEntrypointArgCustom p mname), IsoValue (ContractRef (GetEntrypointArgCustom p mname)), IsNotInView) => Proxy p -> EntrypointRef mname -> Var (ContractRef (GetEntrypointArgCustom p mname)) -> Instruction [ContractCalling] :: (HasEntrypointArg cp epRef epArg, ToTAddress cp vd addr, ToT addr ~ ToT Address, KnownValue epArg, IsoValue (ContractRef epArg)) => Proxy (cp, vd) -> epRef -> Expr addr -> Var (Maybe (ContractRef epArg)) -> Instruction [Emit] :: (HasSideEffects, NicePackedValue a, HasAnnotation a) => FieldAnn -> Expr a -> 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 newtype SequentialHooks SequentialHooks :: (CallStack -> Block -> State InstrCollector ()) -> SequentialHooks [shStmtHook] :: SequentialHooks -> CallStack -> Block -> State InstrCollector () stmtHookL :: Lens' SequentialHooks (CallStack -> Block -> State InstrCollector ()) -- | Data type internally used to collect Instructions from -- IndigoM data InstrCollector InstrCollector :: RefId -> Block -> SequentialHooks -> InstrCollector [nextRef] :: InstrCollector -> RefId [instrList] :: InstrCollector -> Block [seqHooks] :: InstrCollector -> SequentialHooks -- | Transformation from IndigoM to a Block of -- Instructions. -- -- Requires the first non-used RefId and returns the next one. indigoMtoSequential :: RefId -> SequentialHooks -> 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.Hooks data CommentsVerbosity NoComments :: CommentsVerbosity LogTopLevelFrontendStatements :: CommentsVerbosity LogBackendStatements :: CommentsVerbosity LogAuxCode :: CommentsVerbosity LogExpressionsComputations :: CommentsVerbosity data CommentSettings CommentSettings :: CommentsVerbosity -> Bool -> Bool -> CommentSettings [csVerbosity] :: CommentSettings -> CommentsVerbosity [csPrintFullStackTrace] :: CommentSettings -> Bool [csPrintFileName] :: CommentSettings -> Bool defaultCommentSettings :: CommentsVerbosity -> CommentSettings data CommentHooks CommentHooks :: SequentialHooks -> GenCodeHooks -> CommentHooks [chFrontendHooks] :: CommentHooks -> SequentialHooks [chBackendHooks] :: CommentHooks -> GenCodeHooks -- | Convert from enum-based verbosity description to specific actions. settingsToHooks :: CommentSettings -> CommentHooks instance GHC.Base.Semigroup Indigo.Compilation.Hooks.CommentHooks instance GHC.Base.Monoid Indigo.Compilation.Hooks.CommentHooks instance GHC.Enum.Enum Indigo.Compilation.Hooks.CommentsVerbosity instance GHC.Enum.Bounded Indigo.Compilation.Hooks.CommentsVerbosity instance GHC.Classes.Ord Indigo.Compilation.Hooks.CommentsVerbosity instance GHC.Classes.Eq Indigo.Compilation.Hooks.CommentsVerbosity instance GHC.Show.Show Indigo.Compilation.Hooks.CommentsVerbosity instance GHC.Show.Show Indigo.Compilation.Hooks.CommentSettings instance GHC.Classes.Eq Indigo.Compilation.Hooks.CommentSettings instance Data.Default.Class.Default Indigo.Compilation.Hooks.CommentSettings module Indigo.Compilation.Field optimizeFields :: (Block, RefId) -> (Block, RefId) 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 -- | This module contains the high-level compilation of Indigo to Lorentz, -- including plain Indigo code, as well as Indigo contracts. module Indigo.Compilation data CommentSettings CommentSettings :: CommentsVerbosity -> Bool -> Bool -> CommentSettings [csVerbosity] :: CommentSettings -> CommentsVerbosity [csPrintFullStackTrace] :: CommentSettings -> Bool [csPrintFileName] :: CommentSettings -> Bool data CommentsVerbosity NoComments :: CommentsVerbosity LogTopLevelFrontendStatements :: CommentsVerbosity LogBackendStatements :: CommentsVerbosity LogAuxCode :: CommentsVerbosity LogExpressionsComputations :: CommentsVerbosity defaultCommentSettings :: CommentsVerbosity -> CommentSettings -- | Simplified version of compileIndigoFull 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. compileIndigoContractFull :: forall param st. (KnownValue param, IsObject st) => CommentSettings -> IndigoContract param st -> ContractCode param st -- | Simplified version of compileIndigoContractFull 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, HasCallStack) => ex -> IndigoM (Var x) -- | Set the given variable to the result of the given expression. setVar :: (IsExpr ex x, HasCallStack) => Var x -> ex -> IndigoM () setField :: (ex :~> ftype, IsObject dt, IsObject ftype, HasField dt fname ftype, HasCallStack) => Var dt -> Label fname -> ex -> IndigoM () (+=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Add n m m, HasCallStack) => Var m -> ex1 -> IndigoM () (-=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Sub n m m, HasCallStack) => Var m -> ex1 -> IndigoM () (*=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Mul n m m, HasCallStack) => Var m -> ex1 -> IndigoM () (<<<=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Lsl n m m, HasCallStack) => Var m -> ex1 -> IndigoM () (>>>=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Lsr n m m, HasCallStack) => Var m -> ex1 -> IndigoM () (&&=) :: (IsExpr ex1 n, IsObject m, ArithOpHs And n m m, HasCallStack) => Var m -> ex1 -> IndigoM () (||=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Or n m m, HasCallStack) => Var m -> ex1 -> IndigoM () (^=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Xor n m m, HasCallStack) => Var m -> ex1 -> IndigoM () (=:) :: (IsExpr ex x, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => Label fname -> (Var ftype -> IndigoM fex) -> IndigoM () if_ :: forall a b ex. (IfConstraint a b, ex :~> Bool, HasCallStack) => ex -> IndigoM a -> IndigoM b -> IndigoM (RetVars a) -- | Run the instruction when the condition is met, do nothing otherwise. when :: (exc :~> Bool, HasCallStack) => exc -> IndigoM () -> IndigoM () -- | Reverse of when. unless :: (exc :~> Bool, HasCallStack) => exc -> IndigoM () -> IndigoM () ifSome :: forall x a b ex. (KnownValue x, ex :~> Maybe x, IfConstraint a b, HasCallStack) => ex -> (Var x -> IndigoM a) -> IndigoM b -> IndigoM (RetVars a) ifNone :: forall x a b ex. (KnownValue x, ex :~> Maybe x, IfConstraint a b, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => exa -> IndigoM () -> IndigoM () ifRight :: forall x y a b ex. (KnownValue x, KnownValue y, ex :~> Either y x, IfConstraint a b, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => ex -> (Var x -> IndigoM ()) -> IndigoM () whenLeft :: forall x y ex. (KnownValue x, KnownValue y, ex :~> Either y x, HasCallStack) => ex -> (Var y -> IndigoM ()) -> IndigoM () ifCons :: forall x a b ex. (KnownValue x, ex :~> List x, IfConstraint a b, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => IndigoM a -> IndigoFunction a -- | Alias for scope we use in the tutorial. defFunction :: forall a. (ScopeCodeGen a, HasCallStack) => 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 :: HasCallStack => ((HasSideEffects, IsNotInView) => IndigoM ()) -> (HasSideEffects, IsNotInView) => 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, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => String -> (Var (ExprType argExpr) -> IndigoM res) -> argExpr -> IndigoM (RetVars res) -- | While statement. while :: forall ex. (ex :~> Bool, HasCallStack) => ex -> IndigoM () -> IndigoM () whileLeft :: forall x y ex. (ex :~> Either y x, KnownValue y, KnownValue x, HasCallStack) => 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, HasCallStack) => e -> (Var (IterOpElHs a) -> IndigoM ()) -> IndigoM () selfCalling :: forall p mname. (NiceParameterFull p, KnownValue (GetEntrypointArgCustom p mname), IsoValue (ContractRef (GetEntrypointArgCustom p mname)), HasCallStack, IsNotInView) => EntrypointRef mname -> IndigoM (Var (ContractRef (GetEntrypointArgCustom p mname))) contractCalling :: forall cp vd epRef epArg addr exAddr. (HasEntrypointArg cp epRef epArg, ToTAddress cp vd addr, ToT addr ~ ToT Address, exAddr :~> addr, KnownValue epArg, IsoValue (ContractRef epArg), HasCallStack) => epRef -> exAddr -> IndigoM (Var (Maybe (ContractRef epArg))) -- | Put a document item. doc :: (DocItem di, HasCallStack) => di -> IndigoM () -- | Group documentation built in the given piece of code into a block -- dedicated to one thing, e.g. to one entrypoint. docGroup :: (DocItem di, HasCallStack) => (SubDoc -> di) -> IndigoM () -> IndigoM () -- | Insert documentation of the contract's storage type. The type should -- be passed using type applications. -- | Deprecated: Use `doc (dStorage @storage)` instead. docStorage :: forall storage. (TypeHasDoc storage, HasCallStack) => IndigoM () -- | Give a name to the given contract. Apply it to the whole contract -- code. -- | Deprecated: Use `docGroup name` instead. contractName :: HasCallStack => Text -> IndigoM () -> IndigoM () -- | Attach general info to the given contract. -- | Deprecated: Use `docGroup DGeneralInfoSection` instead. contractGeneral :: HasCallStack => IndigoM () -> IndigoM () -- | Attach default general info to the contract documentation. contractGeneralDefault :: HasCallStack => 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 :: HasCallStack => Text -> IndigoM () -- | Put a DDescription doc item. description :: HasCallStack => Markdown -> IndigoM () -- | Put a DEntrypointExample doc item. example :: forall a. (NiceParameter a, HasCallStack) => a -> IndigoM () transferTokens :: (IsExpr exp p, IsExpr exm Mutez, IsExpr exc (ContractRef p), NiceParameter p, HasSideEffects, HasCallStack, IsNotInView) => exp -> exm -> exc -> IndigoM () setDelegate :: (HasSideEffects, IsExpr ex (Maybe KeyHash), HasCallStack, IsNotInView) => ex -> IndigoM () -- | Create contract using default compilation options for Lorentz -- compiler. -- -- See Lorentz.Run. createContract :: forall st exk exm exs param. (IsObject st, IsExpr exk (Maybe KeyHash), IsExpr exm Mutez, IsExpr exs st, NiceStorageFull st, NiceParameterFull param, HasSideEffects, HasCallStack, IsNotInView) => (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, NiceViewsDescriptor vd, Typeable vd, HasSideEffects, HasCallStack, IsNotInView) => Contract param st vd -> exk -> exm -> exs -> IndigoM (Var Address) -- | emit tag expression emits a contract event with textual tag -- tag and payload expression. -- -- The tag must be a field annotation. Use annQ quoter to -- construct it from a literal, for example: -- --
--   emit [annQ|tag|] ()
--   
emit :: (HasSideEffects, NicePackedValue a, HasAnnotation a, HasCallStack) => FieldAnn -> Expr a -> IndigoM () failWith :: forall ret a ex. (NiceConstant a, IsExpr ex a, ReturnableValue ret, HasCallStack) => ex -> IndigoM (RetVars ret) assert :: forall x ex. (IsError x, Buildable x, IsExpr ex Bool, HasCallStack) => x -> ex -> IndigoM () failCustom :: forall ret tag err ex. (ReturnableValue ret, MustHaveErrorArg tag (MText, err), CustomErrorHasDoc tag, NiceConstant err, ex :~> err, HasCallStack) => Label tag -> ex -> IndigoM (RetVars ret) failCustom_ :: forall ret tag. (ReturnableValue ret, MustHaveErrorArg tag (MText, ()), CustomErrorHasDoc tag, HasCallStack) => Label tag -> IndigoM (RetVars ret) failCustomNoArg :: forall ret tag. (ReturnableValue ret, MustHaveErrorArg tag MText, CustomErrorHasDoc tag, HasCallStack) => Label tag -> IndigoM (RetVars ret) failUnexpected_ :: forall ret. (ReturnableValue ret, HasCallStack) => MText -> IndigoM (RetVars ret) assertCustom :: forall tag err errEx ex. (MustHaveErrorArg tag (MText, err), CustomErrorHasDoc tag, NiceConstant err, IsExpr errEx err, IsExpr ex Bool, HasCallStack) => Label tag -> errEx -> ex -> IndigoM () assertCustom_ :: forall tag ex. (MustHaveErrorArg tag (MText, ()), CustomErrorHasDoc tag, IsExpr ex Bool, HasCallStack) => Label tag -> ex -> IndigoM () assertCustomNoArg :: forall tag ex. (MustHaveErrorArg tag MText, CustomErrorHasDoc tag, IsExpr ex Bool, HasCallStack) => Label tag -> ex -> IndigoM () assertSome :: forall x err ex. (IsError err, Buildable err, KnownValue x, ex :~> Maybe x, HasCallStack) => err -> ex -> IndigoM () assertNone :: forall x err ex. (IsError err, Buildable err, KnownValue x, ex :~> Maybe x, HasCallStack) => err -> ex -> IndigoM () assertRight :: forall x y err ex. (IsError err, Buildable err, KnownValue x, KnownValue y, ex :~> Either y x, HasCallStack) => err -> ex -> IndigoM () assertLeft :: forall x y err ex. (IsError err, Buildable err, KnownValue x, KnownValue y, ex :~> Either y x, HasCallStack) => err -> ex -> IndigoM () type ReturnableValue ret = ReturnableValue' (ClassifyReturnValue ret) ret type RetVars ret = RetVars' (ClassifyReturnValue ret) ret -- | A convenience synonym for field Annotation type FieldAnn = Annotation FieldTag -- |
--   >>> :t [annQ||]
--   ... :: forall {k} {tag :: k}. Annotation tag
--   
-- --
--   >>> :t [annQ|abc|]
--   ... :: forall {k} {tag :: k}. Annotation tag
--   
annQ :: QuasiQuoter -- | Add a comment in a generated Michelson code comment :: HasCallStack => CommentType -> IndigoM () -- | Add a comment in a generated Michelson code justComment :: HasCallStack => Text -> IndigoM () -- | Add a comment before and after the given Indigo function code. The -- first argument is the name of the function. commentAroundFun :: HasCallStack => 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 :: HasCallStack => 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 () -- | Indigo compiler front-end. -- -- For reference, "front-end" refers to the part of the compiler pipeline -- that comes before the intermediate representation. In our case, -- intermediate representation is defined in -- Indigo.Frontend.Internal.Statement. -- -- This module exports the syntactical constructs of the Indigo language, -- along with the required types. 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, NiceStorageFull st) => Bool -> CommentSettings -> IndigoContract param st -> LText -- | Generate an Indigo contract documentation. renderIndigoDoc :: forall param st. (IsObject st, NiceParameterFull param, NiceStorageFull st) => 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, NiceStorageFull st, MonadIO m) => CommentSettings -> 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, NiceStorageFull st, MonadIO m, MonadMask m) => CommentSettings -> IndigoContract param st -> FilePath -> m () -- | Print the generated documentation to the standard output. printDocumentation :: forall param st m. (IsObject st, NiceParameterFull param, NiceStorageFull st, MonadIO m) => IndigoContract param st -> m () -- | Save the generated documentation to the given file. saveDocumentation :: forall param st m. (IsObject st, NiceParameterFull param, NiceStorageFull st, 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.Rebound -- | 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, IsNotInView) => (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, IsNotInView) => 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 :: forall {r :: RuntimeRep} a (b :: TYPE r). a -> b -> b infixr 0 `seq` -- | <math>. filter, applied to a predicate and a list, -- returns the list of those elements that satisfy the predicate; i.e., -- --
--   filter p xs = [ x | x <- xs, p x]
--   
-- --
--   >>> filter odd [1, 2, 3]
--   [1,3]
--   
filter :: (a -> Bool) -> [a] -> [a] -- | <math>. zip takes two lists and returns a list of -- corresponding pairs. -- --
--   >>> zip [1, 2] ['a', 'b']
--   [(1, 'a'), (2, 'b')]
--   
-- -- If one input list is shorter than the other, excess elements of the -- longer list are discarded, even if one of the lists is infinite: -- --
--   >>> zip [1] ['a', 'b']
--   [(1, 'a')]
--   
--   >>> zip [1, 2] ['a']
--   [(1, 'a')]
--   
--   >>> zip [] [1..]
--   []
--   
--   >>> zip [1..] []
--   []
--   
-- -- zip is right-lazy: -- --
--   >>> zip [] _|_
--   []
--   
--   >>> 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 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. -- -- 'join bss' can be understood as the do -- expression -- --
--   do bs <- bss
--      bs
--   
-- --

Examples

-- -- A common use of join is to run an IO computation -- returned from an STM transaction, since STM transactions -- can't perform IO directly. Recall that -- --
--   atomically :: STM a -> IO a
--   
-- -- is used to run STM transactions atomically. So, by specializing -- the types of atomically and join to -- --
--   atomically :: STM (IO b) -> IO (IO b)
--   join       :: IO (IO b)  -> IO b
--   
-- -- we can compose them as -- --
--   join . atomically :: STM (IO b) -> IO b
--   
-- -- to run an STM transaction and the IO action it returns. join :: Monad m => m (m a) -> m a -- | The Bounded class is used to name the upper and lower limits of -- a type. Ord is not a superclass of Bounded since types -- that are not totally ordered may also have upper and lower bounds. -- -- The Bounded class may be derived for any enumeration type; -- minBound is the first constructor listed in the data -- declaration and maxBound is the last. Bounded may also -- be derived for single-constructor datatypes whose constituent types -- are in Bounded. class Bounded a minBound :: Bounded a => a maxBound :: Bounded a => a -- | Class Enum defines operations on sequentially ordered types. -- -- The enumFrom... methods are used in Haskell's translation of -- arithmetic sequences. -- -- Instances of Enum may be derived for any enumeration type -- (types whose constructors have no fields). The nullary constructors -- are assumed to be numbered left-to-right by fromEnum from -- 0 through n-1. See Chapter 10 of the Haskell -- Report for more details. -- -- For any type that is an instance of class Bounded as well as -- Enum, the following should hold: -- -- -- --
--   enumFrom     x   = enumFromTo     x maxBound
--   enumFromThen x y = enumFromThenTo x y bound
--     where
--       bound | fromEnum y >= fromEnum x = maxBound
--             | otherwise                = minBound
--   
class Enum a -- | the successor of a value. For numeric types, succ adds 1. succ :: Enum a => a -> a -- | the predecessor of a value. For numeric types, pred subtracts -- 1. pred :: Enum a => a -> a -- | Convert from an Int. toEnum :: Enum a => Int -> a -- | Convert to an Int. It is implementation-dependent what -- fromEnum returns when applied to a value that is too large to -- fit in an Int. fromEnum :: Enum a => a -> Int -- | Used in Haskell's translation of [n..] with [n..] = -- enumFrom n, a possible implementation being enumFrom n = n : -- enumFrom (succ n). For example: -- -- enumFrom :: Enum a => a -> [a] -- | Used in Haskell's translation of [n,n'..] with [n,n'..] = -- enumFromThen n n', a possible implementation being -- enumFromThen n n' = n : n' : worker (f x) (f x n'), -- worker s v = v : worker s (s v), x = fromEnum n' - -- fromEnum n and f n y | n > 0 = f (n - 1) (succ y) | n < -- 0 = f (n + 1) (pred y) | otherwise = y For example: -- -- enumFromThen :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n..m] with [n..m] = -- enumFromTo n m, a possible implementation being enumFromTo n -- m | n <= m = n : enumFromTo (succ n) m | otherwise = []. For -- example: -- -- enumFromTo :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n,n'..m] with [n,n'..m] -- = enumFromThenTo n n' m, a possible implementation being -- enumFromThenTo n n' m = worker (f x) (c x) n m, x = -- fromEnum n' - fromEnum n, c x = bool (>=) ((x -- 0) f n y | n > 0 = f (n - 1) (succ y) | n < 0 = f (n + -- 1) (pred y) | otherwise = y and worker s c v m | c v m = v : -- worker s c (s v) m | otherwise = [] For example: -- -- enumFromThenTo :: Enum a => a -> a -> a -> [a] -- | The Eq class defines equality (==) and inequality -- (/=). All the basic datatypes exported by the Prelude -- are instances of Eq, and Eq may be derived for any -- datatype whose constituents are also instances of Eq. -- -- The Haskell Report defines no laws for Eq. However, == -- 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. -- -- 'as >>= bs' can be understood as the do -- expression -- --
--   do a <- as
--      bs a
--   
(>>=) :: Monad m => m a -> (a -> m b) -> m b -- | Sequentially compose two actions, discarding any value produced by the -- first, like sequencing operators (such as the semicolon) in imperative -- languages. -- -- 'as >> bs' can be understood as the do -- expression -- --
--   do as
--      bs
--   
(>>) :: Monad m => m a -> m b -> m b -- | Inject a value into the monadic type. return :: Monad m => a -> m a infixl 1 >>= infixl 1 >> -- | A type f is a Functor if it provides a function fmap -- which, given any types a and b lets you apply any -- function from (a -> b) to turn an f a into an -- f b, preserving the structure of f. Furthermore -- f needs to adhere to the following: -- -- -- -- Note, that the second law follows from the free theorem of the type -- fmap and the first law, so you need only check that the former -- condition holds. class Functor (f :: Type -> Type) -- | fmap is used to apply a function of type (a -> b) -- to a value of type f a, where f is a functor, to produce a -- value of type f b. Note that for any type constructor with -- more than one parameter (e.g., Either), only the last type -- parameter can be modified with fmap (e.g., b in -- `Either a b`). -- -- Some type constructors with two parameters or more have a -- Bifunctor instance that allows both the last and the -- penultimate parameters to be mapped over. ==== Examples -- -- Convert from a Maybe Int to a Maybe String -- using show: -- --
--   >>> fmap show Nothing
--   Nothing
--   
--   >>> fmap show (Just 3)
--   Just "3"
--   
-- -- Convert from an Either Int Int to an Either Int -- String using show: -- --
--   >>> fmap show (Left 17)
--   Left 17
--   
--   >>> fmap show (Right 17)
--   Right "17"
--   
-- -- Double each element of a list: -- --
--   >>> fmap (*2) [1,2,3]
--   [2,4,6]
--   
-- -- Apply even to the second element of a pair: -- --
--   >>> fmap even (2,2)
--   (2,True)
--   
-- -- It may seem surprising that the function is only applied to the last -- element of the tuple compared to the list example above which applies -- it to every element in the list. To understand, remember that tuples -- are type constructors with multiple type parameters: a tuple of 3 -- elements `(a,b,c)` can also be written `(,,) a b c` and its -- Functor instance is defined for `Functor ((,,) a b)` (i.e., -- only the third parameter is free to be mapped over with fmap). -- -- It explains why fmap can be used with tuples containing values -- of different types as in the following example: -- --
--   >>> fmap even ("hello", 1.0, 4)
--   ("hello",1.0,True)
--   
fmap :: Functor f => (a -> b) -> f a -> f b -- | Replace all locations in the input with the same value. The default -- definition is fmap . const, but this may be -- overridden with a more efficient version. (<$) :: Functor f => a -> f b -> f a infixl 4 <$ -- | Basic numeric class. -- -- The Haskell Report defines no laws for Num. However, -- (+) and (*) are customarily expected -- to define a ring and have the following properties: -- -- -- -- Note that it isn't customarily expected that a type instance of -- both Num and Ord implement an ordered ring. Indeed, in -- base only Integer and Rational do. class Num a -- | 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. --
-- -- Note that (7.) and (8.) do not require min and -- max to return either of their arguments. The result is merely -- required to equal one of the arguments in terms of (==). -- -- Minimal complete definition: either compare or <=. -- Using compare can be more efficient for complex types. class Eq a => Ord a compare :: Ord a => a -> a -> Ordering 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. -- --

Example

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

Example

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

Examples

-- -- If used in conjunction with the Applicative instance for Maybe, -- you can chain Maybe computations, with a possible "early return" in -- case of Nothing. -- --
--   >>> Just 2 *> Just 3
--   Just 3
--   
-- --
--   >>> Nothing *> Just 3
--   Nothing
--   
-- -- Of course a more interesting use case would be to have effectful -- computations instead of just returning pure values. -- --
--   >>> import Data.Char
--   
--   >>> import Text.ParserCombinators.ReadP
--   
--   >>> let p = string "my name is " *> munch1 isAlpha <* eof
--   
--   >>> readP_to_S p "my name is Simon"
--   [("Simon","")]
--   
(*>) :: Applicative f => f a -> f b -> f b -- | Sequence actions, discarding the value of the second argument. (<*) :: Applicative f => f a -> f b -> f a infixl 4 <* infixl 4 *> infixl 4 <*> -- | The Foldable class represents data structures that can be reduced to a -- summary value one element at a time. Strict left-associative folds are -- a good fit for space-efficient reduction, while lazy right-associative -- folds are a good fit for corecursive iteration, or for folds that -- short-circuit after processing an initial subsequence of the -- structure's elements. -- -- Instances can be derived automatically by enabling the -- DeriveFoldable extension. For example, a derived instance for -- a binary tree might be: -- --
--   {-# LANGUAGE DeriveFoldable #-}
--   data Tree a = Empty
--               | Leaf a
--               | Node (Tree a) a (Tree a)
--       deriving Foldable
--   
-- -- A more detailed description can be found in the Overview -- section of Data.Foldable#overview. -- -- For the class laws see the Laws section of -- Data.Foldable#laws. class Foldable (t :: Type -> Type) -- | Functors representing data structures that can be transformed to -- structures of the same shape by performing an -- Applicative (or, therefore, Monad) action on each -- element from left to right. -- -- A more detailed description of what same shape means, the -- various methods, how traversals are constructed, and example advanced -- use-cases can be found in the Overview section of -- Data.Traversable#overview. -- -- For the class laws see the Laws section of -- Data.Traversable#laws. class (Functor t, Foldable t) => Traversable (t :: Type -> Type) -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and collect the results. For a version that -- ignores the results see traverse_. -- --

Examples

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

Examples

-- -- Basic usage: -- -- For the first two examples we show sequenceA fully evaluating a a -- structure and collecting the results. -- --
--   >>> sequenceA [Just 1, Just 2, Just 3]
--   Just [1,2,3]
--   
-- --
--   >>> sequenceA [Right 1, Right 2, Right 3]
--   Right [1,2,3]
--   
-- -- The next two example show Nothing and Just will short -- circuit the resulting structure if present in the input. For more -- context, check the Traversable instances for Either and -- Maybe. -- --
--   >>> sequenceA [Just 1, Just 2, Just 3, Nothing]
--   Nothing
--   
-- --
--   >>> sequenceA [Right 1, Right 2, Right 3, Left 4]
--   Left 4
--   
sequenceA :: (Traversable t, Applicative f) => t (f a) -> f (t a) -- | Map each element of a structure to a monadic action, evaluate these -- actions from left to right, and collect the results. For a version -- that ignores the results see mapM_. -- --

Examples

-- -- mapM is literally a traverse with a type signature -- restricted to Monad. Its implementation may be more efficient -- due to additional power of Monad. mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b) -- | Evaluate each monadic action in the structure from left to right, and -- collect the results. For a version that ignores the results see -- sequence_. -- --

Examples

-- -- Basic usage: -- -- The first two examples are instances where the input and and output of -- sequence are isomorphic. -- --
--   >>> sequence $ Right [1,2,3,4]
--   [Right 1,Right 2,Right 3,Right 4]
--   
-- --
--   >>> sequence $ [Right 1,Right 2,Right 3,Right 4]
--   Right [1,2,3,4]
--   
-- -- The following examples demonstrate short circuit behavior for -- sequence. -- --
--   >>> sequence $ Left [1,2,3,4]
--   Left [1,2,3,4]
--   
-- --
--   >>> sequence $ [Left 0, Right 1,Right 2,Right 3,Right 4]
--   Left 0
--   
sequence :: (Traversable t, Monad m) => t (m a) -> m (t a) -- | Representable types of kind *. This class is derivable in GHC -- with the DeriveGeneric flag on. -- -- A Generic instance must satisfy the following laws: -- --
--   from . toid
--   to . fromid
--   
class Generic a -- | 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. -- --
--   >>> import Data.List.NonEmpty (NonEmpty (..))
--   
--   >>> sconcat $ "Hello" :| [" ", "Haskell", "!"]
--   "Hello Haskell!"
--   
sconcat :: Semigroup a => NonEmpty a -> a -- | Repeat a value n times. -- -- Given that this works on a Semigroup it is allowed to fail if -- you request 0 or fewer repetitions, and the default definition will do -- so. -- -- By making this a member of the class, idempotent semigroups and -- monoids can upgrade this to execute in <math> by picking -- stimes = stimesIdempotent or stimes = -- stimesIdempotentMonoid respectively. -- --
--   >>> stimes 4 [1]
--   [1,1,1,1]
--   
stimes :: (Semigroup a, Integral b) => b -> a -> a -- | The class of monoids (types with an associative binary operation that -- has an identity). Instances should satisfy the following: -- -- -- -- The method names refer to the monoid of lists under concatenation, but -- there are many other instances. -- -- Some types can be viewed as a monoid in more than one way, e.g. both -- addition and multiplication on numbers. In such cases we often define -- newtypes and make those instances of Monoid, e.g. -- Sum and Product. -- -- NOTE: Semigroup is a superclass of Monoid since -- base-4.11.0.0. class Semigroup a => Monoid a -- | Identity of mappend -- --
--   >>> "Hello world" <> mempty
--   "Hello world"
--   
mempty :: Monoid a => a -- | An associative operation -- -- NOTE: This method is redundant and has the default -- implementation mappend = (<>) since -- base-4.11.0.0. Should it be implemented manually, since -- mappend is a synonym for (<>), it is expected that -- the two functions are defined the same way. In a future GHC release -- mappend will be removed from Monoid. mappend :: Monoid a => a -> a -> a -- | Fold a list using the monoid. -- -- For most types, the default definition for mconcat will be -- used, but the function is included in the class definition so that an -- optimized version can be provided for specific types. -- --
--   >>> mconcat ["Hello", " ", "Haskell", "!"]
--   "Hello Haskell!"
--   
mconcat :: Monoid a => [a] -> a data Bool False :: Bool True :: Bool -- | A String is a list of characters. String constants in Haskell -- are values of type String. -- -- See Data.List for operations on lists. type String = [Char] -- | The character type Char is an enumeration whose values -- represent Unicode (or equivalently ISO/IEC 10646) code points (i.e. -- characters, see http://www.unicode.org/ for details). This set -- extends the ISO 8859-1 (Latin-1) character set (the first 256 -- characters), which is itself an extension of the ASCII character set -- (the first 128 characters). A character literal in Haskell has type -- Char. -- -- To convert a Char to or from the corresponding Int value -- defined by Unicode, use toEnum and fromEnum from the -- Enum class respectively (or equivalently ord and -- chr). data Char -- | Double-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- double-precision type. data Double 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 -- | Arbitrary precision integers. In contrast with fixed-size integral -- types such as Int, the Integer type represents the -- entire infinite range of integers. -- -- Integers are stored in a kind of sign-magnitude form, hence do not -- expect two's complement form when using bit operations. -- -- If the value is small (fit into an Int), IS constructor -- is used. Otherwise IP and IN constructors are used to -- store a BigNat representing respectively the positive or the -- negative value magnitude. -- -- Invariant: IP and IN are used iff value doesn't fit in -- IS data Integer -- | Natural number -- -- Invariant: numbers <= 0xffffffffffffffff use the NS -- constructor data Natural -- | The Maybe type encapsulates an optional value. A value of type -- Maybe a either contains a value of type a -- (represented as Just a), or it is empty (represented -- as Nothing). Using Maybe is a good way to deal with -- errors or exceptional cases without resorting to drastic measures such -- as error. -- -- The Maybe type is also a monad. It is a simple kind of error -- monad, where all errors are represented by Nothing. A richer -- error monad can be built using the Either type. data Maybe a Nothing :: Maybe a Just :: a -> Maybe a data Ordering LT :: Ordering EQ :: Ordering GT :: Ordering -- | Rational numbers, with numerator and denominator of some -- Integral type. -- -- Note that Ratio's instances inherit the deficiencies from the -- type parameter's. For example, Ratio Natural's Num -- instance has similar problems to Natural's. data Ratio a (:%) :: !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 types with lifted values. For example Int :: -- Type. type Type = Type -- | 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 -- | 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 -- | Reverse order of bytes in Word16. byteSwap16 :: Word16 -> Word16 -- | Reverse order of bytes in Word32. byteSwap32 :: Word32 -> Word32 -- | Reverse order of bytes in Word64. byteSwap64 :: Word64 -> Word64 -- | 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 -- | deepseq: fully evaluates the first argument, before returning -- the second. -- -- The name deepseq is used to illustrate the relationship to -- seq: where seq is shallow in the sense that it only -- evaluates the top level of its argument, deepseq traverses the -- entire data structure evaluating it completely. -- -- deepseq can be useful for forcing pending exceptions, -- eradicating space leaks, or forcing lazy I/O to happen. It is also -- useful in conjunction with parallel Strategies (see the -- parallel package). -- -- There is no guarantee about the ordering of evaluation. The -- implementation may evaluate the components of the structure in any -- order or in parallel. To impose an actual order on evaluation, use -- pseq from Control.Parallel in the parallel -- package. deepseq :: NFData a => a -> b -> b -- | a 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 -- | 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 set of values a. data Set a -- | 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 -- | 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 -- | Function composition. (.) :: (b -> c) -> (a -> b) -> a -> c infixr 9 . -- | Same as >>=, but with the arguments interchanged. (=<<) :: Monad m => (a -> m b) -> m a -> m b infixr 1 =<< -- | 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 -- | asTypeOf is a type-restricted version of const. It is -- usually used as an infix operator, and its typing forces its first -- argument (which is usually overloaded) to have the same type as the -- second. asTypeOf :: a -> a -> a -- | const x is a unary function which evaluates to x for -- all inputs. -- --
--   >>> const 42 "hello"
--   42
--   
-- --
--   >>> map (const 42) [0..3]
--   [42,42,42,42]
--   
const :: a -> b -> a -- | flip f takes its (first) two arguments in the reverse -- order of f. -- --
--   >>> flip (++) "hello" "world"
--   "worldhello"
--   
flip :: (a -> b -> c) -> b -> a -> c -- | Identity function. -- --
--   id x = x
--   
id :: a -> a -- | 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 -- | The fromEnum method restricted to the type Char. ord :: Char -> Int -- | 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 -- | Non-empty (and non-strict) list type. data NonEmpty a (:|) :: a -> [a] -> NonEmpty a infixr 5 :| -- | 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 -- | curry converts an uncurried function to a curried function. -- --

Examples

-- --
--   >>> curry fst 1 2
--   1
--   
curry :: ((a, b) -> c) -> a -> b -> c -- | 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 -- | 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 <$> -- | 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 () -- | 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` -- | 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 fromMaybe function takes a default value and a Maybe -- value. If the Maybe is Nothing, it returns the default -- value; otherwise, it returns the value contained in the Maybe. -- --

Examples

-- -- Basic usage: -- --
--   >>> fromMaybe "" (Just "Hello, World!")
--   "Hello, World!"
--   
-- --
--   >>> fromMaybe "" Nothing
--   ""
--   
-- -- Read an integer from a string using readMaybe. If we fail to -- parse an integer, we want to return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> fromMaybe 0 (readMaybe "5")
--   5
--   
--   >>> fromMaybe 0 (readMaybe "")
--   0
--   
fromMaybe :: a -> Maybe a -> a -- | The 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 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 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 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 maybe function takes a default value, a function, and a -- Maybe value. If the Maybe value is Nothing, the -- function returns the default value. Otherwise, it applies the function -- to the value inside the Just and returns the result. -- --

Examples

-- -- Basic usage: -- --
--   >>> maybe False odd (Just 3)
--   True
--   
-- --
--   >>> maybe False odd Nothing
--   False
--   
-- -- Read an integer from a string using readMaybe. If we succeed, -- return twice the integer; that is, apply (*2) to it. If -- instead we fail to parse an integer, return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> maybe 0 (*2) (readMaybe "5")
--   10
--   
--   >>> maybe 0 (*2) (readMaybe "")
--   0
--   
-- -- Apply show to a Maybe Int. If we have Just n, -- we want to show the underlying Int n. But if we have -- Nothing, we return the empty string instead of (for example) -- "Nothing": -- --
--   >>> maybe "" show (Just 5)
--   "5"
--   
--   >>> maybe "" show Nothing
--   ""
--   
maybe :: b -> (a -> b) -> Maybe a -> b -- | The 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] -- | break, applied to a predicate p and a list -- xs, returns a tuple where first element is longest prefix -- (possibly empty) of xs of elements that do not satisfy -- p and second element is the remainder of the list: -- --
--   >>> break (> 3) [1,2,3,4,1,2,3,4]
--   ([1,2,3],[4,1,2,3,4])
--   
--   >>> break (< 9) [1,2,3]
--   ([],[1,2,3])
--   
--   >>> break (> 9) [1,2,3]
--   ([1,2,3],[])
--   
-- -- break p is equivalent to span (not . -- p). break :: (a -> Bool) -> [a] -> ([a], [a]) -- | cycle ties a finite list into a circular one, or equivalently, -- the infinite repetition of the original list. It is the identity on -- infinite lists. -- --
--   >>> cycle []
--   *** Exception: Prelude.cycle: empty list
--   
--   >>> take 20 $ cycle [42]
--   [42,42,42,42,42,42,42,42,42,42...
--   
--   >>> take 20 $ cycle [2, 5, 7]
--   [2,5,7,2,5,7,2,5,7,2,5,7...
--   
cycle :: [a] -> [a] -- | drop n xs returns the suffix of xs after the -- first n elements, or [] if n >= length -- xs. -- --
--   >>> drop 6 "Hello World!"
--   "World!"
--   
--   >>> drop 3 [1,2,3,4,5]
--   [4,5]
--   
--   >>> drop 3 [1,2]
--   []
--   
--   >>> drop 3 []
--   []
--   
--   >>> drop (-1) [1,2]
--   [1,2]
--   
--   >>> drop 0 [1,2]
--   [1,2]
--   
-- -- It is an instance of the more general genericDrop, in which -- n may be of any integral type. drop :: Int -> [a] -> [a] -- | dropWhile p xs returns the suffix remaining after -- takeWhile p xs. -- --
--   >>> dropWhile (< 3) [1,2,3,4,5,1,2,3]
--   [3,4,5,1,2,3]
--   
--   >>> dropWhile (< 9) [1,2,3]
--   []
--   
--   >>> dropWhile (< 0) [1,2,3]
--   [1,2,3]
--   
dropWhile :: (a -> Bool) -> [a] -> [a] -- | iterate f x returns an infinite list of repeated -- applications of f to x: -- --
--   iterate f x == [x, f x, f (f x), ...]
--   
-- -- Note that iterate is lazy, potentially leading to thunk -- build-up if the consumer doesn't force each iterate. See -- iterate' for a strict variant of this function. -- --
--   >>> take 10 $ iterate not True
--   [True,False,True,False...
--   
--   >>> take 10 $ iterate (+3) 42
--   [42,45,48,51,54,57,60,63...
--   
iterate :: (a -> a) -> a -> [a] -- | repeat x is an infinite list, with x the -- value of every element. -- --
--   >>> take 20 $ repeat 17
--   [17,17,17,17,17,17,17,17,17...
--   
repeat :: a -> [a] -- | replicate n x is a list of length n with -- x the value of every element. It is an instance of the more -- general genericReplicate, in which n may be of any -- integral type. -- --
--   >>> replicate 0 True
--   []
--   
--   >>> replicate (-1) True
--   []
--   
--   >>> replicate 4 True
--   [True,True,True,True]
--   
replicate :: Int -> a -> [a] -- | reverse xs returns the elements of xs in -- reverse order. xs must be finite. -- --
--   >>> reverse []
--   []
--   
--   >>> reverse [42]
--   [42]
--   
--   >>> reverse [2,5,7]
--   [7,5,2]
--   
--   >>> reverse [1..]
--   * Hangs forever *
--   
reverse :: [a] -> [a] -- | <math>. scanl is similar to foldl, but returns a -- list of successive reduced values from the left: -- --
--   scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
--   
-- -- Note that -- --
--   last (scanl f z xs) == foldl f z xs
--   
-- --
--   >>> scanl (+) 0 [1..4]
--   [0,1,3,6,10]
--   
--   >>> scanl (+) 42 []
--   [42]
--   
--   >>> scanl (-) 100 [1..4]
--   [100,99,97,94,90]
--   
--   >>> scanl (\reversedString nextChar -> nextChar : reversedString) "foo" ['a', 'b', 'c', 'd']
--   ["foo","afoo","bafoo","cbafoo","dcbafoo"]
--   
--   >>> scanl (+) 0 [1..]
--   * Hangs forever *
--   
scanl :: (b -> a -> b) -> b -> [a] -> [b] -- | <math>. scanr is the right-to-left dual of scanl. -- Note that the order of parameters on the accumulating function are -- reversed compared to scanl. Also note that -- --
--   head (scanr f z xs) == foldr f z xs.
--   
-- --
--   >>> scanr (+) 0 [1..4]
--   [10,9,7,4,0]
--   
--   >>> scanr (+) 42 []
--   [42]
--   
--   >>> scanr (-) 100 [1..4]
--   [98,-97,99,-96,100]
--   
--   >>> scanr (\nextChar reversedString -> nextChar : reversedString) "foo" ['a', 'b', 'c', 'd']
--   ["abcdfoo","bcdfoo","cdfoo","dfoo","foo"]
--   
--   >>> force $ scanr (+) 0 [1..]
--   *** Exception: stack overflow
--   
scanr :: (a -> b -> b) -> b -> [a] -> [b] -- | 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]) -- | take n, applied to a list xs, returns the -- prefix of xs of length n, or xs itself if -- n >= length xs. -- --
--   >>> take 5 "Hello World!"
--   "Hello"
--   
--   >>> take 3 [1,2,3,4,5]
--   [1,2,3]
--   
--   >>> take 3 [1,2]
--   [1,2]
--   
--   >>> take 3 []
--   []
--   
--   >>> take (-1) [1,2]
--   []
--   
--   >>> take 0 [1,2]
--   []
--   
-- -- It is an instance of the more general genericTake, in which -- n may be of any integral type. take :: Int -> [a] -> [a] -- | takeWhile, applied to a predicate p and a list -- xs, returns the longest prefix (possibly empty) of -- xs of elements that satisfy p. -- --
--   >>> takeWhile (< 3) [1,2,3,4,1,2,3,4]
--   [1,2]
--   
--   >>> takeWhile (< 9) [1,2,3]
--   [1,2,3]
--   
--   >>> takeWhile (< 0) [1,2,3]
--   []
--   
takeWhile :: (a -> Bool) -> [a] -> [a] -- | unzip transforms a list of pairs into a list of first -- components and a list of second components. -- --
--   >>> unzip []
--   ([],[])
--   
--   >>> unzip [(1, 'a'), (2, 'b')]
--   ([1,2],"ab")
--   
unzip :: [(a, b)] -> ([a], [b]) -- | The unzip3 function takes a list of triples and returns three -- lists, analogous to unzip. -- --
--   >>> unzip3 []
--   ([],[],[])
--   
--   >>> unzip3 [(1, 'a', True), (2, 'b', False)]
--   ([1,2],"ab",[True,False])
--   
unzip3 :: [(a, b, c)] -> ([a], [b], [c]) -- | 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)] -- | <math>. zipWith generalises zip by zipping with -- the function given as the first argument, instead of a tupling -- function. -- --
--   zipWith (,) xs ys == zip xs ys
--   zipWith f [x1,x2,x3..] [y1,y2,y3..] == [f x1 y1, f x2 y2, f x3 y3..]
--   
-- -- For example, zipWith (+) is applied to two lists to -- produce the list of corresponding sums: -- --
--   >>> zipWith (+) [1, 2, 3] [4, 5, 6]
--   [5,7,9]
--   
-- -- zipWith is right-lazy: -- --
--   >>> 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] -- | The toEnum method restricted to the type Char. chr :: Int -> Char -- | raise a number to an integral power (^^) :: (Fractional a, Integral b) => a -> b -> a infixr 8 ^^ -- | 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 -- | lcm x y is the smallest positive integer that both -- x and y divide. lcm :: Integral a => a -> a -> a -- | Proxy is a type that holds no data, but has a phantom parameter -- of arbitrary type (or even kind). Its use is to provide type -- information, even though there is no value available of that type (or -- it may be too costly to create one). -- -- Historically, Proxy :: Proxy a is a safer -- alternative to the undefined :: a idiom. -- --
--   >>> Proxy :: Proxy (Void, Int -> Int)
--   Proxy
--   
-- -- Proxy can even hold types of higher kinds, -- --
--   >>> Proxy :: Proxy Either
--   Proxy
--   
-- --
--   >>> Proxy :: Proxy Functor
--   Proxy
--   
-- --
--   >>> Proxy :: Proxy complicatedStructure
--   Proxy
--   
data Proxy (t :: k) Proxy :: Proxy (t :: k) -- | 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 -- | 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]) -- | 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 -- |
--   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 -- | intercalate xs xss is equivalent to (concat -- (intersperse xs xss)). It inserts the list xs in -- between the lists in xss and concatenates the result. -- --
--   >>> intercalate ", " ["Lorem", "ipsum", "dolor"]
--   "Lorem, ipsum, dolor"
--   
intercalate :: [a] -> [[a]] -> [a] -- | <math>. The 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] -- | <math>. The isPrefixOf function takes two lists and -- returns True iff the first list is a prefix of the second. -- --
--   >>> "Hello" `isPrefixOf` "Hello World!"
--   True
--   
-- --
--   >>> "Hello" `isPrefixOf` "Wello Horld!"
--   False
--   
isPrefixOf :: Eq a => [a] -> [a] -> Bool -- | The sort function implements a stable sorting algorithm. It is -- a special case of sortBy, which allows the programmer to supply -- their own comparison function. -- -- Elements are arranged from lowest to highest, keeping duplicates in -- the order they appeared in the input. -- --
--   >>> sort [1,6,4,3,2,5]
--   [1,2,3,4,5,6]
--   
sort :: Ord a => [a] -> [a] -- | 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 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] -- | Map a function over all the elements of a container and concatenate -- the resulting lists. -- --

Examples

-- -- Basic usage: -- --
--   >>> concatMap (take 3) [[1..], [10..], [100..], [1000..]]
--   [1,2,3,10,11,12,100,101,102,1000,1001,1002]
--   
-- --
--   >>> concatMap (take 3) (Just [1..])
--   [1,2,3]
--   
concatMap :: Foldable t => (a -> [b]) -> t a -> [b] -- | The Const functor. newtype Const a (b :: k) Const :: a -> Const a (b :: k) [getConst] :: Const a (b :: k) -> a -- | Any type that you wish to throw or catch as an exception must be an -- instance of the Exception class. The simplest case is a new -- exception type directly below the root: -- --
--   data MyException = ThisException | ThatException
--       deriving Show
--   
--   instance Exception MyException
--   
-- -- The default method definitions in the Exception class do what -- we need in this case. You can now throw and catch -- ThisException and ThatException as exceptions: -- --
--   *Main> throw ThisException `catch` \e -> putStrLn ("Caught " ++ show (e :: MyException))
--   Caught ThisException
--   
-- -- In more complicated examples, you may wish to define a whole hierarchy -- of exceptions: -- --
--   ---------------------------------------------------------------------
--   -- Make the root exception type for all the exceptions in a compiler
--   
--   data SomeCompilerException = forall e . Exception e => SomeCompilerException e
--   
--   instance Show SomeCompilerException where
--       show (SomeCompilerException e) = show e
--   
--   instance Exception SomeCompilerException
--   
--   compilerExceptionToException :: Exception e => e -> SomeException
--   compilerExceptionToException = toException . SomeCompilerException
--   
--   compilerExceptionFromException :: Exception e => SomeException -> Maybe e
--   compilerExceptionFromException x = do
--       SomeCompilerException a <- fromException x
--       cast a
--   
--   ---------------------------------------------------------------------
--   -- Make a subhierarchy for exceptions in the frontend of the compiler
--   
--   data SomeFrontendException = forall e . Exception e => SomeFrontendException e
--   
--   instance Show SomeFrontendException where
--       show (SomeFrontendException e) = show e
--   
--   instance Exception SomeFrontendException where
--       toException = compilerExceptionToException
--       fromException = compilerExceptionFromException
--   
--   frontendExceptionToException :: Exception e => e -> SomeException
--   frontendExceptionToException = toException . SomeFrontendException
--   
--   frontendExceptionFromException :: Exception e => SomeException -> Maybe e
--   frontendExceptionFromException x = do
--       SomeFrontendException a <- fromException x
--       cast a
--   
--   ---------------------------------------------------------------------
--   -- Make an exception type for a particular frontend compiler exception
--   
--   data MismatchedParentheses = MismatchedParentheses
--       deriving Show
--   
--   instance Exception MismatchedParentheses where
--       toException   = frontendExceptionToException
--       fromException = frontendExceptionFromException
--   
-- -- We can now catch a MismatchedParentheses exception as -- MismatchedParentheses, SomeFrontendException or -- SomeCompilerException, but not other types, e.g. -- IOException: -- --
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: MismatchedParentheses))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeFrontendException))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeCompilerException))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: IOException))
--   *** Exception: MismatchedParentheses
--   
class (Typeable e, Show e) => Exception e toException :: Exception e => e -> SomeException fromException :: Exception e => SomeException -> Maybe e -- | Render this exception value in a human-friendly manner. -- -- Default implementation: show. displayException :: Exception e => e -> String -- | Pretty print a CallStack. prettyCallStack :: CallStack -> String -- | 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 -- | Return the current CallStack. -- -- Does *not* include the call-site of callStack. callStack :: HasCallStack => CallStack -- | Perform some computation without adding new entries to the -- CallStack. withFrozenCallStack :: HasCallStack => (HasCallStack => a) -> a -- | Identity functor and monad. (a non-strict monad) newtype Identity a Identity :: a -> Identity a [runIdentity] :: Identity a -> a -- | One or none. -- -- It is useful for modelling any computation that is allowed to fail. -- --

Examples

-- -- Using the Alternative instance of Except, the following -- functions: -- --
--   >>> canFail = throwError "it failed" :: Except String Int
--   
--   >>> final = return 42                :: Except String Int
--   
-- -- Can be combined by allowing the first function to fail: -- --
--   >>> runExcept $ canFail *> final
--   Left "it failed"
--   
--   >>> runExcept $ optional canFail *> final
--   Right 42
--   
optional :: Alternative f => f a -> f (Maybe a) -- | for is traverse with its arguments flipped. For a -- version that ignores the results see for_. for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b) -- | This generalizes the list-based filter function. filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a] -- | 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 -- | Extract the first element of the stream. head :: NonEmpty a -> a -- | 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] -- | 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 -- | If Void is uninhabited then any Functor that holds only -- values of type Void is holding no values. It is implemented in -- terms of fmap absurd. vacuous :: Functor f => f Void -> f a -- | Uninhabited data type data Void -- | 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 -- | 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 (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). liftM5 :: Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r -- | fix f is the least fixed point of the function -- f, i.e. the least defined x such that f x = -- x. -- -- For example, we can write the factorial function using direct -- recursion as -- --
--   >>> let fac n = if n <= 1 then 1 else n * fac (n-1) in fac 5
--   120
--   
-- -- This uses the fact that Haskell’s let introduces recursive -- bindings. We can rewrite this definition using fix, -- --
--   >>> fix (\rec n -> if n <= 1 then 1 else n * rec (n-1)) 5
--   120
--   
-- -- Instead of making a recursive call, we introduce a dummy parameter -- rec; when used within fix, this parameter then refers -- to fix’s argument, hence the recursion is reintroduced. fix :: (a -> a) -> a -- | 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) -- | Strict version of <$>. (<$!>) :: Monad m => (a -> b) -> m a -> m b infixl 4 <$!> -- | 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. -- -- '(bs >=> cs) a' can be understood as the -- do expression -- --
--   do b <- bs a
--      cs b
--   
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 >=> -- | Like foldM, but discards the result. foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m () -- | Repeat an action indefinitely. -- --

Examples

-- -- A common use of forever is to process input from network -- sockets, Handles, and channels (e.g. MVar and -- Chan). -- -- For example, here is how we might implement an echo server, -- using forever both to listen for client connections on a -- network socket and to echo client input on client connection handles: -- --
--   echoServer :: Socket -> IO ()
--   echoServer socket = forever $ do
--     client <- accept socket
--     forkFinally (echo client) (\_ -> hClose client)
--     where
--       echo :: Handle -> IO ()
--       echo client = forever $
--         hGetLine client >>= hPutStrLn client
--   
-- -- Note that "forever" isn't necessarily non-terminating. If the action -- is in a MonadPlus and short-circuits after some number -- of iterations. then forever actually returns -- mzero, effectively short-circuiting its caller. forever :: Applicative f => f a -> f b -- | 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]) -- | 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 -- | replicateM n act performs the action act -- n times, and then returns the list of results: -- --

Examples

-- --
--   >>> replicateM 3 (putStrLn "a")
--   a
--   a
--   a
--   
replicateM :: Applicative m => Int -> m a -> m [a] -- | Like replicateM, but discards the result. replicateM_ :: Applicative m => Int -> m a -> m () -- | The zipWithM function generalizes zipWith to arbitrary -- applicative functors. zipWithM :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m [c] -- | zipWithM_ is the extension of zipWithM which ignores the -- final result. zipWithM_ :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m () -- | Monads in which IO computations may be embedded. Any monad -- built by applying a sequence of monad transformers to the IO -- monad will be an instance of this class. -- -- Instances should satisfy the following laws, which state that -- liftIO is a transformer of monads: -- -- class Monad m => MonadIO (m :: Type -> Type) -- | Lift a computation from the IO monad. This allows us to run IO -- computations in any monadic stack, so long as it supports these kinds -- of operations (i.e. IO is the base monad for the stack). -- --

Example

-- --
--   import Control.Monad.Trans.State -- from the "transformers" library
--   
--   printState :: Show s => StateT s IO ()
--   printState = do
--     state <- get
--     liftIO $ print state
--   
-- -- Had we omitted liftIO, we would have ended up with -- this error: -- --
--   • Couldn't match type ‘IO’ with ‘StateT s IO’
--    Expected type: StateT s IO ()
--      Actual type: IO ()
--   
-- -- The important part here is the mismatch between StateT s IO -- () and IO (). -- -- Luckily, we know of a function that takes an IO a and -- returns an (m a): liftIO, enabling us to run -- the program and see the expected results: -- --
--   > evalStateT printState "hello"
--   "hello"
--   
--   > evalStateT printState 3
--   3
--   
liftIO :: MonadIO m => IO a -> m a -- | 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 () type Word62 = OddWord Word64 One One One One One Zero () type Word63 = OddWord Word64 One One One One One One () -- | 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 -- | The class of types that can be converted to a hash value. -- -- Minimal implementation: hashWithSalt. -- -- Note: the hash is not guaranteed to be stable across library -- versions, operating systems or architectures. For stable hashing use -- named hashes: SHA256, CRC32 etc. -- -- If you are looking for Hashable instance in time -- package, check time-compat class 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 -- | 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 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 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 -- | 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` -- | 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. newtype Option a Option :: Maybe a -> Option a [getOption] :: Option a -> Maybe a -- | Repeat a value n times. -- --
--   mtimesDefault n a = a <> a <> ... <> a  -- using <> (n-1) times
--   
-- -- Implemented using stimes and mempty. -- -- This is a suitable definition for an mtimes member of -- Monoid. mtimesDefault :: (Integral b, Monoid a) => b -> a -> a -- | A generalization of cycle to an arbitrary Semigroup. May -- fail to terminate for some values in some semigroups. cycle1 :: Semigroup m => m -> m -- | 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] -- | 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]) -- | The mapAccumR function behaves like a combination of -- fmap and foldr; it applies a function to each element of -- a structure, passing an accumulating parameter from right to left, and -- returning a final value of this accumulator together with the new -- structure. -- --

Examples

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

Examples

-- -- Basic usage: -- --
--   >>> mapAccumL (\a b -> (a + b, a)) 0 [1..10]
--   (55,[0,1,3,6,10,15,21,28,36,45])
--   
-- --
--   >>> mapAccumL (\a b -> (a <> show b, a)) "0" [1..5]
--   ("012345",["0","01","012","0123","01234"])
--   
mapAccumL :: Traversable t => (s -> a -> (s, b)) -> s -> t a -> (s, t b) -- | This function may be used as a value for foldMap in a -- Foldable instance. -- --
--   foldMapDefault f ≡ getConst . traverse (Const . f)
--   
foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m -- | This function may be used as a value for fmap in a -- Functor instance, provided that traverse is defined. -- (Using fmapDefault with a Traversable instance defined -- only by sequenceA will result in infinite recursion.) -- --
--   fmapDefault f ≡ runIdentity . traverse (Identity . f)
--   
fmapDefault :: Traversable t => (a -> b) -> t a -> t b -- | Lists, but with an Applicative functor based on zipping. newtype ZipList a ZipList :: [a] -> ZipList a [getZipList] :: ZipList a -> [a] -- | 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 &&& stdin :: Handle stderr :: Handle -- | Shared memory locations that support atomic memory transactions. data TVar a -- | A monad supporting atomic memory transactions. data STM a -- | 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 mutable variable in the IO monad data IORef a -- | Pretty print a SrcLoc. prettySrcLoc :: SrcLoc -> String -- | Right-to-left monadic fold over the elements of a structure. -- -- Given a structure t with elements (a, b, c, ..., x, -- y), the result of a fold with an operator function f is -- equivalent to: -- --
--   foldrM f z t = do
--       yy <- f y z
--       xx <- f x yy
--       ...
--       bb <- f b cc
--       aa <- f a bb
--       return aa -- Just @return z@ when the structure is empty
--   
-- -- For a Monad m, given two functions f1 :: a -> m b -- and f2 :: b -> m c, their Kleisli composition (f1 -- >=> f2) :: a -> m c is defined by: -- --
--   (f1 >=> f2) a = f1 a >>= f2
--   
-- -- Another way of thinking about foldrM is that it amounts to an -- application to z of a Kleisli composition: -- --
--   foldrM f z t = f y >=> f x >=> ... >=> f b >=> f a $ z
--   
-- -- The monadic effects of foldrM are sequenced from right to -- left, and e.g. folds of infinite lists will diverge. -- -- If at some step the bind operator (>>=) -- short-circuits (as with, e.g., mzero in a MonadPlus), -- the evaluated effects will be from a tail of the element sequence. If -- you want to evaluate the monadic effects in left-to-right order, or -- perhaps be able to short-circuit after an initial sequence of -- elements, you'll need to use foldlM instead. -- -- If the monadic effects don't short-circuit, the outermost application -- of f is to the leftmost element a, so that, ignoring -- effects, the result looks like a right fold: -- --
--   a `f` (b `f` (c `f` (... (x `f` (y `f` z))))).
--   
-- --

Examples

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

Examples

-- -- Basic usage: -- --
--   >>> let f a e = do { print e ; return $ e : a }
--   
--   >>> foldlM f [] [0..3]
--   0
--   1
--   2
--   3
--   [3,2,1,0]
--   
foldlM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | The transpose function transposes the rows and columns of its -- argument. For example, -- --
--   >>> transpose [[1,2,3],[4,5,6]]
--   [[1,4],[2,5],[3,6]]
--   
-- -- If some of the rows are shorter than the following rows, their -- elements are skipped: -- --
--   >>> transpose [[10,11],[20],[],[30,31,32]]
--   [[10,20,30],[11,31],[32]]
--   
transpose :: [[a]] -> [[a]] -- | <math>. The tails function returns all final segments of -- the argument, longest first. For example, -- --
--   >>> tails "abc"
--   ["abc","bc","c",""]
--   
-- -- Note that tails has the following strictness property: -- tails _|_ = _|_ : _|_ tails :: [a] -> [[a]] -- | The subsequences function returns the list of all subsequences -- of the argument. -- --
--   >>> subsequences "abc"
--   ["","a","b","ab","c","ac","bc","abc"]
--   
subsequences :: [a] -> [[a]] -- | Sort a list by comparing the results of a key function applied to each -- element. sortOn f is equivalent to sortBy (comparing -- f), but has the performance advantage of only evaluating -- f once for each element in the input list. This is called the -- decorate-sort-undecorate paradigm, or Schwartzian transform. -- -- Elements are arranged from lowest to highest, keeping duplicates in -- the order they appeared in the input. -- --
--   >>> sortOn fst [(2, "world"), (4, "!"), (1, "Hello")]
--   [(1,"Hello"),(2,"world"),(4,"!")]
--   
sortOn :: Ord b => (a -> b) -> [a] -> [a] -- | The permutations function returns the list of all permutations -- of the argument. -- --
--   >>> permutations "abc"
--   ["abc","bac","cba","bca","cab","acb"]
--   
permutations :: [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 genericTake function is an overloaded version of -- take, which accepts any Integral value as the number of -- elements to take. genericTake :: Integral i => i -> [a] -> [a] -- | The genericSplitAt function is an overloaded version of -- splitAt, which accepts any Integral value as the -- position at which to split. genericSplitAt :: Integral i => i -> [a] -> ([a], [a]) -- | The genericReplicate function is an overloaded version of -- replicate, which accepts any Integral value as the -- number of repetitions to make. genericReplicate :: Integral i => i -> a -> [a] -- | <math>. The genericLength function is an overloaded -- version of length. In particular, instead of returning an -- Int, it returns any type which is an instance of Num. It -- is, however, less efficient than length. -- --
--   >>> genericLength [1, 2, 3] :: Int
--   3
--   
--   >>> genericLength [1, 2, 3] :: Float
--   3.0
--   
genericLength :: Num i => [a] -> i -- | The 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] -- | Maybe monoid returning the rightmost non-Nothing value. -- -- Last a is isomorphic to Dual (First -- a), and thus to Dual (Alt Maybe a) -- --
--   >>> getLast (Last (Just "hello") <> Last Nothing <> Last (Just "world"))
--   Just "world"
--   
newtype Last a Last :: Maybe a -> Last a [getLast] :: Last a -> Maybe a -- | 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"
--   
newtype First a First :: Maybe a -> First a [getFirst] :: First a -> Maybe a -- | Monoid under addition. -- --
--   >>> getSum (Sum 1 <> Sum 2 <> mempty)
--   3
--   
newtype Sum a Sum :: a -> Sum a [getSum] :: Sum a -> a -- | Monoid under multiplication. -- --
--   >>> getProduct (Product 3 <> Product 4 <> mempty)
--   12
--   
newtype Product a Product :: a -> Product a [getProduct] :: Product a -> a -- | The monoid of endomorphisms under composition. -- --
--   >>> let computation = Endo ("Hello, " ++) <> Endo (++ "!")
--   
--   >>> appEndo computation "Haskell"
--   "Hello, Haskell!"
--   
newtype Endo a Endo :: (a -> a) -> Endo a [appEndo] :: Endo a -> a -> a -- | The dual of a Monoid, obtained by swapping the arguments of -- mappend. -- --
--   >>> getDual (mappend (Dual "Hello") (Dual "World"))
--   "WorldHello"
--   
newtype Dual a Dual :: a -> Dual a [getDual] :: Dual a -> a -- | Monoid under <|>. -- --
--   >>> getAlt (Alt (Just 12) <> Alt (Just 24))
--   Just 12
--   
-- --
--   >>> getAlt $ Alt Nothing <> Alt (Just 24)
--   Just 24
--   
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 -- | This is a valid definition of stimes for a Monoid. -- -- Unlike the default definition of stimes, it is defined for 0 -- and so it should be preferred where possible. stimesMonoid :: (Integral b, Monoid a) => b -> a -> a -- | This is a valid definition of stimes for an idempotent -- Semigroup. -- -- When x <> x = x, this definition should be preferred, -- because it works in <math> rather than <math>. stimesIdempotent :: Integral b => b -> a -> a -- | The Down type allows you to reverse sort order conveniently. A -- value of type Down a contains a value of type -- a (represented as Down a). -- -- If a has an Ord instance associated with it -- then comparing two values thus wrapped will give you the opposite of -- their normal sort order. This is particularly useful when sorting in -- generalised list comprehensions, as in: then sortWith by -- Down x. -- --
--   >>> compare True False
--   GT
--   
-- --
--   >>> compare (Down True) (Down False)
--   LT
--   
-- -- If a has a Bounded instance then the wrapped -- instance also respects the reversed ordering by exchanging the values -- of minBound and maxBound. -- --
--   >>> minBound :: Int
--   -9223372036854775808
--   
-- --
--   >>> minBound :: Down Int
--   Down 9223372036854775807
--   
-- -- All other instances of Down a behave as they do for -- a. newtype Down a Down :: a -> Down a [getDown] :: Down a -> a -- | This type represents unknown type-level natural numbers. data SomeNat SomeNat :: Proxy n -> SomeNat -- | Convert an integer into an unknown type-level natural. someNatVal :: Natural -> SomeNat natVal :: forall (n :: Nat) proxy. KnownNat n => proxy n -> Natural -- | 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] -- | 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 -- | See openFile data IOMode ReadMode :: IOMode WriteMode :: IOMode AppendMode :: IOMode ReadWriteMode :: IOMode underflowError :: 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 ratioZeroDenominatorError :: a ratioPrec1 :: Int ratioPrec :: Int overflowError :: a numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a] numericEnumFromThenTo :: (Ord a, Fractional a) => a -> a -> a -> [a] numericEnumFromThen :: Fractional a => a -> a -> [a] numericEnumFrom :: Fractional a => 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 notANumber :: Rational -- | Convert an Int into a Natural, throwing an underflow exception for -- negative values. naturalFromInt :: Int -> Natural integralEnumFromTo :: Integral a => a -> a -> [a] integralEnumFromThenTo :: Integral a => a -> a -> a -> [a] integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a] integralEnumFrom :: (Integral a, Bounded a) => a -> [a] infinity :: Rational divZeroError :: 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 (^^%^^) :: Integral a => Rational -> a -> Rational (^%^) :: Integral a => Rational -> a -> Rational boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a] boundedEnumFrom :: (Enum a, Bounded a) => a -> [a] -- | Case analysis for the Bool type. bool x y p -- evaluates to x when p is False, and evaluates -- to y when p is True. -- -- This is equivalent to if p then y else x; that is, one can -- think of it as an if-then-else construct with its arguments reordered. -- --

Examples

-- -- Basic usage: -- --
--   >>> bool "foo" "bar" True
--   "bar"
--   
--   >>> bool "foo" "bar" False
--   "foo"
--   
-- -- Confirm that bool x y p and if p then y else -- x are equivalent: -- --
--   >>> let p = True; x = "bar"; y = "foo"
--   
--   >>> bool x y p == if p then y else x
--   True
--   
--   >>> let p = False
--   
--   >>> bool x y p == if p then y else x
--   True
--   
bool :: a -> a -> Bool -> a -- | & 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 & -- | 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 <&> -- | 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 $> -- | Swap the components of a pair. swap :: (a, b) -> (b, 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] minInt :: Int maxInt :: Int -- | 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 <**> -- | 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 -- | Extract a list of call-sites from the CallStack. -- -- The list is ordered by most recent call. getCallStack :: CallStack -> [([Char], SrcLoc)] -- | This is a valid definition of stimes for an idempotent -- Monoid. -- -- When mappend x x = x, this definition should be preferred, -- because it works in <math> rather than <math> stimesIdempotentMonoid :: (Integral b, Monoid a) => b -> a -> a -- | The 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 class for types with a default value. class Default a -- | The default value for this type. def :: Default 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 $!! -- | The inverse of ExceptT. runExceptT :: ExceptT e m a -> m (Either e 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 -- | 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 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 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) -- | 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) -- | The (open) type family IntBaseType encodes type-level -- information about the value range of an integral type. -- -- This module also provides type family instances for the standard -- Haskell 2010 integral types (including Foreign.C.Types) as well -- as the Natural type. -- -- Here's a simple example for registering a custom type with the -- Data.IntCast facilities: -- --
--   -- user-implemented unsigned 4-bit integer
--   data Nibble = …
--   
--   -- declare meta-information
--   type instance IntBaseType Nibble = FixedWordTag 4
--   
--   -- user-implemented signed 7-bit integer
--   data MyInt7 = …
--   
--   -- declare meta-information
--   type instance IntBaseType MyInt7 = FixedIntTag 7
--   
-- -- The type-level predicate IsIntSubType provides a partial -- ordering based on the types above. See also intCast. type family IntBaseType a :: IntBaseTypeK -- | 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 -- | Retrieve the first value targeted by a Fold or Traversal -- (or Just the result from a Getter or Lens) into -- the current state. -- --
--   preuse = use . pre
--   
-- --
--   preuse :: MonadState s m => Getter s a     -> m (Maybe a)
--   preuse :: MonadState s m => Fold s a       -> m (Maybe a)
--   preuse :: MonadState s m => Lens' s a      -> m (Maybe a)
--   preuse :: MonadState s m => Iso' s a       -> m (Maybe a)
--   preuse :: MonadState s m => Traversal' s a -> m (Maybe a)
--   
preuse :: MonadState s m => Getting (First a) s a -> m (Maybe a) -- | Retrieve the first value targeted by a Fold or Traversal -- (or Just the result from a Getter or Lens). See -- also firstOf and ^?, which are similar with some subtle -- differences (explained below). -- --
--   listToMaybe . toListpreview folded
--   
-- --
--   preview = view . pre
--   
-- -- Unlike ^?, this function uses a MonadReader to read the -- value to be focused in on. This allows one to pass the value as the -- last argument by using the MonadReader instance for (->) -- s However, it may also be used as part of some deeply nested -- transformer stack. -- -- preview uses a monoidal value to obtain the result. This means -- that it generally has good performance, but can occasionally cause -- space leaks or even stack overflows on some data types. There is -- another function, firstOf, which avoids these issues at the -- cost of a slight constant performance cost and a little less -- flexibility. -- -- It may be helpful to think of preview as having one of the -- following more specialized types: -- --
--   preview :: Getter s a     -> s -> Maybe a
--   preview :: Fold s a       -> s -> Maybe a
--   preview :: Lens' s a      -> s -> Maybe a
--   preview :: Iso' s a       -> s -> Maybe a
--   preview :: Traversal' s a -> s -> Maybe a
--   
-- --
--   preview :: MonadReader s m => Getter s a     -> m (Maybe a)
--   preview :: MonadReader s m => Fold s a       -> m (Maybe a)
--   preview :: MonadReader s m => Lens' s a      -> m (Maybe a)
--   preview :: MonadReader s m => Iso' s a       -> m (Maybe a)
--   preview :: MonadReader s m => Traversal' s a -> m (Maybe a)
--   
preview :: MonadReader s m => Getting (First a) s a -> m (Maybe a) -- | A convenient infix (flipped) version of toListOf. -- --
--   >>> [[1,2],[3]]^..id
--   [[[1,2],[3]]]
--   
--   >>> [[1,2],[3]]^..traverse
--   [[1,2],[3]]
--   
--   >>> [[1,2],[3]]^..traverse.traverse
--   [1,2,3]
--   
-- --
--   >>> (1,2)^..both
--   [1,2]
--   
-- --
--   toList xs ≡ xs ^.. folded
--   (^..) ≡ flip toListOf
--   
-- --
--   (^..) :: s -> Getter s a     -> a :: s -> Fold s a       -> a :: s -> Lens' s a      -> a :: s -> Iso' s a       -> a :: s -> Traversal' s a -> a :: s -> Prism' s a     -> [a]
--   
(^..) :: s -> Getting (Endo [a]) s a -> [a] infixl 8 ^.. -- | Use the target of a Lens, Iso, or Getter in the -- current state, or use a summary of a Fold or Traversal -- that points to a monoidal value. -- --
--   >>> evalState (use _1) (a,b)
--   a
--   
-- --
--   >>> evalState (use _1) ("hello","world")
--   "hello"
--   
-- --
--   use :: MonadState s m             => Getter s a     -> m a
--   use :: (MonadState s m, Monoid r) => Fold s r       -> m r
--   use :: MonadState s m             => Iso' s a       -> m a
--   use :: MonadState s m             => Lens' s a      -> m a
--   use :: (MonadState s m, Monoid r) => Traversal' s r -> m r
--   
use :: MonadState s m => Getting a s a -> m a -- | View the value pointed to by a Getter, Iso or -- Lens or the result of folding over all the results of a -- Fold or Traversal that points at a monoidal value. -- --
--   view . toid
--   
-- --
--   >>> view (to f) a
--   f a
--   
-- --
--   >>> view _2 (1,"hello")
--   "hello"
--   
-- --
--   >>> view (to succ) 5
--   6
--   
-- --
--   >>> view (_2._1) ("hello",("world","!!!"))
--   "world"
--   
-- -- As view is commonly used to access the target of a -- Getter or obtain a monoidal summary of the targets of a -- Fold, It may be useful to think of it as having one of these -- more restricted signatures: -- --
--   view ::             Getter s a     -> s -> a
--   view :: Monoid m => Fold s m       -> s -> m
--   view ::             Iso' s a       -> s -> a
--   view ::             Lens' s a      -> s -> a
--   view :: Monoid m => Traversal' s m -> s -> m
--   
-- -- In a more general setting, such as when working with a Monad -- transformer stack you can use: -- --
--   view :: MonadReader s m             => Getter s a     -> m a
--   view :: (MonadReader s m, Monoid a) => Fold s a       -> m a
--   view :: MonadReader s m             => Iso' s a       -> m a
--   view :: MonadReader s m             => Lens' s a      -> m a
--   view :: (MonadReader s m, Monoid a) => Traversal' s a -> m a
--   
view :: MonadReader s m => Getting a s a -> m a -- | Access the 1st field of a tuple (and possibly change its type). -- --
--   >>> (1,2)^._1
--   1
--   
-- --
--   >>> _1 .~ "hello" $ (1,2)
--   ("hello",2)
--   
-- --
--   >>> (1,2) & _1 .~ "hello"
--   ("hello",2)
--   
-- --
--   >>> _1 putStrLn ("hello","world")
--   hello
--   ((),"world")
--   
-- -- This can also be used on larger tuples as well: -- --
--   >>> (1,2,3,4,5) & _1 +~ 41
--   (42,2,3,4,5)
--   
-- --
--   _1 :: Lens (a,b) (a',b) a a'
--   _1 :: Lens (a,b,c) (a',b,c) a a'
--   _1 :: Lens (a,b,c,d) (a',b,c,d) a a'
--   ...
--   _1 :: Lens (a,b,c,d,e,f,g,h,i) (a',b,c,d,e,f,g,h,i) a a'
--   
_1 :: Field1 s t a b => Lens s t a b -- | Access the 2nd field of a tuple. -- --
--   >>> _2 .~ "hello" $ (1,(),3,4)
--   (1,"hello",3,4)
--   
-- --
--   >>> (1,2,3,4) & _2 *~ 3
--   (1,6,3,4)
--   
-- --
--   >>> _2 print (1,2)
--   2
--   (1,())
--   
-- --
--   anyOf _2 :: (s -> Bool) -> (a, s) -> Bool
--   traverse . _2 :: (Applicative f, Traversable t) => (a -> f b) -> t (s, a) -> f (t (s, b))
--   foldMapOf (traverse . _2) :: (Traversable t, Monoid m) => (s -> m) -> t (b, s) -> m
--   
_2 :: Field2 s t a b => Lens s t a b -- | Access the 3rd field of a tuple. _3 :: Field3 s t a b => Lens s t a b -- | Access the 4th field of a tuple. _4 :: Field4 s t a b => Lens s t a b -- | Access the 5th field of a tuple. _5 :: Field5 s t a b => Lens s t a b -- | Replace the target of a Lens or all of the targets of a -- Setter or Traversal with a constant value. -- -- This is an infix version of set, provided for consistency with -- (.=). -- --
--   f <$ a ≡ mapped .~ f $ a
--   
-- --
--   >>> (a,b,c,d) & _4 .~ e
--   (a,b,c,e)
--   
-- --
--   >>> (42,"world") & _1 .~ "hello"
--   ("hello","world")
--   
-- --
--   >>> (a,b) & both .~ c
--   (c,c)
--   
-- --
--   (.~) :: Setter s t a b    -> b -> s -> t
--   (.~) :: Iso s t a b       -> b -> s -> t
--   (.~) :: Lens s t a b      -> b -> s -> t
--   (.~) :: Traversal s t a b -> b -> s -> t
--   
(.~) :: ASetter s t a b -> b -> s -> t infixr 4 .~ -- | Replace the target of a Lens or all of the targets of a -- Setter or Traversal with a constant value. -- --
--   (<$) ≡ set mapped
--   
-- --
--   >>> set _2 "hello" (1,())
--   (1,"hello")
--   
-- --
--   >>> set mapped () [1,2,3,4]
--   [(),(),(),()]
--   
-- -- Note: Attempting to set a Fold or Getter will -- fail at compile time with an relatively nice error message. -- --
--   set :: Setter s t a b    -> b -> s -> t
--   set :: Iso s t a b       -> b -> s -> t
--   set :: Lens s t a b      -> b -> s -> t
--   set :: Traversal s t a b -> b -> s -> t
--   
set :: ASetter s t a b -> b -> s -> t -- | Modify the target of a Lens or all the targets of a -- Setter or Traversal with a function. -- --
--   fmapover mapped
--   fmapDefaultover traverse
--   sets . overid
--   over . setsid
--   
-- -- Given any valid Setter l, you can also rely on the -- law: -- --
--   over l f . over l g = over l (f . g)
--   
-- -- e.g. -- --
--   >>> over mapped f (over mapped g [a,b,c]) == over mapped (f . g) [a,b,c]
--   True
--   
-- -- Another way to view over is to say that it transforms a -- Setter into a "semantic editor combinator". -- --
--   >>> over mapped f (Just a)
--   Just (f a)
--   
-- --
--   >>> over mapped (*10) [1,2,3]
--   [10,20,30]
--   
-- --
--   >>> over _1 f (a,b)
--   (f a,b)
--   
-- --
--   >>> over _1 show (10,20)
--   ("10",20)
--   
-- --
--   over :: Setter s t a b -> (a -> b) -> s -> t
--   over :: ASetter s t a b -> (a -> b) -> s -> t
--   
over :: ASetter s t a b -> (a -> b) -> s -> t -- | A Lens is actually a lens family as described in -- http://comonad.com/reader/2012/mirrored-lenses/. -- -- With great power comes great responsibility and a Lens is -- subject to the three common sense Lens laws: -- -- 1) You get back what you put in: -- --
--   view l (set l v s)  ≡ v
--   
-- -- 2) Putting back what you got doesn't change anything: -- --
--   set l (view l s) s  ≡ s
--   
-- -- 3) Setting twice is the same as setting once: -- --
--   set l v' (set l v s) ≡ set l v' s
--   
-- -- These laws are strong enough that the 4 type parameters of a -- Lens cannot vary fully independently. For more on how they -- interact, read the "Why is it a Lens Family?" section of -- http://comonad.com/reader/2012/mirrored-lenses/. -- -- There are some emergent properties of these laws: -- -- 1) set l s must be injective for every s This -- is a consequence of law #1 -- -- 2) set l must be surjective, because of law #2, which -- indicates that it is possible to obtain any v from some -- s such that set s v = s -- -- 3) Given just the first two laws you can prove a weaker form of law #3 -- where the values v that you are setting match: -- --
--   set l v (set l v s) ≡ set l v s
--   
-- -- Every Lens can be used directly as a Setter or -- Traversal. -- -- You can also use a Lens for Getting as if it were a -- Fold or Getter. -- -- Since every Lens is a valid Traversal, the -- Traversal laws are required of any Lens you create: -- --
--   l purepure
--   fmap (l f) . l g ≡ getCompose . l (Compose . fmap f . g)
--   
-- --
--   type Lens s t a b = forall f. Functor f => LensLike f s t a b
--   
type Lens s t a b = forall (f :: Type -> Type). Functor f => a -> f b -> s -> f t -- |
--   type Lens' = Simple Lens
--   
type Lens' s a = Lens s s a a -- | A Traversal can be used directly as a Setter or a -- Fold (but not as a Lens) and provides the ability to -- both read and update multiple fields, subject to some relatively weak -- Traversal laws. -- -- These have also been known as multilenses, but they have the signature -- and spirit of -- --
--   traverse :: Traversable f => Traversal (f a) (f b) a b
--   
-- -- and the more evocative name suggests their application. -- -- Most of the time the Traversal you will want to use is just -- traverse, but you can also pass any Lens or Iso -- as a Traversal, and composition of a Traversal (or -- Lens or Iso) with a Traversal (or Lens or -- Iso) using (.) forms a valid Traversal. -- -- The laws for a Traversal t follow from the laws for -- Traversable as stated in "The Essence of the Iterator Pattern". -- --
--   t purepure
--   fmap (t f) . t g ≡ getCompose . t (Compose . fmap f . g)
--   
-- -- One consequence of this requirement is that a Traversal needs -- to leave the same number of elements as a candidate for subsequent -- Traversal that it started with. Another testament to the -- strength of these laws is that the caveat expressed in section 5.5 of -- the "Essence of the Iterator Pattern" about exotic Traversable -- instances that traverse the same entry multiple times was -- actually already ruled out by the second law in that same paper! type Traversal s t a b = forall (f :: Type -> Type). Applicative f => a -> f b -> s -> f t -- |
--   type Traversal' = Simple Traversal
--   
type Traversal' s a = Traversal s s a a -- | Pretty-print a Lorentz contract into Michelson code. printLorentzContract :: Bool -> Contract cp st vd -> LText -- | Pretty-print a Haskell value as Michelson one. printLorentzValue :: NiceUntypedValue v => Bool -> v -> LText cdCompilationOptionsL :: Lens' (ContractData cp st vd) CompilationOptions cdCodeL :: forall cp st vd cp1. NiceParameterFull cp1 => Lens (ContractData cp st vd) (ContractData cp1 st vd) (ContractCode cp st) (ContractCode cp1 st) coStringTransformerL :: Lens' CompilationOptions (Bool, MText -> MText) coOptimizerConfL :: Lens' CompilationOptions (Maybe OptimizerConf) coBytesTransformerL :: Lens' CompilationOptions (Bool, ByteString -> ByteString) -- | Lorentz version of analyzer. analyzeLorentz :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> AnalyzerRes -- | Like interpretLorentzInstr, but works on singleton input and -- output stacks. interpretLorentzLambda :: (IsoValue inp, IsoValue out) => ContractEnv -> (IsNotInView => Fn inp out) -> inp -> Either (MichelsonFailureWithStack Void) out -- | Interpret a Lorentz instruction, for test purposes. Note that this -- does not run the optimizer. interpretLorentzInstr :: forall (inp :: [Type]) (out :: [Type]). (IsoValuesStack inp, IsoValuesStack out) => ContractEnv -> (IsNotInView => inp :-> out) -> Rec Identity inp -> Either (MichelsonFailureWithStack Void) (Rec Identity out) -- | Restrict type of Contract, ContractData or other similar -- type to have no views. noViews :: forall {k1} {k2} contract (cp :: k1) (st :: k2). contract cp st () -> contract cp st () -- | Version of setViews that accepts a Rec. -- -- May be useful if you have too many views or want to combine views -- sets. setViewsRec :: forall vd cp st. NiceViewsDescriptor vd => Rec (ContractView st) (RevealViews vd) -> ContractData cp st () -> ContractData cp st vd -- | Set all the contract's views. -- --
--   compileLorentzContract $
--     defaultContractData do
--       ...
--     & setViews
--       ( mkView "myView" () do
--           ...
--       , mkView "anotherView" Integer do
--           ...
--       )
--   
setViews :: forall vd cp st. (RecFromTuple (Rec (ContractView st) (RevealViews vd)), NiceViewsDescriptor vd) => IsoRecTuple (Rec (ContractView st) (RevealViews vd)) -> ContractData cp st () -> ContractData cp st vd -- | Compile a whole contract to Michelson. -- -- Note that compiled contract can be ill-typed in terms of Michelson -- code when some of the compilation options are used. However, -- compilation with defaultCompilationOptions should be valid. compileLorentzContract :: ContractData cp st vd -> Contract cp st vd -- | Compile contract with defaultCompilationOptions. defaultContractData :: (NiceParameterFull cp, NiceStorageFull st) => (IsNotInView => '[(cp, st)] :-> ContractOut st) -> ContractData cp st () -- | Construct a view. -- --
--   mkView @"add" @(Integer, Integer) do
--    car; unpair; add
--   
mkView :: forall (name :: Symbol) arg ret st. (KnownSymbol name, NiceViewable arg, NiceViewable ret, HasAnnotation arg, HasAnnotation ret, TypeHasDoc arg, TypeHasDoc ret) => ViewCode arg st ret -> ContractView st ('ViewTyInfo name arg ret) -- | Version of mkContract that accepts custom compilation options. mkContractWith :: (NiceParameterFull cp, NiceStorageFull st) => CompilationOptions -> ContractCode cp st -> Contract cp st () -- | Construct and compile Lorentz contract. -- -- Note that this accepts code with initial and final stacks unpaired for -- simplicity. mkContract :: (NiceParameterFull cp, NiceStorageFull st) => ContractCode cp st -> Contract cp st () -- | Construct and compile Lorentz contract. -- -- This is an alias for mkContract. defaultContract :: (NiceParameterFull cp, NiceStorageFull st) => (IsNotInView => '[(cp, st)] :-> ContractOut st) -> Contract cp st () -- | Compile Lorentz code, optionally running the optimizer, string and -- byte transformers. compileLorentzWithOptions :: forall (inp :: [Type]) (out :: [Type]). CompilationOptions -> (inp :-> out) -> Instr (ToTs inp) (ToTs out) -- | For use outside of Lorentz. Will use defaultCompilationOptions. compileLorentz :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> Instr (ToTs inp) (ToTs out) -- | Leave contract without any modifications. For testing purposes. intactCompilationOptions :: CompilationOptions -- | Runs Michelson optimizer with default config and does not touch -- strings and bytes. defaultCompilationOptions :: CompilationOptions -- | Options to control Lorentz to Michelson compilation. data CompilationOptions CompilationOptions :: Maybe OptimizerConf -> (Bool, MText -> MText) -> (Bool, ByteString -> ByteString) -> CompilationOptions -- | Config for Michelson optimizer. [coOptimizerConf] :: CompilationOptions -> Maybe OptimizerConf -- | Function to transform strings with. See -- transformStringsLorentz. [coStringTransformer] :: CompilationOptions -> (Bool, MText -> MText) -- | Function to transform byte strings with. See -- transformBytesLorentz. [coBytesTransformer] :: CompilationOptions -> (Bool, ByteString -> ByteString) -- | Code for a contract along with compilation options for the Lorentz -- compiler. -- -- It is expected that a Contract is one packaged entity, wholly -- controlled by its author. Therefore the author should be able to set -- all options that control contract's behavior. -- -- This helps ensure that a given contract will be interpreted in the -- same way in all environments, like production and testing. -- -- Raw ContractCode should not be used for distribution of -- contracts. data ContractData cp st vd ContractData :: ContractCode cp st -> Rec (ContractView st) (RevealViews vd) -> CompilationOptions -> ContractData cp st vd -- | The contract itself. [cdCode] :: ContractData cp st vd -> ContractCode cp st -- | Contract views. [cdViews] :: ContractData cp st vd -> Rec (ContractView st) (RevealViews vd) -- | General compilation options for the Lorentz compiler. [cdCompilationOptions] :: ContractData cp st vd -> CompilationOptions -- | Single contract view. data ContractView st (v :: ViewTyInfo) [ContractView] :: forall (name :: Symbol) arg ret st. (KnownSymbol name, NiceViewable arg, NiceViewable ret, HasAnnotation arg, HasAnnotation ret) => ViewCode arg st ret -> ContractView st ('ViewTyInfo name arg ret) -- | Note that calling given entrypoints involves constructing -- UParam. pbsUParam :: forall (ctorName :: Symbol). KnownSymbol ctorName => ParamBuildingStep -- | Make up UParam from ADT sum. -- -- Entry points template will consist of (constructorName, -- constructorFieldType) pairs. Each constructor is expected to have -- exactly one field. uparamFromAdt :: UParamLinearize up => up -> UParam (UParamLinearized up) -- | Like caseUParam, but accepts a tuple of clauses, not a -- Rec. 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 -- | Pattern-match on given UParam entries. -- -- You have to provide all case branches and a fallback action on case -- when entrypoint is not found. caseUParam :: forall (entries :: [EntrypointKind]) (inp :: [Type]) (out :: [Type]). (CaseUParam entries, RequireUniqueEntrypoints entries) => Rec (CaseClauseU inp out) entries -> UParamFallback inp out -> (UParam entries : inp) :-> out -- | Default implementation for UParamFallback, simply reports an -- error. uparamFallbackFail :: forall (inp :: [Type]) (out :: [Type]). UParamFallback inp out -- | Helper instruction which extracts content of UParam. unwrapUParam :: forall (entries :: [EntrypointKind]) (s :: [Type]). (UParam entries : s) :-> ((MText, ByteString) : s) -- | Construct a UParam safely. mkUParam :: forall a (name :: Symbol) (entries :: [EntrypointKind]). (NicePackedValue a, LookupEntrypoint name entries ~ a, RequireUniqueEntrypoints entries) => Label name -> a -> UParam entries -- | An entrypoint is described by two types: its name and type of -- argument. type EntrypointKind = (Symbol, Type) -- | A convenient alias for type-level name-something pair. type (n :: Symbol) ?: (a :: k) = '(n, a) -- | Encapsulates parameter for one of entry points. It keeps entrypoint -- name and corresponding argument serialized. -- -- In Haskell world, we keep an invariant of that contained value relates -- to one of entry points from entries list. newtype UParam (entries :: [EntrypointKind]) UnsafeUParam :: (MText, ByteString) -> UParam (entries :: [EntrypointKind]) -- | Pseudo value for UParam type variable. type SomeInterface = '[ '("SomeEntrypoints", Void)] -- | Homomorphic version of UParam, forgets the exact interface. type UParam_ = UParam SomeInterface -- | Get type of entrypoint argument by its name. type family LookupEntrypoint (name :: Symbol) (entries :: [EntrypointKind]) -- | Ensure that given entry points do no contain duplicated names. type family RequireUniqueEntrypoints (entries :: [EntrypointKind]) -- | This type can store any value that satisfies a certain constraint. data ConstrainedSome (c :: Type -> Constraint) [ConstrainedSome] :: forall (c :: Type -> Constraint) a. c a => a -> ConstrainedSome c -- | This class is needed to implement unpackUParam. class UnpackUParam (c :: Type -> Constraint) (entries :: [EntrypointKind]) -- | Turn UParam into a Haskell value. Since we don't know its type -- in compile time, we have to erase it using ConstrainedSome. The -- user of this function can require arbitrary constraint to hold -- (depending on how they want to use the result). unpackUParam :: UnpackUParam c entries => UParam entries -> Either EntrypointLookupError (MText, ConstrainedSome c) data EntrypointLookupError NoSuchEntrypoint :: MText -> EntrypointLookupError ArgumentUnpackFailed :: EntrypointLookupError -- | Implementations of some entry points. -- -- Note that this thing inherits properties of Rec, e.g. you can -- Data.Vinyl.Core.rappend implementations for two entrypoint -- sets when assembling scattered parts of a contract. type EntrypointsImpl (inp :: [Type]) (out :: [Type]) (entries :: [EntrypointKind]) = Rec CaseClauseU inp out entries -- | An action invoked when user-provided entrypoint is not found. type UParamFallback (inp :: [Type]) (out :: [Type]) = (MText, ByteString) : inp :-> out -- | Make up a "case" over entry points. class CaseUParam (entries :: [EntrypointKind]) -- | Constraint required by uparamFromAdt. type UParamLinearize p = (Generic p, GUParamLinearize Rep p) -- | Entry points template derived from given ADT sum. type UParamLinearized p = GUParamLinearized Rep p -- | Version of entryCase for contracts with recursive delegate -- parameter that needs to be flattened. Use it with EpdDelegate -- when you don't need hierarchical entrypoints in autodoc. You can also -- hide particular entrypoints with the first type parameter. Consider -- using entryCaseFlattened if you don't want to hide any -- entrypoints. -- --
--   entryCaseFlattenedHiding @'[Ep1, Ep2] ...
--   
entryCaseFlattenedHiding :: forall (heps :: [Symbol]) cp (out :: [Type]) (inp :: [Type]) clauses. (CaseTC cp out inp clauses, DocumentEntrypoints (FlattenedEntrypointsKindHiding heps) cp, HasEntrypoints (ParameterEntrypointsDerivation cp) cp heps) => IsoRecTuple clauses -> (cp : inp) :-> out -- | Version of entryCase_ for contracts with recursive delegate -- parameter that needs to be flattened. Use it with EpdDelegate -- when you don't need hierarchical entrypoints in autodoc. You can also -- hide particular entrypoints with the type parameter. Consider using -- entryCaseFlattened_ if you don't want to hide any entrypoints. entryCaseFlattenedHiding_ :: forall (heps :: [Symbol]) cp (out :: [Type]) (inp :: [Type]). (InstrCaseC cp, RMap (CaseClauses cp), DocumentEntrypoints (FlattenedEntrypointsKindHiding heps) cp, HasEntrypoints (ParameterEntrypointsDerivation cp) cp heps) => Rec (CaseClauseL inp out) (CaseClauses cp) -> (cp : inp) :-> out -- | Version of entryCase for contracts with recursive parameter -- that needs to be flattened. Use it with EpdRecursive when you -- don't need intermediary nodes in autodoc. entryCaseFlattened :: forall cp (out :: [Type]) (inp :: [Type]) clauses. (CaseTC cp out inp clauses, DocumentEntrypoints FlattenedEntrypointsKind cp) => IsoRecTuple clauses -> (cp : inp) :-> out -- | Version of entryCase_ for contracts with recursive parameter -- that needs to be flattened. Use it with EpdRecursive when you -- don't need intermediary nodes in autodoc. entryCaseFlattened_ :: forall cp (out :: [Type]) (inp :: [Type]). (InstrCaseC cp, RMap (CaseClauses cp), DocumentEntrypoints FlattenedEntrypointsKind cp) => Rec (CaseClauseL inp out) (CaseClauses cp) -> (cp : inp) :-> out -- | Version of entryCase_ for contracts with flat parameter. entryCaseSimple_ :: forall cp (out :: [Type]) (inp :: [Type]). (InstrCaseC cp, RMap (CaseClauses cp), DocumentEntrypoints PlainEntrypointsKind cp, RequireFlatParamEps cp) => Rec (CaseClauseL inp out) (CaseClauses cp) -> (cp : inp) :-> out -- | Whether finalizeParamCallingDoc has already been applied to -- these steps. areFinalizedParamBuildingSteps :: [ParamBuildingStep] -> Bool -- | Modify param building steps with respect to entrypoints that given -- parameter declares. -- -- Each contract with entrypoints should eventually call this function, -- otherwise, in case if contract uses built-in entrypoints feature, the -- resulting parameter building steps in the generated documentation will -- not consider entrypoints and thus may be incorrect. -- -- Calling this twice over the same code is also prohibited. -- -- This method is for internal use, if you want to apply it to a contract -- manually, use finalizeParamCallingDoc. finalizeParamCallingDoc' :: forall cp (inp :: [Type]) (out :: [Type]). (NiceParameterFull cp, HasCallStack) => Proxy cp -> (inp :-> out) -> inp :-> out -- | Wrapper for documenting single entrypoint which parameter isn't going -- to be unwrapped from some datatype. -- -- entryCase unwraps a datatype, however, sometimes we want to -- have entrypoint parameter to be not wrapped into some datatype. documentEntrypoint :: forall kind (epName :: Symbol) param (s :: [Type]) (out :: [Type]). (KnownSymbol epName, DocItem (DEntrypoint kind), NiceParameter param, TypeHasDoc param) => ((param : s) :-> out) -> (param : s) :-> out -- | Go over contract code and update every occurrence of -- DEntrypointArg documentation item, adding the given step to its -- "how to build parameter" description. clarifyParamBuildingSteps :: forall (inp :: [Type]) (out :: [Type]). ParamBuildingStep -> (inp :-> out) -> inp :-> out mkDEntrypointArgSimple :: (NiceParameter t, TypeHasDoc t) => DEntrypointArg mkDEpUType :: HasAnnotation t => Ty emptyDEpArg :: DEntrypointArg -- | Make a ParamBuildingStep that tells about wrapping an argument -- into a constructor with given name and uses given ParamBuilder -- as description of Michelson part. mkPbsWrapIn :: Text -> ParamBuilder -> ParamBuildingStep -- | Mark code as part of entrypoint with given name. -- -- This is automatically called at most of the appropriate situations, -- like entryCase calls. entrypointSection :: forall kind (i :: [Type]) (o :: [Type]). EntrypointKindHasDoc kind => Text -> Proxy kind -> (i :-> o) -> i :-> o -- | Default implementation of docItemToMarkdown for entrypoints. diEntrypointToMarkdown :: HeaderLevel -> DEntrypoint level -> Markdown -- | Pattern that checks whether given SomeDocItem hides -- DEntrypoint inside (of any entrypoint kind). -- -- In case a specific kind is necessary, use plain (cast -> Just -- DEntrypoint{..}) construction instead. pattern DEntrypointDocItem :: () => DEntrypoint kind -> SomeDocItem -- | Gathers information about single entrypoint. -- -- We assume that entry points might be of different kinds, which is -- designated by phantom type parameter. For instance, you may want to -- have several groups of entry points corresponding to various parts of -- a contract - specifying different kind type argument for each -- of those groups will allow you defining different DocItem -- instances with appropriate custom descriptions for them. data DEntrypoint kind DEntrypoint :: Text -> SubDoc -> DEntrypoint kind [depName] :: DEntrypoint kind -> Text [depSub] :: DEntrypoint kind -> SubDoc -- | Can be used to make a kind equivalent to some other kind; if changing -- this, entrypointKindPos and entrypointKindSectionName -- will be ignored. type family EntrypointKindOverride ep -- | Describes location of entrypoints of the given kind. -- -- All such entrypoints will be placed under the same "entrypoints" -- section, and this instance defines characteristics of this section. class Typeable ep => EntrypointKindHasDoc ep where { -- | Can be used to make a kind equivalent to some other kind; if changing -- this, entrypointKindPos and entrypointKindSectionName -- will be ignored. type family EntrypointKindOverride ep; type EntrypointKindOverride ep = ep; } -- | Implement this when specifying EntrypointKindOverride. This -- should never be normally used, but because MINIMAL pragma -- can't specify type families, we use this hack. -- -- Default implementation is a bottom (i.e. a runtime error). -- -- If implemented, it should be -- --
--   entrypointKindOverrideSpecified = Dict
--   
entrypointKindOverrideSpecified :: EntrypointKindHasDoc ep => Dict ((EntrypointKindOverride ep == ep) ~ 'False) -- | Position of the respective entrypoints section in the doc. This shares -- the same positions space with all other doc items. entrypointKindPos :: EntrypointKindHasDoc ep => Natural -- | Name of the respective entrypoints section. entrypointKindSectionName :: EntrypointKindHasDoc ep => Text -- | Description in the respective entrypoints section. entrypointKindSectionDescription :: EntrypointKindHasDoc ep => Maybe Markdown -- | Default value for DEntrypoint type argument. data PlainEntrypointsKind -- | Special entrypoint kind that flattens one level of recursive -- entrypoints. -- -- With EpdRecursive, intermediary nodes are hidden from -- documentation. -- -- With EpdDelegate, intermediary nodes will still be shown. -- -- Any entrypoints can be omitted from docs by listing those in the type -- parameter (which is especially helpful with EpdDelegate). -- -- For other entrypoint derivation strategies (e.g. EpdPlain), -- behaves like PlainEntrypointsKind (with the exception of hiding -- entrypoints from docs) -- -- If you have several levels of recursion, each level will need to have -- this kind. -- -- Note that list of entrypoints to be hidden is not checked by default. -- Use entryCaseFlattenedHiding to have a static check that -- entrypoints to be hidden do indeed exist. data FlattenedEntrypointsKindHiding (hiddenEntrypoints :: [Symbol]) -- | A convenience type synonym for FlattenedEntrypointsKindHiding -- not hiding any entrypoitns. type FlattenedEntrypointsKind = FlattenedEntrypointsKindHiding '[] :: [Symbol] -- | Describes the behaviour common for all entrypoints. -- -- For instance, if your contract runs some checks before calling any -- entrypoint, you probably want to wrap those checks into -- entrypointSection "Prior checks" (Proxy -- @CommonContractBehaviourKind). data CommonContractBehaviourKind -- | Describes the behaviour common for entrypoints of given kind. -- -- This has very special use cases, like contracts with mix of -- upgradeable and permanent entrypoints. data CommonEntrypointsBehaviourKind (kind :: k) -- | Inserts a reference to an existing entrypoint. -- -- This helps to avoid duplication in the generated documentation, in -- order not to overwhelm the reader. data DEntrypointReference DEntrypointReference :: Text -> Anchor -> DEntrypointReference -- | When describing the way of parameter construction - piece of -- incremental builder for this description. newtype ParamBuilder ParamBuilder :: (Markdown -> Markdown) -> ParamBuilder -- | Argument stands for previously constructed parameter piece, and -- returned value - a piece constructed after our step. [unParamBuilder] :: ParamBuilder -> Markdown -> Markdown data ParamBuildingDesc ParamBuildingDesc :: Markdown -> ParamBuilder -> ParamBuilder -> ParamBuildingDesc -- | Plain english description of this step. [pbdEnglish] :: ParamBuildingDesc -> Markdown -- | How to construct parameter in Haskell code. [pbdHaskell] :: ParamBuildingDesc -> ParamBuilder -- | How to construct parameter working on raw Michelson. [pbdMichelson] :: ParamBuildingDesc -> ParamBuilder -- | Describes a parameter building step. -- -- This can be wrapping into (Haskell) constructor, or a more complex -- transformation. data ParamBuildingStep -- | Wraps something into constructor with given name. Constructor should -- be the one which corresponds to an entrypoint defined via field -- annotation, for more complex cases use PbsCustom. PbsWrapIn :: Text -> ParamBuildingDesc -> ParamBuildingStep -- | Directly call an entrypoint marked with a field annotation. PbsCallEntrypoint :: EpName -> ParamBuildingStep -- | Other action. PbsCustom :: ParamBuildingDesc -> ParamBuildingStep -- | This entrypoint cannot be called, which is possible when an explicit -- default entrypoint is present. This is not a true entrypoint but just -- some intermediate node in or tree and neither it nor any of -- its parents are marked with a field annotation. -- -- It contains dummy ParamBuildingSteps which were assigned before -- entrypoints were taken into account. PbsUncallable :: [ParamBuildingStep] -> ParamBuildingStep -- | Entrypoint argument type in typed representation. data SomeEntrypointArg SomeEntrypointArg :: Proxy a -> SomeEntrypointArg -- | Describes argument of an entrypoint. data DEntrypointArg DEntrypointArg :: Maybe SomeEntrypointArg -> [ParamBuildingStep] -> DEntrypointArg -- | Argument of the entrypoint. Pass Nothing if no argument is -- required. [epaArg] :: DEntrypointArg -> Maybe SomeEntrypointArg -- | Describes a way to lift an entrypoint argument into full parameter -- which can be passed to the contract. -- -- Steps are supposed to be applied in the order opposite to one in which -- they are given. E.g. suppose that an entrypoint is called as Run -- (Service1 arg); then the first step (actual last) should describe -- wrapping into Run constructor, and the second step (actual -- first) should be about wrapping into Service1 constructor. [epaBuilding] :: DEntrypointArg -> [ParamBuildingStep] -- | Pick a type documentation from CtorField. class KnownSymbol con => DeriveCtorFieldDoc (con :: Symbol) (cf :: CtorField) deriveCtorFieldDoc :: DeriveCtorFieldDoc con cf => DEntrypointArg -- | Constraint for documentEntrypoints. type DocumentEntrypoints kind a = (Generic a, GDocumentEntrypoints BuildEPTree' a kind Rep a '[] :: [CaseClauseParam]) -- | Provides arror for convenient entrypoint documentation class EntryArrow (kind :: k) (name :: Symbol) body -- | Lift entrypoint implementation. -- -- Entrypoint names should go with "e" prefix. (#->) :: EntryArrow kind name body => (Label name, Proxy kind) -> body -> body type family RequireFlatParamEps cp type family RequireFlatEpDerivation (cp :: t) deriv -- | Version of stAlias adopted to labels. stNickname :: forall (name :: Symbol). Label name -> FieldRef (FieldAlias name) -- | Construct an alias at term level. -- -- This requires passing the alias via type annotation. stAlias :: forall {k} (alias :: k). FieldRef (FieldAlias alias) -- | Provides alternative variadic interface for deep entries access. -- -- Example: stToField (stNested #a #b #c) stNested :: StNestedImpl f SelfRef => f -- | An alias for SelfRef. -- -- Examples: -- --
--   >>> push 5 # stMem this -$ (mempty :: Map Integer MText)
--   False
--   
-- --
--   >>> stGetField this # pair -$ (5 :: Integer)
--   (5,5)
--   
this :: forall (p :: FieldRefTag). SelfRef p -- | Utility to create EntrypointsFields from an entrypoint name -- (epName) and an EntrypointLambda implementation. Note -- that you need to merge multiple of these (with <>) if -- your field contains more than one entrypoint lambda. mkStoreEp :: forall (epName :: Symbol) epParam epStore. Label epName -> EntrypointLambda epParam epStore -> EntrypointsField epParam epStore -- | Turn submap operations into operations on a part of the submap value. -- -- Normally, if you need this set of operations, it would be better to -- split your submap into several separate submaps, each operating with -- its own part of the value. This set of operations is pretty -- inefficient and exists only as a temporary measure, if due to -- historical reasons you have to leave storage format intact. -- -- This implementation puts no distinction between value == -- Nothing and value == Just defValue cases. Getters, when -- notice a value equal to the default value, report its absence. Setters -- tend to remove the value from submap when possible. -- -- LIso (Maybe value) value and LIso (Maybe subvalue) -- subvalue arguments describe how to get a value if it was absent -- in map and how to detect when it can be safely removed from map. -- -- Example of use: zoomStoreSubmapOps #mySubmap nonDefIso nonDefIso -- storeSubmapOps storeFieldOpsADT zoomStoreSubmapOps :: forall {k1} {k2} store (submapName :: k1) (nameInSubmap :: k2) key value subvalue. (NiceConstant value, NiceConstant subvalue, Dupable key, Dupable store) => FieldRef submapName -> LIso (Maybe value) value -> LIso (Maybe subvalue) subvalue -> StoreSubmapOps store submapName key value -> StoreFieldOps value nameInSubmap subvalue -> StoreSubmapOps store nameInSubmap key subvalue composeStoreEntrypointOps :: forall {k} store substore (nameInStore :: k) (epName :: Symbol) epParam epStore. (HasDupableGetters store, Dupable substore) => FieldRef nameInStore -> StoreFieldOps store nameInStore substore -> StoreEntrypointOps substore epName epParam epStore -> StoreEntrypointOps store epName epParam epStore -- | Chain implementations of two submap operations sets. Used to provide -- shortcut access to a nested submap. -- -- This is very inefficient since on each access to substore it has to be -- serialized/deserialized. Use this implementation only if due to -- historical reasons migrating storage is difficult. -- -- LIso (Maybe substore) substore argument describes how to get -- substore value if it was absent in map and how to detect when -- it can be safely removed. -- -- Example of use: sequenceStoreSubmapOps #mySubmap nonDefIso -- storeSubmapOps storeSubmapOps sequenceStoreSubmapOps :: forall {k1} {k2} store substore value (name :: k1) (subName :: k2) key1 key2. (NiceConstant substore, KnownValue value, Dupable (key1, key2), Dupable store) => FieldRef name -> LIso (Maybe substore) substore -> StoreSubmapOps store name key1 substore -> StoreSubmapOps substore subName key2 value -> StoreSubmapOps store subName (key1, key2) value -- | Chain implementations of field and submap operations. -- -- This requires Dupable substore for simplicity, in most cases -- it is possible to use a different chaining (nameInStore :-| mname -- :-| this) to avoid that constraint. If this constraint is still -- an issue, please create a ticket. composeStoreSubmapOps :: forall {k1} {k2} store substore (nameInStore :: k1) (mname :: k2) key value. (HasDupableGetters store, Dupable substore) => FieldRef nameInStore -> StoreFieldOps store nameInStore substore -> StoreSubmapOps substore mname key value -> StoreSubmapOps store mname key value -- | Chain two implementations of field operations. -- -- Suits for a case when your store does not contain its fields directly -- rather has a nested structure. composeStoreFieldOps :: forall {k1} {k2} substore (nameInStore :: k1) store (nameInSubstore :: k2) field. HasDupableGetters substore => FieldRef nameInStore -> StoreFieldOps store nameInStore substore -> StoreFieldOps substore nameInSubstore field -> StoreFieldOps store nameInSubstore field -- | Change submap operations so that they work on a modified value. mapStoreSubmapOpsValue :: forall {k} value1 value2 store (name :: k) key. (KnownValue value1, KnownValue value2) => LIso value1 value2 -> StoreSubmapOps store name key value1 -> StoreSubmapOps store name key value2 -- | Change submap operations so that they work on a modified key. mapStoreSubmapOpsKey :: forall {k} key2 key1 store (name :: k) value. Fn key2 key1 -> StoreSubmapOps store name key1 value -> StoreSubmapOps store name key2 value -- | Change field operations so that they work on a modified field. -- -- For instance, to go from StoreFieldOps Storage "name" Integer -- to StoreFieldOps Storage "name" (value :! Integer) you can -- use mapStoreFieldOps (namedIso #value) mapStoreFieldOps :: forall {k} field1 field2 store (name :: k). KnownValue field1 => LIso field1 field2 -> StoreFieldOps store name field1 -> StoreFieldOps store name field2 -- | Pretend that given StoreEntrypointOps implementation is made up -- for entrypoint with name desiredName, not its actual name. -- Logic of the implementation remains the same. -- -- See also storeSubmapOpsReferTo. storeEntrypointOpsReferTo :: forall (epName :: Symbol) store epParam epStore (desiredName :: Symbol). Label epName -> StoreEntrypointOps store epName epParam epStore -> StoreEntrypointOps store desiredName epParam epStore -- | Pretend that given StoreFieldOps implementation is made up for -- field with name desiredName, not its actual name. Logic of -- the implementation remains the same. -- -- See also storeSubmapOpsReferTo. storeFieldOpsReferTo :: forall {k1} {k2} (name :: k1) storage field (desiredName :: k2). FieldRef name -> StoreFieldOps storage name field -> StoreFieldOps storage desiredName field -- | Pretend that given StoreSubmapOps implementation is made up for -- submap with name desiredName, not its actual name. Logic of -- the implementation remains the same. -- -- Use case: imagine that your code requires access to submap named -- X, but in your storage that submap is called Y. Then -- you implement the instance which makes X refer to Y: -- --
--   instance StoreHasSubmap Store X Key Value where
--     storeSubmapOps = storeSubmapOpsReferTo #Y storeSubmapOpsForY
--   
storeSubmapOpsReferTo :: forall {k1} {k2} (name :: k1) storage key value (desiredName :: k2). FieldRef name -> StoreSubmapOps storage name key value -> StoreSubmapOps storage desiredName key value -- | Implementation of StoreHasEntrypoint for a data type which has -- an instance of StoreHasEntrypoint inside. For instance, it can -- be used for top-level storage. storeEntrypointOpsDeeper :: forall store (nameInStore :: Symbol) substore (epName :: Symbol) epParam epStore. (HasFieldOfType store nameInStore substore, StoreHasEntrypoint substore epName epParam epStore, HasDupableGetters store, Dupable substore) => FieldRef nameInStore -> StoreEntrypointOps store epName epParam epStore -- | Implementation of StoreHasSubmap for a data type which has an -- instance of StoreHasSubmap inside. For instance, it can be used -- for top-level storage. storeSubmapOpsDeeper :: forall {k} storage (bigMapPartName :: Symbol) fields key value (mname :: k). (HasFieldOfType storage bigMapPartName fields, StoreHasSubmap fields SelfRef key value, HasDupableGetters storage, Dupable fields) => FieldRef bigMapPartName -> StoreSubmapOps storage mname key value -- | Implementation of StoreHasField for a data type which has an -- instance of StoreHasField inside. For instance, it can be used -- for top-level storage. storeFieldOpsDeeper :: forall {k} storage (fieldsPartName :: Symbol) fields (fname :: k) ftype. (HasFieldOfType storage fieldsPartName fields, StoreHasField fields fname ftype, HasDupableGetters fields) => FieldRef fieldsPartName -> StoreFieldOps storage fname ftype -- | Implementation of StoreHasEntrypoint for a datatype that has a -- StoreHasSubmap that contains the entrypoint and a -- StoreHasField for the field such entrypoint operates on. 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 -- | Implementation of StoreHasEntrypoint for a datatype that has a -- StoreHasField for an EntrypointsField that contains the -- entrypoint and a StoreHasField for the field such entrypoint -- operates on. 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 -- | Implementation of StoreHasEntrypoint for a datatype keeping a -- pack of fields, among which one contains the entrypoint and another is -- what such entrypoint operates on. 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 -- | Implementation of StoreHasField for case of datatype keeping a -- pack of fields. storeFieldOpsADT :: forall dt (fname :: Symbol) ftype. HasFieldOfType dt fname ftype => StoreFieldOps dt fname ftype -- | Update the sub-storage that the entrypoint operates on. stSetEpStore :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (epStore : (store : s)) :-> (store : s) -- | Get the sub-storage that the entrypoint operates on, preserving the -- storage itself on the stack. stGetEpStore :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). (StoreHasEntrypoint store epName epParam epStore, Dupable store) => Label epName -> (store : s) :-> (epStore : (store : s)) -- | Pick the sub-storage that the entrypoint operates on. stToEpStore :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (epStore : s) -- | Stores the entrypoint lambda in the storage. Fails if already set. stSetEpLambda :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). (StoreHasEntrypoint store epName epParam epStore, HasDupableGetters store) => Label epName -> (EntrypointLambda epParam epStore : (store : s)) :-> (store : s) -- | Get stored entrypoint lambda, preserving the storage itself on the -- stack. stGetEpLambda :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). (StoreHasEntrypoint store epName epParam epStore, Dupable store) => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : (store : s)) -- | Pick stored entrypoint lambda. stToEpLambda :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). StoreHasEntrypoint store epName epParam epStore => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : s) -- | Extracts and executes the epName entrypoint lambda from -- storage, returing the updated full storage (store) and the -- produced Operations. stEntrypoint :: forall store (epName :: Symbol) epParam epStore (s :: [Type]). (StoreHasEntrypoint store epName epParam epStore, Dupable store) => Label epName -> (epParam : (store : s)) :-> (([Operation], store) : s) -- | Atomically get and update a value in storage. stGetAndUpdate :: forall {k} store (mname :: k) key value (s :: [Type]). StoreHasSubmap store mname key value => FieldRef mname -> (key : (Maybe value : (store : s))) :-> (Maybe value : (store : s)) -- | Update storage field. stSetField :: forall {k} store (fname :: k) ftype (s :: [Type]). StoreHasField store fname ftype => FieldRef fname -> (ftype : (store : s)) :-> (store : s) -- | Version of stToFieldNamed that preserves the storage on stack. stGetFieldNamed :: forall {k} store (fname :: k) ftype (s :: [Type]). (StoreHasField store fname ftype, FieldRefHasFinalName fname, Dupable ftype, HasDupableGetters store) => FieldRef fname -> (store : s) :-> ((FieldRefFinalName fname :! ftype) : (store : s)) -- | Pick storage field retaining a name label attached. -- -- For complex refs this tries to attach the immediate name of the -- referred field. stToFieldNamed :: forall {k} store (fname :: k) ftype (s :: [Type]). (StoreHasField store fname ftype, FieldRefHasFinalName fname) => FieldRef fname -> (store : s) :-> ((FieldRefFinalName fname :! ftype) : s) -- | Get storage field, preserving the storage itself on stack. stGetField :: forall {k} store (fname :: k) ftype (s :: [Type]). (StoreHasField store fname ftype, Dupable ftype, HasDupableGetters store) => FieldRef fname -> (store : s) :-> (ftype : (store : s)) -- | Pick storage field. stToField :: forall {k} store (fname :: k) ftype (s :: [Type]). StoreHasField store fname ftype => FieldRef fname -> (store : s) :-> (ftype : s) -- | Simplified version of sopSetFieldOpen where res is -- ftype. sopSetField :: forall {k} store (fname :: k) ftype (s :: [Type]). StoreFieldOps store fname ftype -> FieldRef fname -> (ftype : (store : s)) :-> (store : s) -- | Simplified version of sopGetFieldOpen where res is -- ftype. sopGetField :: forall {k} ftype store (fname :: k) (s :: [Type]). (Dupable ftype, HasDupableGetters store) => StoreFieldOps store fname ftype -> FieldRef fname -> (store : s) :-> (ftype : (store : s)) -- | Convert a label to FieldRef, useful for compatibility with -- other interfaces. fieldNameFromLabel :: forall (n :: Symbol). Label n -> FieldSymRef n -- | Convert a symbolic FieldRef to a label, useful for -- compatibility with other interfaces. fieldNameToLabel :: forall (n :: Symbol). FieldSymRef n -> Label n -- | Open kind for various field references. -- -- The simplest field reference could be Label, pointing to a -- field by its name, but we also support more complex scenarios like -- deep fields identifiers. type FieldRefKind = FieldRefTag -> Type data FieldRefTag type family FieldRefObject (ty :: k) = (fr :: FieldRefKind) | fr -> k ty -- | For a type-level field reference - an associated term-level -- representation. -- -- This is similar to singletons Sing + SingI -- pair but has small differences: -- -- class KnownFieldRef (ty :: k) where { type family FieldRefObject (ty :: k) = (fr :: FieldRefKind) | fr -> k ty; } mkFieldRef :: forall (p :: FieldRefTag). KnownFieldRef ty => FieldRefObject ty p -- | Some kind of reference to a field. -- -- The idea behind this type is that in trivial case (name :: -- Symbol) it can be instantiated with a mere label, but it is -- generic enough to allow complex field references as well. type FieldRef (name :: k) = FieldRefObject name 'FieldRefTag -- | The simplest field reference - just a name. Behaves similarly to -- Label. data FieldName (n :: Symbol) (p :: FieldRefTag) -- | Version of FieldRef restricted to symbolic labels. -- --
--   FieldSymRef name ≡ FieldName name 'FieldRefTag
--   
type FieldSymRef (name :: Symbol) = FieldRef name type family FieldRefFinalName (fr :: k) :: Symbol -- | Provides access to the direct name of the referred field. -- -- This is used in stToFieldNamed. class FieldRefHasFinalName (fr :: k) where { type family FieldRefFinalName (fr :: k) :: Symbol; } fieldRefFinalName :: FieldRefHasFinalName fr => FieldRef fr -> Label (FieldRefFinalName fr) -- | Datatype containing the full implementation of StoreHasField -- typeclass. -- -- We use this grouping because in most cases the implementation will be -- chosen among the default ones, and initializing all methods at once is -- simpler and more consistent. (One can say that we are trying to -- emulate the DerivingVia extension.) data StoreFieldOps store (fname :: k) ftype StoreFieldOps :: (forall (s :: [Type]). () => FieldRef fname -> (store : s) :-> (ftype : s)) -> (forall res (s :: [Type]). HasDupableGetters store => ('[ftype] :-> '[res, ftype]) -> ('[ftype] :-> '[res]) -> FieldRef fname -> (store : s) :-> (res : (store : s))) -> (forall new (s :: [Type]). () => ('[new, ftype] :-> '[ftype]) -> FieldRef fname -> (new : (store : s)) :-> (store : s)) -> StoreFieldOps store (fname :: k) ftype [sopToField] :: StoreFieldOps store (fname :: k) ftype -> forall (s :: [Type]). () => FieldRef fname -> (store : s) :-> (ftype : s) -- | See getFieldOpen for explanation of the signature. [sopGetFieldOpen] :: StoreFieldOps store (fname :: k) ftype -> forall res (s :: [Type]). HasDupableGetters store => ('[ftype] :-> '[res, ftype]) -> ('[ftype] :-> '[res]) -> FieldRef fname -> (store : s) :-> (res : (store : s)) -- | See setFieldOpen for explanation of the signature. [sopSetFieldOpen] :: StoreFieldOps store (fname :: k) ftype -> forall new (s :: [Type]). () => ('[new, ftype] :-> '[ftype]) -> FieldRef fname -> (new : (store : s)) :-> (store : s) -- | Provides operations on fields for storage. class StoreHasField store (fname :: k) ftype | store fname -> ftype storeFieldOps :: StoreHasField store fname ftype => StoreFieldOps store fname ftype -- | Datatype containing the full implementation of StoreHasSubmap -- typeclass. -- -- We use this grouping because in most cases the implementation will be -- chosen among the default ones, and initializing all methods at once is -- simpler and more consistent. (One can say that we are trying to -- emulate the DerivingVia extension.) data StoreSubmapOps store (mname :: k) key value StoreSubmapOps :: (forall (s :: [Type]). () => FieldRef mname -> (key : (store : s)) :-> (Bool : s)) -> (forall (s :: [Type]). KnownValue value => FieldRef mname -> (key : (store : s)) :-> (Maybe value : s)) -> (forall (s :: [Type]). () => FieldRef mname -> (key : (Maybe value : (store : s))) :-> (store : s)) -> (forall (s :: [Type]). () => FieldRef mname -> (key : (Maybe value : (store : s))) :-> (Maybe value : (store : s))) -> (forall (s :: [Type]). () => FieldRef mname -> (key : (store : s)) :-> (store : s)) -> (forall (s :: [Type]). () => FieldRef mname -> (key : (value : (store : s))) :-> (store : s)) -> StoreSubmapOps store (mname :: k) key value [sopMem] :: StoreSubmapOps store (mname :: k) key value -> forall (s :: [Type]). () => FieldRef mname -> (key : (store : s)) :-> (Bool : s) [sopGet] :: StoreSubmapOps store (mname :: k) key value -> forall (s :: [Type]). KnownValue value => FieldRef mname -> (key : (store : s)) :-> (Maybe value : s) [sopUpdate] :: StoreSubmapOps store (mname :: k) key value -> forall (s :: [Type]). () => FieldRef mname -> (key : (Maybe value : (store : s))) :-> (store : s) [sopGetAndUpdate] :: StoreSubmapOps store (mname :: k) key value -> forall (s :: [Type]). () => FieldRef mname -> (key : (Maybe value : (store : s))) :-> (Maybe value : (store : s)) [sopDelete] :: StoreSubmapOps store (mname :: k) key value -> forall (s :: [Type]). () => FieldRef mname -> (key : (store : s)) :-> (store : s) [sopInsert] :: StoreSubmapOps store (mname :: k) key value -> forall (s :: [Type]). () => FieldRef mname -> (key : (value : (store : s))) :-> (store : s) -- | Provides operations on submaps of storage. class StoreHasSubmap store (mname :: k) key value | store mname -> key value storeSubmapOps :: StoreHasSubmap store mname key value => StoreSubmapOps store mname key value -- | Type synonym for a Lambda that can be used as an entrypoint type EntrypointLambda param store = Lambda (param, store) ([Operation], store) -- | Type synonym of a BigMap mapping MText (entrypoint -- names) to EntrypointLambda. -- -- This is useful when defining instances of StoreHasEntrypoint as -- a storage field containing one or more entrypoints (lambdas) of the -- same type. type EntrypointsField param store = BigMap MText EntrypointLambda param store -- | Datatype containing the full implementation of -- StoreHasEntrypoint typeclass. -- -- We use this grouping because in most cases the implementation will be -- chosen among the default ones, and initializing all methods at once is -- simpler and more consistent. (One can say that we are trying to -- emulate the DerivingVia extension.) data StoreEntrypointOps store (epName :: Symbol) epParam epStore StoreEntrypointOps :: (forall (s :: [Type]). () => Label epName -> (store : s) :-> (EntrypointLambda epParam epStore : s)) -> (forall (s :: [Type]). HasDupableGetters store => 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]). HasDupableGetters store => 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) -- | Provides operations on stored entrypoints. -- -- store is the storage containing both the entrypoint -- epName (note: it has to be in a BigMap to take -- advantage of lazy evaluation) and the epStore field this -- operates on. class StoreHasEntrypoint store (epName :: Symbol) epParam epStore | store epName -> epParam epStore storeEpOps :: StoreHasEntrypoint store epName epParam epStore => StoreEntrypointOps store epName epParam epStore -- | Refer to a nested entry in storage. -- -- Example: stToField (#a :-| #b) fetches field b in -- the type under field a. -- -- If not favouring this name much, you can try an alias from -- Lorentz.StoreClass.Extra. data ( (l :: k1) :-| (r :: k2) ) (p :: FieldRefTag) (:-|) :: FieldRef l -> FieldRef r -> (:-|) (l :: k1) (r :: k2) (p :: FieldRefTag) infixr 8 :-| infixr 8 :-| -- | Refer to no particular field, access itself. data SelfRef (p :: FieldRefTag) SelfRef :: SelfRef (p :: FieldRefTag) -- | Alias for a field reference. -- -- This allows creating _custom_ field references; you will have to -- define the respective StoreHasField and StoreHasSubmap -- instances manually. Since this type occupies a different "namespace" -- than string labels and :-|, no overlappable instances will be -- necessary. -- -- Example: -- --
--   -- Shortcut for a deeply nested field X
--   data FieldX
--   
--   instance StoreHasField Storage (FieldAlias FieldX) Integer where
--     ...
--   
--   accessX = stToField (stAlias @FieldX)
--   
-- -- Note that alias type argument allows instantiations of any -- kind. data FieldAlias (alias :: k) (p :: FieldRefTag) -- | Kind-restricted version of FieldAlias to work solely with -- string labels. type FieldNickname (alias :: Symbol) = FieldAlias alias -- | Indicates a submap with given key and value types. data (k2 :: k) ~> (v :: k1) infix 9 ~> -- | Indicates a stored entrypoint with the given param and -- store types. data (param :: k) ::-> (store :: k1) infix 9 ::-> -- | Concise way to write down constraints with expected content of a -- storage. -- -- Use it like follows: -- --
--   type StorageConstraint store = StorageContains store
--     [ "fieldInt" := Int
--     , "fieldNat" := Nat
--     , "epsToNat" := Int ::-> Nat
--     , "balances" := Address ~> Int
--     ]
--   
-- -- Note that this won't work with complex field references, they have to -- be included using e.g. StoreHasField manually. type family StorageContains store (content :: [NamedField]) -- | Handlers for most common errors defined in Lorentz. baseErrorDocHandlers :: [NumericErrorDocHandler] -- | Handler for VoidResult. voidResultDocHandler :: NumericErrorDocHandler -- | Handler for all CustomErrors. customErrorDocHandler :: NumericErrorDocHandler -- | Extended version of applyErrorTagToErrorsDoc which accepts -- error handlers. -- -- In most cases that function should be enough for your purposes, but it -- uses a fixed set of base handlers which may be not enough in case when -- you define your own errors. In this case define and pass all the -- necessary handlers to this function. -- -- It fails with error if some of the errors used in the contract -- cannot be handled with given handlers. applyErrorTagToErrorsDocWith :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => [NumericErrorDocHandler] -> ErrorTagMap -> (inp :-> out) -> inp :-> out -- | Modify documentation generated for given code so that all -- CustomError mention not their textual error tag rather -- respective numeric one from the given map. -- -- If some documented error is not present in the map, it remains -- unmodified. This function may fail with error if contract uses -- some uncommon errors, see applyErrorTagToErrorsDocWith for -- details. applyErrorTagToErrorsDoc :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => ErrorTagMap -> (inp :-> out) -> inp :-> out -- | Adds a section which explains error tag mapping. data DDescribeErrorTagMap DDescribeErrorTagMap :: Text -> DDescribeErrorTagMap -- | Describes where the error tag map is defined in Haskell code. [detmSrcLoc] :: DDescribeErrorTagMap -> Text -- | Errors for NumericErrorDocHandler data NumericErrorDocHandlerError -- | Handler which changes documentation for one particular error type. data NumericErrorDocHandler -- | Some error with a numeric tag attached. data NumericErrorWrapper (numTag :: Nat) err voidResultTag :: MText -- | view type synonym as described in A1. data View_ a r -- | void type synonym as described in A1. data Void_ a b -- | Newtype over void result type used in tests to distinguish successful -- void result from other errors. -- -- Usage example: lExpectFailWith (== VoidResult roleMaster)` -- -- This error is special - it can contain arguments of different types -- depending on entrypoint which raises it. data VoidResult r class NonZero t -- | Unwrap a constructor with the given name. Useful for sum types. -- --
--   >>> unsafeUnwrap_ @TestSum #cTestSumA -$? TestSumA 42
--   Right 42
--   
--   >>> first pretty $ unsafeUnwrap_ @TestSum #cTestSumA -$? TestSumB (False, ())
--   Left "Reached FAILWITH instruction with \"BadCtor\" at Error occurred on line 1 char 1."
--   
unsafeUnwrap_ :: forall dt (name :: Symbol) (st :: [Type]). InstrUnwrapC dt name => Label name -> (dt : st) :-> (CtorOnlyField name dt : st) -- | Wrap entry in single-field constructor. Useful for sum types. -- --
--   >>> wrapOne @TestSum #cTestSumA -$ 42
--   TestSumA 42
--   
wrapOne :: forall dt (name :: Symbol) (st :: [Type]). InstrWrapOneC dt name => Label name -> (CtorOnlyField name dt : st) :-> (dt : st) -- | Wrap entry in constructor. Useful for sum types. -- --
--   >>> wrap_ @TestSum #cTestSumB -$ (False, ())
--   TestSumB (False,())
--   
wrap_ :: forall dt (name :: Symbol) (st :: [Type]). InstrWrapC dt name => Label name -> AppendCtorField (GetCtorField dt name) st :-> (dt : st) -- | Lift an instruction to field constructor. fieldCtor :: forall (st :: [Type]) f. HasCallStack => (st :-> (f : st)) -> FieldConstructor st f -- | Decompose a complex object into its fields -- --
--   >>> deconstruct @TestProduct # constructStack @TestProduct -$ testProduct
--   TestProduct {fieldA = True, fieldB = 42, fieldC = ()}
--   
deconstruct :: forall dt (fields :: [Type]) (st :: [Type]). (InstrDeconstructC dt (ToTs st), fields ~ GFieldTypes (Rep dt) ('[] :: [Type]), (ToTs fields ++ ToTs st) ~ ToTs (fields ++ st)) => (dt : st) :-> (fields ++ st) -- | Construct an object from fields on the stack. -- --
--   >>> constructStack @TestProduct -$ True ::: 42 ::: ()
--   TestProduct {fieldA = True, fieldB = 42, fieldC = ()}
--   
constructStack :: forall dt (fields :: [Type]) (st :: [Type]). (InstrConstructC dt, fields ~ ConstructorFieldTypes dt, (ToTs fields ++ ToTs st) ~ ToTs (fields ++ st)) => (fields ++ st) :-> (dt : st) -- | "Open" version of setField, an advanced method suitable for -- chaining setters. -- -- It accepts a continuation accepting the field extracted for the update -- and the new value that is being set. Normally this continuation is -- just setField for some nested field. setFieldOpen :: forall dt (name :: Symbol) new (st :: [Type]). InstrSetFieldC dt name => ('[new, GetFieldType dt name] :-> '[GetFieldType dt name]) -> Label name -> (new : (dt : st)) :-> (dt : st) -- | "Open" version of getField, an advanced method suitable for -- chaining getters. -- -- It accepts two continuations accepting the extracted field, one that -- leaves the field on stack (and does a duplication of res -- inside) and another one that consumes the field. Normally these are -- just getField and toField for some nested field. -- -- Unlike the straightforward chaining of getField/toField -- methods, getFieldOpen does not require the immediate field to -- be dupable; rather, in the best case only res has to be -- dupable. getFieldOpen :: forall dt (name :: Symbol) res (st :: [Type]). (InstrGetFieldC dt name, HasDupableGetters dt) => ('[GetFieldType dt name] :-> '[res, GetFieldType dt name]) -> ('[GetFieldType dt name] :-> '[res]) -> Label name -> (dt : st) :-> (res : (dt : st)) -- | Apply given modifier to a datatype field. -- --
--   >>> modifyField @TestProduct #fieldB (dup # mul) -$ testProduct { fieldB = 8 }
--   TestProduct {fieldA = True, fieldB = 64, fieldC = ()}
--   
modifyField :: forall dt (name :: Symbol) (st :: [Type]). (InstrGetFieldC dt name, InstrSetFieldC dt name, Dupable (GetFieldType dt name), HasDupableGetters dt) => Label name -> (forall (st0 :: [Type]). () => (GetFieldType dt name : st0) :-> (GetFieldType dt name : st0)) -> (dt : st) :-> (dt : st) -- | Like getField, but leaves field named. getFieldNamed :: forall dt (name :: Symbol) (st :: [Type]). (InstrGetFieldC dt name, Dupable (GetFieldType dt name), HasDupableGetters dt) => Label name -> (dt : st) :-> ((name :! GetFieldType dt name) : (dt : st)) -- | Extract a field of a datatype, leaving the original datatype on stack. -- --
--   >>> :{
--    (getField @TestProduct #fieldB # L.swap # toField @TestProduct #fieldB # mul) -$
--       testProduct { fieldB = 3 }
--   :}
--   9
--   
getField :: forall dt (name :: Symbol) (st :: [Type]). (InstrGetFieldC dt name, Dupable (GetFieldType dt name), HasDupableGetters dt) => Label name -> (dt : st) :-> (GetFieldType dt name : (dt : st)) -- | Like toField, but leaves field named. toFieldNamed :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt : st) :-> ((name :! GetFieldType dt name) : st) -- | Extract a field of a datatype replacing the value of this datatype -- with the extracted field. -- -- For this and the following functions you have to specify field name -- which is either record name or name attached with (:!) -- operator. -- --
--   >>> :{
--    (toField @TestProductWithNonDup #fieldTP -$ testProductWithNonDup) == testProduct
--   :}
--   True
--   
toField :: forall dt (name :: Symbol) (st :: [Type]). InstrGetFieldC dt name => Label name -> (dt : st) :-> (GetFieldType dt name : st) -- | Like HasField, but allows constrainting field type. type HasFieldOfType dt (fname :: Symbol) fieldTy = (HasField dt fname, GetFieldType dt fname ~ fieldTy) -- | A pair of field name and type. data NamedField NamedField :: Symbol -> Type -> NamedField type (n :: Symbol) := ty = 'NamedField n ty infixr 0 := -- | Shortcut for multiple HasFieldOfType constraints. type family HasFieldsOfType dt (fs :: [NamedField]) -- | This marker typeclass is a requirement for the getField (where -- it is imposed on the datatype), and it is supposed to be -- satisfied in two cases: -- --
    --
  1. The entire datatype is Dupable;
  2. --
  3. When the datatype has non-dupable fields, they are located so that -- getField remains efficient.
  4. --
-- -- The problem we are trying to solve here: without special care, -- getField may become multiple times more costly, see -- instrGetField for the explanation. And this typeclass imposes -- an invariant: if we ever use getField on a datatype, then we -- have to pay attention to the datatype's Michelson representation and -- ensure getField remains optimal. -- -- When you are developing a contract: Lorentz.Layouts.NonDupable -- module contains utilities to help you provide the necessary Michelson -- layout. In case you want to use your custom layout but still allow -- getField for it, you can define an instance for your type -- manually as an assurance that Michelson layout is optimal enough to -- use getField on this type. -- -- When you are developing a library: Note that HasDupableGetters -- resolves to Dupable by default, and when propagating this -- constraint you can switch to Dupable anytime but this will also -- make your code unusable in the presence of Tickets and other -- non-dupable types. class HasDupableGetters (a :: k) -- | Lorentz analogy of CaseClause, it works on plain Type -- types. 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) -- | Provides "case" arrow which works on different wrappers for clauses. class CaseArrow (name :: Symbol) body clause | clause -> name, clause -> body -- | Lift an instruction to case clause. -- -- You should write out constructor name corresponding to the clause -- explicitly. Prefix constructor name with "c" letter, otherwise your -- label will not be recognized by Haskell parser. Passing constructor -- name can be circumvented but doing so is not recomended as mentioning -- contructor name improves readability and allows avoiding some -- mistakes. (/->) :: CaseArrow name body clause => Label name -> body -> clause infixr 0 /-> type CaseTC dt (out :: [Type]) (inp :: [Type]) clauses = (InstrCaseC dt, RMap CaseClauses dt, RecFromTuple clauses, clauses ~ Rec CaseClauseL inp out CaseClauses dt) -- | If you apply numeric error representation in your contract, -- errorToVal will stop working because it doesn't know about this -- transformation. This function takes this transformation into account. -- If a string is used as a tag, but it is not found in the passed map, -- we conservatively preserve that string (because this whole approach is -- rather a heuristic). errorToValNumeric :: IsError e => ErrorTagMap -> e -> (forall (t :: T). ConstantScope t => Value t -> r) -> r -- | If you apply numeric error representation in your contract, -- errorFromVal will stop working because it doesn't know about -- this transformation. This function takes this transformation into -- account. If a number is used as a tag, but it is not found in the -- passed map, we conservatively preserve that number (because this whole -- approach is rather a heuristic). errorFromValNumeric :: forall (t :: T) e. (SingI t, IsError e) => ErrorTagMap -> Value t -> Either Text e -- | This function implements the simplest scenario of using this module's -- functionality: 1. Gather all error tags from a single instruction. 2. -- Turn them into error conversion map. 3. Apply this conversion. useNumericErrors :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => (inp :-> out) -> (inp :-> out, ErrorTagMap) -- | Similar to applyErrorTagMap, but for case when you have -- excluded some tags from map via excludeErrorTags. Needed, -- because both excludeErrorTags and this function do not tolerate -- unknown errors in contract code (for your safety). applyErrorTagMapWithExclusions :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => ErrorTagMap -> ErrorTagExclusions -> (inp :-> out) -> inp :-> out -- | For each typical FAILWITH that uses a string to represent error -- tag this function changes error tag to be a number using the supplied -- conversion map. It assumes that supplied map contains all such strings -- (and will error out if it does not). It will always be the case if you -- gather all error tags using gatherErrorTags and build -- ErrorTagMap from them using addNewErrorTags. applyErrorTagMap :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => ErrorTagMap -> (inp :-> out) -> inp :-> out -- | Remove some error tags from map. This way you say to remain these -- string tags intact, while others will be converted to numbers when -- this map is applied. -- -- Note that later you have to apply this map using -- applyErrorTagMapWithExclusions, otherwise an error would be -- raised. excludeErrorTags :: HasCallStack => ErrorTagExclusions -> ErrorTagMap -> ErrorTagMap -- | Build ErrorTagMap from a set of textual tags. buildErrorTagMap :: HashSet MText -> ErrorTagMap -- | Add more error tags to an existing ErrorTagMap. It is useful -- when your contract consists of multiple parts (e. g. in case of -- contract upgrade), you have existing map for some part and want to add -- tags from another part to it. You can pass empty map as existing one -- if you just want to build ErrorTagMap from a set of textual -- tags. See buildErrorTagMap. addNewErrorTags :: ErrorTagMap -> HashSet MText -> ErrorTagMap -- | Find all textual error tags that are used in typical FAILWITH -- patterns within given instruction. Map them to natural numbers. gatherErrorTags :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> HashSet MText -- | This is a bidirectional map with correspondence between numeric and -- textual error tags. type ErrorTagMap = Bimap Natural MText -- | Tags excluded from map. type ErrorTagExclusions = HashSet MText -- | QuasiQuote that helps generating TypeHasDoc instance. -- -- Usage: -- --
--   [typeDoc| <type> <description> [<field naming strategy>] |]
--   [typeDoc| Storage "This is storage description" |]
--   [typeDoc| Storage "This is storage description" stripFieldPrefix |]
--   
-- -- field naming strategy is optional, and is a function with -- signature Text -> Text. Common strategies include -- id and stripFieldPrefix. If unspecified, ultimately -- defaults to id. -- -- See this tutorial which includes this quasiquote. typeDoc :: QuasiQuoter -- | QuasiQuote that helps generating CustomErrorHasDoc instance. -- -- Usage: -- --
--   [errorDocArg| <error-name> <error-type> <error-description> [<error-arg-type>] |]
--   [errorDocArg| "errorName" exception "Error description" |]
--   [errorDocArg| "errorName" contract-internal "Error description" () |]
--   [errorDocArg| "errorName" bad-argument "Error description" Integer |]
--   
-- -- The default argument type is NoErrorArg. Only a type name can -- be used, if you need complex type, define a type synonym. -- -- See this tutorial which includes this quasiquote. errorDocArg :: QuasiQuoter -- | QuasiQuote that helps generating ParameterHasEntrypoints -- instance. -- -- Usage: -- --
--   [entrypointDoc| Parameter <parameter-type> [<root-annotation>] |]
--   [entrypointDoc| Parameter plain |]
--   [entrypointDoc| Parameter plain "root"|]
--   
-- -- See this tutorial which includes this quasiquote. entrypointDoc :: QuasiQuoter -- | Implementation of typeDocMdDescription (of TypeHasDoc -- typeclass) for Haskell types which sole purpose is to be error. typeDocMdDescriptionReferToError :: IsError e => Markdown -- | Whether given error class is about internal errors. -- -- Internal errors are not enlisted on per-entrypoint basis, only once -- for the entire contract. isInternalErrorClass :: ErrorClass -> Bool errorTagToText :: forall (tag :: Symbol). KnownSymbol tag => Text -- | Demote error tag to term level. errorTagToMText :: forall (tag :: Symbol). Label tag -> MText -- | Fail, providing a reference to the place in the code where this -- function is called. -- -- Like error in Haskell code, this instruction is for internal -- errors only. failUnexpected :: forall (s :: [Type]) (t :: [Type]). MText -> s :-> t -- | Basic implementation for failUsing. simpleFailUsing :: forall e (s :: [Type]) (t :: [Type]). IsError e => e -> s :-> t -- | Implementation of errorFromVal via IsoValue. isoErrorFromVal :: forall (t :: T) e. (SingI t, KnownIsoT e, IsoValue e) => Value t -> Either Text e -- | Implementation of errorToVal via IsoValue. isoErrorToVal :: (KnownError e, IsoValue e) => e -> (forall (t :: T). ErrorScope t => Value t -> r) -> r -- | Since 008 it's prohibited to fail with non-packable values and with -- the 'Contract t' type values, which is equivalent to our -- ConstantScope constraint. See -- https://gitlab.com/tezos/tezos/-/issues/1093#note_496066354 for -- more information. type ErrorScope (t :: T) = ConstantScope t -- | Haskell type representing error. class ErrorHasDoc e => IsError e -- | Converts a Haskell error into Value representation. errorToVal :: IsError e => e -> (forall (t :: T). ErrorScope t => Value t -> r) -> r -- | Converts a Value into Haskell error. errorFromVal :: forall (t :: T). (IsError e, SingI t) => Value t -> Either Text e -- | Fail with the given Haskell value. failUsing :: forall (s :: [Type]) (t :: [Type]). (IsError e, IsError e) => e -> s :-> t -- | Constraints which we require in a particular instance. You are not -- oblidged to often instantiate this correctly, it is only useful for -- some utilities. type family ErrorRequirements e class Typeable e => ErrorHasDoc e where { -- | Constraints which we require in a particular instance. You are not -- oblidged to often instantiate this correctly, it is only useful for -- some utilities. type family ErrorRequirements e; type ErrorRequirements e = (); } -- | Name of error as it appears in the corresponding section title. errorDocName :: ErrorHasDoc e => Text -- | What should happen for this error to be raised. errorDocMdCause :: ErrorHasDoc e => Markdown -- | Brief version of errorDocMdCause. -- -- This will appear along with the error when mentioned in entrypoint -- description. By default, the first sentence of the full description is -- used. errorDocMdCauseInEntrypoint :: ErrorHasDoc e => Markdown -- | How this error is represented in Haskell. errorDocHaskellRep :: ErrorHasDoc e => Markdown -- | Error class. errorDocClass :: ErrorHasDoc e => ErrorClass -- | Which definitions documentation for this error mentions. errorDocDependencies :: ErrorHasDoc e => [SomeDocDefinitionItem] -- | Captured constraints which we require in a particular instance. This -- is a way to encode a bidirectional instance in the nowaday Haskell, -- for class MyConstraint => ErrorHasDoc MyType instance it -- lets deducing MyConstraint by ErrorHasDoc MyType. -- -- You are not oblidged to always instantiate, it is only useful for some -- utilities which otherwise would not compile. errorDocRequirements :: ErrorHasDoc e => Dict (ErrorRequirements e) -- | Use this type as replacement for () when you really -- want to leave error cause unspecified. data UnspecifiedError UnspecifiedError :: UnspecifiedError -- | Use this error when sure that failing at the current position is -- possible in no curcumstances (including invalid user input or -- misconfigured storage). -- -- To use this as error, you have to briefly specify the reason why the -- error scenario is impossible (experimental feature). data Impossible (reason :: Symbol) Impossible :: Impossible (reason :: Symbol) -- | Type wrapper for an IsError. data SomeError SomeError :: e -> SomeError -- | Declares a custom error, defining error name - error argument -- relation. -- -- If your error is supposed to carry no argument, then provide -- (). -- -- Note that this relation is defined globally rather than on -- per-contract basis, so define errors accordingly. If your error has -- argument specific to your contract, call it such that error name -- reflects its belonging to this contract. -- -- This is the basic [error format]. type family ErrorArg (tag :: Symbol) -- | Material custom error. -- -- Use this in pattern matches against error (e.g. in tests). data CustomError (tag :: Symbol) CustomError :: Label tag -> CustomErrorRep tag -> CustomError (tag :: Symbol) [ceTag] :: CustomError (tag :: Symbol) -> Label tag [ceArg] :: CustomError (tag :: Symbol) -> CustomErrorRep tag -- | To be used as ErrorArg instance when failing with just a -- string instead of pair string x data NoErrorArg -- | To be used as ErrorArg instances. This is equivalent to using -- () but using UnitErrorArg is preferred since -- () behavior could be changed in the future. data UnitErrorArg -- | How CustomError is actually represented in Michelson. type CustomErrorRep (tag :: Symbol) = CustomErrorArgRep ErrorArg tag -- | Typeclass implements various method that work with -- CustomErrorArgRep. class IsCustomErrorArgRep a verifyErrorTag :: IsCustomErrorArgRep a => MText -> a -> Either Text a customErrorRepDocDeps :: IsCustomErrorArgRep a => [SomeDocDefinitionItem] customErrorHaskellRep :: forall (tag :: Symbol). (IsCustomErrorArgRep a, KnownSymbol tag, CustomErrorHasDoc tag) => Proxy tag -> Markdown type MustHaveErrorArg (errorTag :: Symbol) expectedArgRep = FailUnlessEqual CustomErrorRep errorTag expectedArgRep 'Text "Error argument type is " :<>: 'ShowType expectedArgRep :<>: 'Text " but given error requires argument of type " :<>: 'ShowType CustomErrorRep errorTag -- | Error class on how the error should be handled by the client. data ErrorClass -- | Normal expected error. Examples: "insufficient balance", "wallet does -- not exist". ErrClassActionException :: ErrorClass -- | Invalid argument passed to entrypoint. Examples: your entrypoint -- accepts an enum represented as nat, and unknown value is -- provided. This includes more complex cases which involve multiple -- entrypoints. E.g. API provides iterator interface, middleware should -- care about using it hiding complex details and exposing a simpler API -- to user; then an attempt to request non-existing element would also -- correspond to an error from this class. ErrClassBadArgument :: ErrorClass -- | Unexpected error. Most likely it means that there is a bug in the -- contract or the contract has been deployed incorrectly. ErrClassContractInternal :: ErrorClass -- | It's possible to leave error class unspecified. ErrClassUnknown :: ErrorClass class (KnownSymbol tag, TypeHasDoc CustomErrorRep tag, IsError CustomError tag) => CustomErrorHasDoc (tag :: Symbol) -- | What should happen for this error to be raised. customErrDocMdCause :: CustomErrorHasDoc tag => Markdown -- | Brief version of customErrDocMdCause. This will appear along -- with the error when mentioned in entrypoint description. -- -- By default, the first sentence of the full description is used. customErrDocMdCauseInEntrypoint :: CustomErrorHasDoc tag => Markdown -- | Error class. -- -- By default this returns "unknown error" class; though you should -- provide explicit implementation in order to avoid a warning. customErrClass :: CustomErrorHasDoc tag => ErrorClass -- | Clarification of error argument meaning. -- -- Provide when it's not obvious, e.g. argument is not named with -- :!. -- -- NOTE: This should not be an entire sentence, rather just the -- semantic backbone. -- -- Bad: * Error argument stands for the previous value of -- approval. -- -- Good: * the previous value of approval * pair, first -- argument of which is one thing, and the second is another customErrArgumentSemantics :: CustomErrorHasDoc tag => Maybe Markdown -- | Mentions that contract uses given error. data DError [DError] :: forall e. ErrorHasDoc e => Proxy e -> DError -- | Documentation for custom errors. -- -- Mentions that entrypoint throws given error. data DThrows [DThrows] :: forall e. ErrorHasDoc e => Proxy e -> DThrows -- | Remove element with the given type from the stack. -- --
--   >>> :{
--   dropSample1 :: [Integer, (), Natural] :-> [Integer, Natural]
--   dropSample1 = dropT @()
--   :}
--   
-- --
--   >>> pretty $ dropSample1 # zipInstr -$ 123 ::: () ::: 321
--   123 : 321
--   
-- --
--   >>> :{
--   dropSampleErr1 :: [Integer, Natural] :-> [Integer, Natural]
--   dropSampleErr1 = dropT @()
--   :}
--   ...
--   ... • Element of type '()' is not present on stack
--   ...   '[Integer, Natural]
--   ...
--   
-- --
--   >>> :{
--   dropSampleErr1 :: [Integer, Integer] :-> '[Integer]
--   dropSampleErr1 = dropT @Integer
--   :}
--   ...
--   ... • Ambiguous reference to element of type 'Integer' for stack
--   ...   '[Integer, Integer]
--   ...
--   
dropT :: forall a (inp :: [Type]) (dinp :: [Type]) (dout :: [Type]) (out :: [Type]). (DipT a inp dinp dout out, dinp ~ (a : dout)) => inp :-> out -- | Allows duplicating stack elements referring them by type. -- --
--   >>> :{
--   dupSample1 :: [Integer, MText, ()] :-> [MText, Integer, MText, ()]
--   dupSample1 = dupT @MText
--   :}
--   
-- --
--   >>> pretty $ dupSample1 # zipInstr -$ 123 ::: [mt|Hello|] ::: ()
--   Hello : 123 : Hello : ()
--   
-- --
--   >>> :{
--   dupSample2 :: [Integer, MText, ()] :-> [MText, Integer, MText, ()]
--   dupSample2 = dupT
--   :}
--   
-- --
--   >>> pretty $ dupSample2 # zipInstr -$ 123 ::: [mt|Hello|] ::: ()
--   Hello : 123 : Hello : ()
--   
-- --
--   >>> :{
--   dupSampleErr1 :: '[] :-> a
--   dupSampleErr1 = dupT @Bool
--   :}
--   ...
--   ... • Element of type 'Bool' is not present on stack
--   ...   '[]
--   ...
--   
-- --
--   >>> :{
--   -- Should fully infer both wildcards
--   dupSampleErr2 :: _ :-> [Bool, Integer, _, ()]
--   dupSampleErr2 = dupT
--   :}
--   ...
--   ... • Found type wildcard ‘_’
--   ...    standing for ‘'[Integer, Bool, ()] :: [*]’
--   ...
--   ... • Found type wildcard ‘_’ standing for ‘Bool’
--   ...   To use the inferred type, enable PartialTypeSignatures
--   ...
--   
-- --
--   >>> :{
--   -- Should fully infer both wildcards
--   _dupSampleErr3 :: [Integer, _, ()] :-> (Bool ': _)
--   _dupSampleErr3 = dupT
--   :}
--   ...
--   ... • Found type wildcard ‘_’ standing for ‘Bool’
--   ...
--   ... • Found type wildcard ‘_’
--   ...     standing for ‘'[Integer, Bool, ()] :: [*]’
--   ...
--   
class st ~ Head st : Tail st => DupT a (st :: [Type]) -- | Duplicate an element of stack referring it by type. -- -- If stack contains multiple entries of this type, compile error is -- raised. dupT :: DupT a st => st :-> (a : st) -- | Allows diving into stack referring expected new tip by type. -- --
--   >>> :{
--   dipSample1
--     :: [Natural, ()] :-> '[()]
--     -> [Integer, MText, Natural, ()] :-> [Integer, MText, ()]
--   dipSample1 = dipT @Natural
--   :}
--   
-- --
--   >>> pretty $ dipSample1 drop # zipInstr -$ 123 ::: [mt|Hello|] ::: 321 ::: ()
--   123 : Hello : ()
--   
-- --
--   >>> :{
--   dipSample2
--     :: [Natural, ()] :-> '[()]
--     -> [Integer, MText, Natural, ()] :-> [Integer, MText, ()]
--   dipSample2 = dipT -- No type application needed
--   :}
--   
-- --
--   >>> pretty $ dipSample2 drop # zipInstr -$ 123 ::: [mt|Hello|] ::: 321 ::: ()
--   123 : Hello : ()
--   
-- --
--   >>> :{
--   -- An implementation of dropT that demands a bit more from inference.
--   dipSample3
--     :: forall a inp dinp dout out.
--        ( DipT a inp dinp dout out
--        , dinp ~ (a ': dout)
--        )
--     => inp :-> out
--   dipSample3 = dipT (drop @a)
--   :}
--   
-- --
--   >>> :{
--   pretty $ dipSample3 @Natural @'[Integer, MText, Natural, ()] # zipInstr
--     -$ 123 ::: [mt|Hello|] ::: 321 ::: ()
--   :}
--   123 : Hello : ()
--   
-- --
--   >>> :{
--   _dipSampleErr1
--     :: [Natural, ()] :-> '[()]
--     -> [Integer, MText, ()] :-> [Integer, MText, ()]
--   _dipSampleErr1 = dipT @Natural
--   :}
--   ...
--   ... • Element of type 'Natural' is not present on stack
--   ...   '[Integer, MText, ()]
--   ...
--   
-- --
--   >>> :{
--   _dipSampleErr2
--     :: [Natural, ()] :-> '[()]
--     -> [Integer, MText, Natural, (), Natural] :-> [Integer, MText, ()]
--   _dipSampleErr2 = dipT @Natural
--   :}
--   ...
--   ... • Ambiguous reference to element of type 'Natural' for stack
--   ...   '[Integer, MText, Natural, (), Natural]
--   ...
--   
-- --
--   >>> :{
--   _dipSampleErr3
--     :: '[] :-> '[()]
--     -> [Integer, MText, Natural, ()] :-> [Integer, MText, ()]
--   _dipSampleErr3 = dipT @Natural
--   :}
--   ...
--   ... • dipT requires a Lorentz instruction that takes input on the stack.
--   ...
--   
class dipInp ~ a : Tail dipInp => DipT a (inp :: [Type]) (dipInp :: [Type]) (dipOut :: [Type]) (out :: [Type]) | inp a -> dipInp, dipOut inp a -> out, inp out a -> dipOut -- | Dip down until an element of the given type is on top of the stack. -- -- If the stack does not contain an element of this type, or contains -- more than one, then a compile-time error is raised. dipT :: DipT a inp dipInp dipOut out => (dipInp :-> dipOut) -> inp :-> out -- | A constructor providing the required constraint for -- WrappedLambda. This is the only way to construct a lambda that -- uses operations forbidden in views. mkLambdaRec :: forall (i :: [Type]) (o :: [Type]). (IsNotInView => (i ++ '[WrappedLambda i o]) :-> o) -> WrappedLambda i o -- | A constructor providing the required constraint for -- WrappedLambda. This is the only way to construct a lambda that -- uses operations forbidden in views. mkLambda :: forall (i :: [Type]) (o :: [Type]). (IsNotInView => i :-> o) -> WrappedLambda i o -- | A helper type to construct Lorentz lambda values; Use this for lambda -- values outside of Lorentz contracts or with push. data WrappedLambda (i :: [Type]) (o :: [Type]) WrappedLambda :: (i :-> o) -> WrappedLambda (i :: [Type]) (o :: [Type]) RecLambda :: ((i ++ '[WrappedLambda i o]) :-> o) -> WrappedLambda (i :: [Type]) (o :: [Type]) -- | A type synonym representing Michelson lambdas. type Lambda i o = WrappedLambda '[i] '[o] -- | Implementation of castDummy for types composed from smaller -- types. It helps to ensure that all necessary constraints are requested -- in instance head. castDummyG :: (Generic a, Generic b, GCanCastTo (Rep a) (Rep b)) => Proxy a -> Proxy b -> () -- | Locally provide bidirectional CanCastTo instance. allowCheckedCoerce :: forall {k1} {k2} (a :: k1) (b :: k2). Dict (CanCastTo a b, CanCastTo b a) -- | Locally provide given CanCastTo instance. allowCheckedCoerceTo :: forall {k1} {k2} (b :: k1) (a :: k2). Dict (CanCastTo a b) -- | Pretends that the top item of the stack was coerced. checkedCoercing_ :: forall a b (s :: [Type]). Coercible_ a b => ((b : s) :-> (b : s)) -> (a : s) :-> (a : s) -- | Coerce between types which have an explicit permission for that in the -- face of CanCastTo constraint. checkedCoerce_ :: forall a b (s :: [Type]). Castable_ a b => (a : s) :-> (b : s) -- | Coercion in Haskell world which respects CanCastTo. checkedCoerce :: (CanCastTo a b, Coercible a b) => a -> b -- | Unpack named value. fromNamed :: forall (name :: Symbol) a (s :: [Type]). Label name -> ((name :! a) : s) :-> (a : s) -- | Lift given value to a named value. toNamed :: forall (name :: Symbol) a (s :: [Type]). Label name -> (a : s) :-> ((name :! a) : s) -- | Specialized version of forcedCoerce_ to wrap into a haskell -- newtype. -- -- Requires Wrappable constraint. coerceWrap :: forall a (s :: [Type]). Wrappable a => (Unwrappabled a : s) :-> (a : s) -- | Specialized version of forcedCoerce_ to wrap a haskell newtype. -- -- Works under Unwrappable constraint, thus is not safe. unsafeCoerceWrap :: forall a (s :: [Type]). Unwrappable a => (Unwrappabled a : s) :-> (a : s) -- | Specialized version of forcedCoerce_ to unwrap a haskell -- newtype. coerceUnwrap :: forall a (s :: [Type]). Unwrappable a => (a : s) :-> (Unwrappabled a : s) fakeCoercing :: forall (s1 :: [Type]) (s2 :: [Type]) (s1' :: [Type]) (s2' :: [Type]). (s1 :-> s2) -> s1' :-> s2' -- | Convert between two stacks via failing. fakeCoerce :: forall (s1 :: [Type]) (s2 :: [Type]). s1 :-> s2 gForcedCoerce_ :: forall {k} t (a :: k) (b :: k) (s :: [Type]). MichelsonCoercible (t a) (t b) => (t a : s) :-> (t b : s) -- | Convert between values of types that have the same representation. -- -- This function is not safe in a sense that this allows * breaking -- invariants of casted type (example: UStore from -- morley-upgradeable), or * may stop compile on code changes (example: -- coercion of pair to a datatype with two fields will break if new field -- is added). Still, produced Michelson code will always be valid. -- -- Prefer using one of more specific functions from this module. forcedCoerce_ :: forall a b (s :: [Type]). MichelsonCoercible a b => (a : s) :-> (b : s) -- | Whether two types have the same Michelson representation. type MichelsonCoercible a b = ToT a ~ ToT b -- | Explicitly allowed coercions. -- -- a CanCastTo b proclaims that a can be casted -- to b without violating any invariants of b. -- -- This relation is reflexive; it may be symmetric or not. It -- tends to be composable: casting complex types usually requires -- permission to cast their respective parts; for such types consider -- using castDummyG as implementation of the method of this -- typeclass. -- -- For cases when a cast from a to b requires some -- validation, consider rather making a dedicated function which performs -- the necessary checks and then calls forcedCoerce. class CanCastTo (a :: k) (b :: k1) -- | An optional method which helps passing -Wredundant-constraints check. -- Also, you can set specific implementation for it with specific sanity -- checks. castDummy :: CanCastTo a b => Proxy a -> Proxy b -> () -- | Coercion from a to b is permitted and safe. type Castable_ a b = (MichelsonCoercible a b, CanCastTo a b) -- | Coercions between a to b are permitted and safe. type Coercible_ a b = (MichelsonCoercible a b, CanCastTo a b, CanCastTo b a) -- | Wrap parameter into this to locally assign a way to derive entrypoints -- for it. newtype ParameterWrapper deriv cp ParameterWrapper :: cp -> ParameterWrapper deriv cp [unParameterWraper] :: ParameterWrapper deriv cp -> cp -- | The type we unwrap to (inner type of the newtype). -- -- Used in constraint for Lorentz instruction wrapping into a Haskell -- newtype and vice versa. type family Unwrappabled s -- | Declares that this type is just a wrapper over some other type and it -- can be safely unwrapped to that inner type. -- -- Inspired by lens Wrapped. class ToT s ~ ToT Unwrappabled s => Unwrappable s where { -- | The type we unwrap to (inner type of the newtype). -- -- Used in constraint for Lorentz instruction wrapping into a Haskell -- newtype and vice versa. type family Unwrappabled s; type Unwrappabled s = GUnwrappabled s Rep s; } -- | Declares that it is safe to wrap an inner type to the given wrapper -- type. Can be provided in addition to Unwrappable. -- -- You can declare this instance when your wrapper exists just to make -- type system differentiate the two types. Example: newtype TokenId -- = TokenId Natural. -- -- Do not define this instance for wrappers that provide some -- invariants. Example: UStore type from -- morley-upgradeable. -- -- Wrappable is similar to lens Wrapped class without the -- method. class Unwrappable s => Wrappable s -- | Lifted ArithOp. class ArithOpHs aop n m r evalArithOpHs :: forall (s :: [Type]). ArithOpHs aop n m r => (n : (m : s)) :-> (r : s) -- | Helper typeclass that provides default definition of -- evalArithOpHs. class DefArithOp (aop :: k) defEvalOpHs :: forall (n :: T) (m :: T) (r :: T) (s :: [T]). (DefArithOp aop, ArithOp aop n m, r ~ ArithRes aop n m) => Instr (n : (m : s)) (r : s) type family UnaryArithResHs aop n -- | Lifted UnaryArithOp. class UnaryArithOpHs aop n where { type family UnaryArithResHs aop n; } evalUnaryArithOpHs :: forall (s :: [Type]). UnaryArithOpHs aop n => (n : s) :-> (UnaryArithResHs aop n : s) type family DefUnaryArithOpExtraConstraints (aop :: k) (n :: T) -- | Helper typeclass that provides default definition of -- evalUnaryArithOpHs. class DefUnaryArithOp (aop :: k) where { type family DefUnaryArithOpExtraConstraints (aop :: k) (n :: T); type DefUnaryArithOpExtraConstraints aop :: k n :: T = (); } defUnaryArithOpHs :: forall (n :: T) (r :: T) (s :: [T]). (DefUnaryArithOp aop, UnaryArithOp aop n, r ~ UnaryArithRes aop n, DefUnaryArithOpExtraConstraints aop n) => Instr (n : s) (r : s) class ToIntegerArithOpHs n evalToIntOpHs :: forall (s :: [Type]). ToIntegerArithOpHs n => (n : s) :-> (Integer : s) class ToBytesArithOpHs n evalToBytesOpHs :: forall bs (s :: [Type]). (ToBytesArithOpHs n, BytesLike bs) => (n : s) :-> (bs : s) -- | Similar to valueToScriptExpr, but for values encoded as -- Expressions. This is only used in tests. expressionToScriptExpr :: Expression -> ByteString -- | This function transforms Lorentz values into script_expr. -- -- script_expr is used in RPC as an argument in entrypoint -- designed for getting value by key from the big_map in Babylon. In -- order to convert value to the script_expr we have to pack it, -- take blake2b hash and add specific expr prefix. Take a look -- at -- https://gitlab.com/tezos/tezos/blob/6e25ae8eb385d9975a30388c7a7aa2a9a65bf184/src/proto_005_PsBabyM1/lib_protocol/script_expr_hash.ml -- and -- https://gitlab.com/tezos/tezos/blob/6e25ae8eb385d9975a30388c7a7aa2a9a65bf184/src/proto_005_PsBabyM1/lib_protocol/contract_services.ml#L136 -- for more information. valueToScriptExpr :: NicePackedValue t => t -> ByteString lEncodeValue :: NiceUntypedValue a => a -> ByteString lUnpackValue :: NiceUnpackedValue a => Packed a -> Either UnpackError a lPackValue :: NicePackedValue a => a -> Packed a lUnpackValueRaw :: NiceUnpackedValue a => ByteString -> Either UnpackError a lPackValueRaw :: NicePackedValue a => a -> ByteString openChestT :: forall a (s :: [Type]). BytesLike a => (ChestKey : (ChestT a : (Natural : s))) :-> (OpenChestT a : s) -- | Evaluate hash in Haskell world. toHashHs :: forall (alg :: HashAlgorithmKind) bs. (BytesLike bs, KnownHashAlgorithm alg) => bs -> Hash alg bs -- | Sign data using SecretKey lSign :: (MonadRandom m, BytesLike a) => SecretKey -> a -> m (TSignature a) -- | Everything which is represented as bytes inside. class (KnownValue bs, ToT bs ~ ToT ByteString) => BytesLike bs toBytes :: BytesLike bs => bs -> ByteString -- | Represents a ByteString resulting from packing a value of type -- a. -- -- This is not guaranteed to keep some packed value, and -- unpack can fail. We do so because often we need to accept -- values of such type from user, and also because there is no simple way -- to check validity of packed data without performing full unpack. So -- this wrapper is rather a hint for users. newtype Packed a Packed :: ByteString -> Packed a [unPacked] :: Packed a -> ByteString -- | Represents a signature, where signed data has given type. -- -- Since we usually sign a packed data, a common pattern for this type is -- TSignature (Packed signedData). If you don't want to -- use Packed, use plain TSignature ByteString instead. newtype TSignature a TSignature :: Signature -> TSignature a [unTSignature] :: TSignature a -> Signature -- | Hash of type t evaluated from data of type a. newtype Hash (alg :: HashAlgorithmKind) a UnsafeHash :: ByteString -> Hash (alg :: HashAlgorithmKind) a [unHash] :: Hash (alg :: HashAlgorithmKind) a -> ByteString -- | Hash algorithm used in Tezos. class Typeable alg => KnownHashAlgorithm (alg :: HashAlgorithmKind) hashAlgorithmName :: KnownHashAlgorithm alg => Proxy alg -> Text computeHash :: KnownHashAlgorithm alg => ByteString -> ByteString toHash :: forall bs (s :: [Type]). (KnownHashAlgorithm alg, BytesLike bs) => (bs : s) :-> (Hash alg bs : s) -- | Documentation item for hash algorithms. data DHashAlgorithm data Sha256 (a :: HashAlgoTag) data Sha512 (a :: HashAlgoTag) data Blake2b (a :: HashAlgoTag) data Sha3 (a :: HashAlgoTag) data Keccak (a :: HashAlgoTag) newtype ChestT a ChestT :: Chest -> ChestT a [unChestT] :: ChestT a -> Chest data OpenChestT a ChestContentT :: a -> OpenChestT a ChestOpenFailedT :: Bool -> OpenChestT a mkDEntrypointExample :: NiceParameter a => a -> DEntrypointExample -- | Leave only instructions related to documentation. -- -- This function is useful when your method executes a lambda coming from -- outside, but you know its properties and want to propagate its -- documentation to your contract code. cutLorentzNonDoc :: forall (inp :: [Type]) (out :: [Type]) (s :: [Type]). (inp :-> out) -> s :-> s -- | Modify the example value of an entrypoint data DEntrypointExample DEntrypointExample :: Value t -> DEntrypointExample -- | Renders to a view section. data DView DView :: ViewName -> SubDoc -> DView [dvName] :: DView -> ViewName [dvSub] :: DView -> SubDoc -- | Renders to a line mentioning the view's argument. data DViewArg DViewArg :: Proxy a -> DViewArg -- | Renders to a line mentioning the view's argument. data DViewRet DViewRet :: Proxy a -> DViewRet -- | Provides documentation for views descriptor. -- -- Note that views descriptors may describe views that do not belong to -- the current contract, e.g. TAddress may refer to an external -- contract provided by the user in which we want to call a view. class (Typeable vd, RenderViewsImpl RevealViews vd) => ViewsDescriptorHasDoc vd viewsDescriptorName :: ViewsDescriptorHasDoc vd => Proxy vd -> Text renderViewsDescriptorDoc :: ViewsDescriptorHasDoc vd => Proxy vd -> Builder -- | Renders to documentation of view descriptor. data DViewDesc DViewDesc :: Proxy vd -> DViewDesc -- | Implementation of ParameterHasEntrypoints which fits for case -- when your contract exposes multiple entrypoints via having sum type as -- its parameter. -- -- In particular, each constructor would produce a homonymous entrypoint -- with argument type equal to type of constructor field (each -- constructor should have only one field). Constructor called -- Default will designate the default entrypoint. data EpdPlain -- | Extension of EpdPlain on parameters being defined as several -- nested datatypes. -- -- In particular, this will traverse sum types recursively, stopping at -- Michelson primitives (like Natural) and constructors with -- number of fields different from one. -- -- It does not assign names to intermediate nodes of Or tree, only -- to the very leaves. -- -- If some entrypoint arguments have custom IsoValue instance, -- this derivation way will not work. As a workaround, you can wrap your -- argument into some primitive (e.g. :!). data EpdRecursive -- | Extension of EpdPlain on parameters being defined as several -- nested datatypes. -- -- In particular, it will traverse the immediate sum type, and require -- another ParameterHasEntrypoints for the inner complex -- datatypes. Only those inner types are considered which are the only -- fields in their respective constructors. Inner types should not -- themselves declare default entrypoint, we enforce this for better -- modularity. Each top-level constructor will be treated as entrypoint -- even if it contains a complex datatype within, in such case that would -- be an entrypoint corresponding to intermediate node in or -- tree. -- -- Comparing to EpdRecursive this gives you more control over -- where and how entrypoints will be derived. data EpdDelegate -- | Extension of EpdPlain, EpdRecursive, and -- EpdDelegate which allow specifying root annotation for the -- parameters. data EpdWithRoot (r :: Symbol) (epd :: k) type family MemOpKeyHs c -- | Lifted MemOpKey. class (MemOp ToT c, ToT MemOpKeyHs c ~ MemOpKey ToT c) => MemOpHs c where { type family MemOpKeyHs c; } -- | A useful property which holds for reasonable MapOp instances. -- -- It's a separate thing from MapOpHs because it mentions -- b type parameter. type family IsoMapOpRes c b type family MapOpResHs c :: Type -> Type type family MapOpInpHs c -- | Lifted MapOp. 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 IterOpElHs c -- | Lifted IterOp. class (IterOp ToT c, ToT IterOpElHs c ~ IterOpEl ToT c) => IterOpHs c where { type family IterOpElHs c; } -- | Lifted SizeOp. -- -- This could be just a constraint alias, but to avoid T types -- appearance in error messages we make a full type class with concrete -- instances. class SizeOp ToT c => SizeOpHs c type family UpdOpParamsHs c type family UpdOpKeyHs c -- | Lifted UpdOp. 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 GetOpValHs c type family GetOpKeyHs c -- | Lifted GetOp. 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; } -- | Lifted ConcatOp. class ConcatOp ToT c => ConcatOpHs c -- | Lifted SliceOp. class SliceOp ToT c => SliceOpHs c -- | Provides Buildable instance that prints Lorentz value via -- Michelson's Value. -- -- Result won't be very pretty, but this avoids requiring Show or -- Buildable instances. newtype PrintAsValue a PrintAsValue :: a -> PrintAsValue a data OpenChest type List = [] data Never -- | Value returned by READ_TICKET instruction. data ReadTicket a ReadTicket :: Address -> a -> Natural -> ReadTicket a [rtTicketer] :: ReadTicket a -> Address [rtData] :: ReadTicket a -> a [rtAmount] :: ReadTicket a -> Natural convertContractRef :: forall cp contract2 contract1. (ToContractRef cp contract1, FromContractRef cp contract2) => contract1 -> contract2 -- | Specialization of callingAddress to call the default -- entrypoint. callingDefAddress :: (ToTAddress cp vd addr, NiceParameterFull cp) => addr -> ContractRef (GetDefaultEntrypointArg cp) -- | Turn any typed address to ContractRef in Haskell world. -- -- This is an analogy of address to contract convertion -- in Michelson world, thus you have to supply an entrypoint (or call the -- default one explicitly). callingAddress :: forall cp vd addr (mname :: Maybe Symbol). (ToTAddress cp vd addr, NiceParameterFull cp) => addr -> EntrypointRef mname -> ContractRef (GetEntrypointArgCustom cp mname) -- | Address which remembers the parameter and views types of the contract -- it refers to. -- -- It differs from Michelson's contract type because it cannot -- contain entrypoint, and it always refers to entire contract parameter -- even if this contract has explicit default entrypoint. newtype TAddress p vd TAddress :: Address -> TAddress p vd [unTAddress] :: TAddress p vd -> Address -- | Address associated with value of contract arg type. -- -- Places where ContractRef can appear are now severely limited, -- this type gives you type-safety of ContractRef but still can be -- used everywhere. This type is not a full-featured one rather a helper; -- in particular, once pushing it on stack, you cannot return it back to -- Haskell world. -- -- Note that it refers to an entrypoint of the contract, not just the -- contract as a whole. In this sense this type differs from -- TAddress. -- -- Unlike with ContractRef, having this type you still cannot be -- sure that the referred contract exists and need to perform a lookup -- before calling it. newtype FutureContract arg FutureContract :: ContractRef arg -> FutureContract arg [unFutureContract] :: FutureContract arg -> ContractRef arg -- | Convert something to Address in Haskell world. -- -- Use this when you want to access state of the contract and are not -- interested in calling it. class ToAddress a toAddress :: ToAddress a => a -> Address -- | Convert something referring to a contract (not specific entrypoint) to -- TAddress in Haskell world. class ToTAddress cp vd a toTAddress :: ToTAddress cp vd a => a -> TAddress cp vd -- | Convert something to ContractRef in Haskell world. class ToContractRef cp contract toContractRef :: ToContractRef cp contract => contract -> ContractRef cp -- | Convert something from ContractRef in Haskell world. class FromContractRef cp contract fromContractRef :: FromContractRef cp contract => ContractRef cp -> contract -- | Single entrypoint of a contract. -- -- Note that we cannot make it return [[Operation], store] -- because such entrypoint should've been followed by pair, and -- this is not possible if entrypoint implementation ends with -- failWith. type Entrypoint param store = '[param, store] :-> ContractOut store -- | Version of Entrypoint which accepts no argument. type Entrypoint_ store = '[store] :-> ContractOut store -- | Fix the current type of the stack to be given one. -- --
--   stackType @'[Natural]
--   stackType @(Integer : Natural : s)
--   stackType @'["balance" :! Integer, "toSpend" :! Integer, BigMap Address Integer]
--   
-- -- Note that you can omit arbitrary parts of the type. -- --
--   stackType @'["balance" :! Integer, "toSpend" :! _, BigMap _ _]
--   
stackType :: forall (s :: [Type]). s :-> s -- | Test an invariant, fail if it does not hold. -- -- This won't be included into production contract and is executed only -- in tests. testAssert :: forall (inp :: [Type]) (out :: [Type]). HasCallStack => Text -> PrintComment (ToTs inp) -> (inp :-> (Bool : out)) -> inp :-> inp -- | Print a comment. It will be visible in tests. -- --
--   printComment "Hello world!"
--   printComment $ "On top of the stack I see " <> stackRef @0
--   
printComment :: forall (s :: [Type]). PrintComment (ToTs s) -> s :-> s -- | Include a value at given position on stack into comment produced by -- printComment. -- --
--   stackRef @0
--   
-- -- the top of the stack stackRef :: forall (gn :: Nat) (st :: [T]) (n :: Peano). (n ~ ToPeano gn, SingI n, RequireLongerThan st n) => PrintComment st optimizeLorentz :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> inp :-> out optimizeLorentzWithConf :: forall (inp :: [Type]) (out :: [Type]). OptimizerConf -> (inp :-> out) -> inp :-> out -- | Lorentz version of transformBytes. transformBytesLorentz :: forall (inp :: [Type]) (out :: [Type]). Bool -> (ByteString -> ByteString) -> (inp :-> out) -> inp :-> out -- | Lorentz version of transformStrings. transformStringsLorentz :: forall (inp :: [Type]) (out :: [Type]). Bool -> (MText -> MText) -> (inp :-> out) -> inp :-> out -- | Parse textual representation of a Michelson value and turn it into -- corresponding Haskell value. -- -- Note: it won't work in some complex cases, e. g. if there is a lambda -- which uses an instruction which depends on current contract's type. -- Obviously it can not work, because we don't have any information about -- a contract to which this value belongs (there is no such contract at -- all). parseLorentzValue :: KnownValue v => MichelsonSource -> Text -> Either ParseLorentzError v -- | Demote Lorentz Contract to Michelson typed Contract. toMichelsonContract :: Contract cp st vd -> Contract (ToT cp) (ToT st) -- | A helper to construct ContractCode that provides -- IsNotInView constraint. mkContractCode :: (IsNotInView => '[(cp, st)] :-> ContractOut st) -> ContractCode cp st iForceNotFail :: forall (i :: [Type]) (o :: [Type]). (i :-> o) -> i :-> o 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) iAnyCode :: forall (inp :: [Type]) (out :: [Type]). (inp :-> out) -> Instr (ToTs inp) (ToTs out) 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 pattern I :: Instr (ToTs inp) (ToTs out) -> inp :-> out pattern FI :: (forall (out' :: [T]). () => Instr (ToTs inp) out') -> inp :-> out -- | Alias for instruction which hides inner types representation via -- T. 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) infixr 1 :-> -- | Alias for :->, seems to make signatures more readable -- sometimes. -- -- Let's someday decide which one of these two should remain. type (%>) = (:->) infixr 1 %> type ContractOut st = '[([Operation], st)] -- | Wrap contract code capturing the constraint that the code is not -- inside a view. newtype ContractCode cp st ContractCode :: ('[(cp, st)] :-> ContractOut st) -> ContractCode cp st [unContractCode] :: ContractCode cp st -> '[(cp, st)] :-> ContractOut st data SomeContractCode [SomeContractCode] :: forall cp st. (NiceParameter cp, NiceStorage st) => ContractCode cp st -> SomeContractCode type ViewCode arg st ret = '[(arg, st)] :-> '[ret] -- | Ready contract code. cMichelsonContract :: Contract cp st vd -> Contract (ToT cp) (ToT st) -- | Contract that contains documentation. -- -- We have to keep it separately, since optimizer is free to destroy -- documentation blocks. Also, it is not ContractDoc but Lorentz -- code because the latter is easier to modify. cDocumentedCode :: Contract cp st vd -> ContractCode cp st -- | An alias for ':. -- -- We discourage its use as this hinders reading error messages (the -- compiler inserts unnecessary parentheses and indentation). type a & (b :: [Type]) = a : b infixr 2 & -- | An instruction sequence taking one stack element as input and -- returning one stack element as output. Essentially behaves as a -- Michelson lambda without any additional semantical meaning. -- -- The reason for this distinction is Michelson lambdas allow -- instructions inside them that might be forbidden in the outer scope. -- This type doesn't add any such conditions. type Fn a b = '[a] :-> '[b] -- | Applicable for wrappers over Lorentz code. class MapLorentzInstr instr -- | Modify all the code under given entity. mapLorentzInstr :: MapLorentzInstr instr => (forall (i :: [Type]) (o :: [Type]). () => (i :-> o) -> i :-> o) -> instr -> instr -- | Check whether given value is dupable, returning a proof of that when -- it is. -- -- This lets defining methods that behave differently depending on -- whether given value is dupable or not. This may be suitable when for -- the dupable case you can provide a more efficient implementation, but -- you also want your implementation to be generic. -- -- Example: -- --
--   code = case decideOnDupable @a of
--     IsDupable -> do dup; ...
--     IsNotDupable -> ...
--   
decideOnDupable :: KnownValue a => DupableDecision a -- | Constraint applied to a whole parameter type. type NiceParameterFull cp = (Typeable cp, ParameterDeclaresEntrypoints cp) -- | Tells whether given type is dupable or not. data DupableDecision a IsDupable :: DupableDecision a IsNotDupable :: DupableDecision a -- | Require views set to be proper. type NiceViews (vs :: [ViewTyInfo]) = RequireAllUnique "view" ViewsNames vs -- | Require views set referred by the given views descriptor to be proper. type NiceViewsDescriptor vd = NiceViews RevealViews vd -- | Universal entrypoint calling. parameterEntrypointCallCustom :: forall cp (mname :: Maybe Symbol). ParameterDeclaresEntrypoints cp => EntrypointRef mname -> EntrypointCall cp (GetEntrypointArgCustom cp mname) eprName :: forall (mname :: Maybe Symbol). EntrypointRef mname -> EpName -- | Call root entrypoint safely. sepcCallRootChecked :: (NiceParameter cp, ForbidExplicitDefaultEntrypoint cp) => SomeEntrypointCall cp -- | Call the default entrypoint. parameterEntrypointCallDefault :: ParameterDeclaresEntrypoints cp => EntrypointCall cp (GetDefaultEntrypointArg cp) -- | Prepare call to given entrypoint. -- -- This does not treat calls to default entrypoint in a special way. To -- call default entrypoint properly use -- parameterEntrypointCallDefault. parameterEntrypointCall :: forall cp (name :: Symbol). ParameterDeclaresEntrypoints cp => Label name -> EntrypointCall cp (GetEntrypointArg cp name) -- | Derive annotations for given parameter. parameterEntrypointsToNotes :: ParameterDeclaresEntrypoints cp => ParamNotes (ToT cp) -- | Get entrypoint argument by name. type family EpdLookupEntrypoint (deriv :: k) cp :: Symbol -> Exp Maybe Type -- | Name and argument of each entrypoint. This may include intermediate -- ones, even root if necessary. -- -- Touching this type family is costly (O(N^2)), don't use it -- often. -- -- Note [order of entrypoints children]: If this contains entrypoints -- referring to indermediate nodes (not leaves) in or tree, then -- each such entrypoint should be mentioned eariler than all of its -- children. type family EpdAllEntrypoints (deriv :: k) cp :: [(Symbol, Type)] -- | Defines a generalized way to declare entrypoints for various parameter -- types. -- -- When defining instances of this typeclass, set concrete deriv -- argument and leave variable cp argument. Also keep in mind, -- that in presence of explicit default entrypoint, all other Or -- arms should be callable, though you can put this burden on user if -- very necessary. -- -- Methods of this typeclass aim to better type-safety when making up an -- implementation and they may be not too convenient to use; users should -- exploit their counterparts. class EntrypointsDerivation (deriv :: k) cp where { -- | Name and argument of each entrypoint. This may include intermediate -- ones, even root if necessary. -- -- Touching this type family is costly (O(N^2)), don't use it -- often. -- -- Note [order of entrypoints children]: If this contains entrypoints -- referring to indermediate nodes (not leaves) in or tree, then -- each such entrypoint should be mentioned eariler than all of its -- children. type family EpdAllEntrypoints (deriv :: k) cp :: [(Symbol, Type)]; -- | Get entrypoint argument by name. type family EpdLookupEntrypoint (deriv :: k) cp :: Symbol -> Exp Maybe Type; } -- | Construct parameter annotations corresponding to expected entrypoints -- set. -- -- This method is implementation detail, for actual notes construction -- use parameterEntrypointsToNotes. epdNotes :: EntrypointsDerivation deriv cp => (Notes (ToT cp), RootAnn) -- | Construct entrypoint caller. -- -- This does not treat calls to default entrypoint in a special way. -- -- This method is implementation detail, for actual entrypoint lookup use -- parameterEntrypointCall. epdCall :: forall (name :: Symbol). (EntrypointsDerivation deriv cp, ParameterScope (ToT cp)) => Label name -> EpConstructionRes (ToT cp) (Eval (EpdLookupEntrypoint deriv cp name)) -- | Description of how each of the entrypoints is constructed. epdDescs :: EntrypointsDerivation deriv cp => Rec EpCallingDesc (EpdAllEntrypoints deriv cp) -- | Ensure that all declared entrypoints are unique. type RequireAllUniqueEntrypoints cp = RequireAllUniqueEntrypoints' ParameterEntrypointsDerivation cp cp type family ParameterEntrypointsDerivation cp -- | Which entrypoints given parameter declares. -- -- Note that usually this function should not be used as constraint, use -- ParameterDeclaresEntrypoints for this purpose. class (EntrypointsDerivation ParameterEntrypointsDerivation cp cp, RequireAllUniqueEntrypoints cp) => ParameterHasEntrypoints cp where { type family ParameterEntrypointsDerivation cp; } -- | Parameter declares some entrypoints. -- -- This is a version of ParameterHasEntrypoints which we actually -- use in constraints. When given type is a sum type or newtype, we refer -- to ParameterHasEntrypoints instance, otherwise this instance is -- not necessary. type ParameterDeclaresEntrypoints cp = (If CanHaveEntrypoints cp ParameterHasEntrypoints cp (), NiceParameter cp, EntrypointsDerivation GetParameterEpDerivation cp cp) -- | Get all entrypoints declared for parameter. type family AllParameterEntrypoints cp :: [(Symbol, Type)] -- | Lookup for entrypoint type by name. -- -- Does not treat default entrypoints in a special way. type family LookupParameterEntrypoint cp :: Symbol -> Exp Maybe Type -- | Get type of entrypoint with given name, fail if not found. 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 -- | Get type of entrypoint with given name, fail if not found. type GetDefaultEntrypointArg cp = Eval LiftM2 FromMaybe :: Type -> Maybe Type -> Type -> Type Pure cp LookupParameterEntrypoint cp DefaultEpName -- | Ensure that there is no explicit "default" entrypoint. 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 -- | Similar to ForbidExplicitDefaultEntrypoint, but in a version -- which the compiler can work with (and which produces errors confusing -- for users :/) type NoExplicitDefaultEntrypoint cp = Eval LookupParameterEntrypoint cp DefaultEpName ~ 'Nothing :: Maybe Type -- | Which entrypoint to call. -- -- We intentionally distinguish default and non-default cases because -- this makes API more details-agnostic. data EntrypointRef (mname :: Maybe Symbol) -- | Call the default entrypoint, or root if no explicit default is -- assigned. [CallDefault] :: EntrypointRef ('Nothing :: Maybe Symbol) -- | Call the given entrypoint; calling default is not treated specially. -- You have to provide entrypoint name via passing it as type argument. -- -- Unfortunatelly, here we cannot accept a label because in most cases -- our entrypoints begin from capital letter (being derived from -- constructor name), while labels must start from a lower-case letter, -- and there is no way to make a conversion at type-level. [Call] :: forall (name :: Symbol). NiceEntrypointName name => EntrypointRef ('Just name) -- | Universal entrypoint lookup. type family GetEntrypointArgCustom cp (mname :: Maybe Symbol) -- | When we call a Lorentz contract we should pass entrypoint name and -- corresponding argument. Ideally we want to statically check that -- parameter has entrypoint with given name and argument. Constraint -- defined by this type class holds for contract with parameter -- cp that have entrypoint matching name with type -- arg. -- -- In order to check this property statically, we need to know entrypoint -- name in compile time, EntrypointRef type serves this purpose. -- If entrypoint name is not known, one can use TrustEpName -- wrapper to take responsibility for presence of this entrypoint. -- -- If you want to call a function which has this constraint, you have two -- options: -- --
    --
  1. Pass contract parameter cp using type application, pass -- EntrypointRef as a value and pass entrypoint argument. Type -- system will check that cp has an entrypoint with given -- reference and type.
  2. --
  3. Pass EpName wrapped into TrustEpName and entrypoint -- argument. In this case passing contract parameter is not necessary, -- you do not even have to know it.
  4. --
-- -- You may need to add this constraint for polymorphic arguments. GHC -- should tell you when that is the case: -- --
--   >>> :{
--   f :: forall (cp :: Type). ParameterDeclaresEntrypoints cp => ()
--   f = useHasEntrypointArg @cp @_ @(Maybe Integer) CallDefault & const ()
--   :}
--   ...
--   ... Can not look up entrypoints in type
--   ...   cp
--   ... The most likely reason it is ambiguous, or you need
--   ...   HasEntrypointArg cp (EntrypointRef 'Nothing) (Maybe Integer)
--   ... constraint
--   ...
--   
-- -- If GHC can't deduce the type of entrypoint argument, it'll use an -- unbound type variable, usually arg0, in the error message: -- --
--   >>> :{
--   f :: forall (cp :: Type). ParameterDeclaresEntrypoints cp => ()
--   f = useHasEntrypointArg @cp CallDefault & const ()
--   :}
--   ...
--   ... Can not look up entrypoints in type
--   ...   cp
--   ... The most likely reason it is ambiguous, or you need
--   ...   HasEntrypointArg cp (EntrypointRef 'Nothing) arg0
--   ... constraint
--   ...
--   
class HasEntrypointArg (cp :: k) name arg -- | Data returned by this method may look somewhat arbitrary. -- EpName is obviously needed because name can be -- EntrypointRef or TrustEpName. Dict is returned -- because in EntrypointRef case we get this evidence for free and -- don't want to use it. We seem to always need it anyway. useHasEntrypointArg :: HasEntrypointArg cp name arg => name -> (Dict (ParameterScope (ToT arg)), EpName) -- | HasEntrypointArg constraint specialized to default entrypoint. type HasDefEntrypointArg (cp :: k) defEpName defArg = (defEpName ~ EntrypointRef 'Nothing :: Maybe Symbol, HasEntrypointArg cp defEpName defArg) -- | This wrapper allows to pass untyped EpName and bypass checking -- that entrypoint with given name and type exists. newtype TrustEpName TrustEpName :: EpName -> TrustEpName -- | Checks that the given parameter consists of some specific entrypoint. -- Similar as HasEntrypointArg but ensures that the argument -- matches the following datatype. type HasEntrypointOfType param (con :: Symbol) exp = (GetEntrypointArgCustom param 'Just con ~ exp, ParameterDeclaresEntrypoints param) type (n :: Symbol) :> ty = 'NamedEp n ty infixr 0 :> -- | Check that the given entrypoint has some fields inside. This interface -- allows for an abstraction of contract parameter so that it requires -- some *minimal* specification, but not a concrete one. type family ParameterContainsEntrypoints param (fields :: [NamedEp]) -- | No entrypoints declared, parameter type will serve as argument type of -- the only existing entrypoint (default one). data EpdNone -- | A special type which wraps over a primitive type and states that it -- has entrypoints (one). -- -- Assuming that any type can have entrypoints makes use of Lorentz -- entrypoints too annoying, so for declaring entrypoints for not sum -- types we require an explicit wrapper. newtype ShouldHaveEntrypoints a ShouldHaveEntrypoints :: a -> ShouldHaveEntrypoints a [unHasEntrypoints] :: ShouldHaveEntrypoints a -> a -- | Gathers constraints, commonly required for values. class (IsoValue a, Typeable a) => KnownValue a -- | Ensure given type does not contain "operation". class (ForbidOp ToT a, IsoValue a) => NoOperation a class (ForbidContract ToT a, IsoValue a) => NoContractType a class (ForbidBigMap ToT a, IsoValue a) => NoBigMap a class (HasNoNestedBigMaps ToT a, IsoValue a) => CanHaveBigMap a -- | Constraint applied to any part of a parameter type. -- -- Use NiceParameterFull instead when you need to know the -- contract's entrypoints at compile-time. type NiceParameter a = (ProperParameterBetterErrors ToT a, KnownValue a) type NiceStorage a = (ProperStorageBetterErrors ToT a, KnownValue a) type NiceStorageFull a = (NiceStorage a, HasAnnotation a) type NiceConstant a = (ProperConstantBetterErrors ToT a, KnownValue a) type Dupable a = (ProperDupableBetterErrors ToT a, KnownValue a) type NicePackedValue a = (ProperPackedValBetterErrors ToT a, KnownValue a) type NiceUnpackedValue a = (ProperUnpackedValBetterErrors ToT a, KnownValue a) type NiceFullPackedValue a = (NicePackedValue a, NiceUnpackedValue a) type NiceUntypedValue a = (ProperUntypedValBetterErrors ToT a, KnownValue a) type NiceViewable a = (ProperViewableBetterErrors ToT a, KnownValue a) -- | Constraint applied to any type, to check if Michelson representation -- (if exists) of this type is Comparable. In case it is not prints -- human-readable error message type NiceComparable n = (ProperNonComparableValBetterErrors ToT n, KnownValue n, Comparable ToT n) type NiceNoBigMap n = (KnownValue n, HasNoBigMap ToT n) -- | This class defines the type and field annotations for a given type. -- Right now the type annotations come from names in a named field, and -- field annotations are generated from the record fields. class HasAnnotation a -- | 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 :& -- | Infix application. -- --
--   f :: Either String $ Maybe Int
--   =
--   f :: Either String (Maybe Int)
--   
type (f :: k1 -> k) $ (a :: k1) = f a infixr 2 $ -- | undefined that leaves a warning in code on every usage. undefined :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => 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 -- | Type of a strategy to derive Generic instances. data GenericStrategy -- | In this strategy the desired depths of contructors (in the type tree) -- and fields (in each constructor's tree) are provided manually and -- simply checked against the number of actual constructors and fields. withDepths :: [CstrDepth] -> GenericStrategy -- | Strategy to make right-balanced instances (both in constructors and -- fields). -- -- This will try its best to produce a flat tree: -- -- rightBalanced :: GenericStrategy -- | Strategy to make left-balanced instances (both in constructors and -- fields). -- -- This is the same as symmetrically mapped rightBalanced. leftBalanced :: GenericStrategy -- | Strategy to make fully right-leaning instances (both in constructors -- and fields). rightComb :: GenericStrategy -- | Strategy to make fully left-leaning instances (both in constructors -- and fields). leftComb :: GenericStrategy -- | Strategy to make Haskell's Generics-like instances (both in -- constructors and fields). -- -- This is similar to rightBalanced, except for the "flat" part: -- -- -- -- This strategy matches A1.1. -- -- customGeneric "T" haskellBalanced is equivalent to mere -- deriving stock Generic T. haskellBalanced :: GenericStrategy -- | Modify given strategy to reorder constructors. -- -- The reordering will take place before depths are evaluated and -- structure of generic representation is formed. -- -- Example: reorderingConstrs alphabetically rightBalanced. reorderingConstrs :: EntriesReorder -> GenericStrategy -> GenericStrategy -- | Modify given strategy to reorder fields. -- -- Same notes as for reorderingConstrs apply here. -- -- Example: reorderingFields forbidUnnamedFields alphabetically -- rightBalanced. reorderingFields :: UnnamedEntriesReorder -> EntriesReorder -> GenericStrategy -> GenericStrategy -- | Modify given strategy to reorder constructors and fields. -- -- Same notes as for reorderingConstrs apply here. -- -- Example: reorderingData forbidUnnamedFields alphabetically -- rightBalanced. reorderingData :: UnnamedEntriesReorder -> EntriesReorder -> GenericStrategy -> GenericStrategy -- | Sort entries by name alphabetically. alphabetically :: EntriesReorder -- | Leave unnamed fields intact, without any reordering. leaveUnnamedFields :: UnnamedEntriesReorder -- | Fail in case records are unnamed and we cannot figure out the -- necessary reordering. forbidUnnamedFields :: UnnamedEntriesReorder -- | Helper to make a strategy that created depths for constructor and -- fields in the same way, just from their number. -- -- The provided function f must satisfy the following rules: -- -- fromDepthsStrategy :: (Int -> [Natural]) -> GenericStrategy -- | Like fromDepthsStrategy, but allows specifying different -- strategies for constructors and fields. fromDepthsStrategy' :: (Int -> [Natural]) -> (Int -> [Natural]) -> GenericStrategy makeRightBalDepths :: Int -> [Natural] -- | Helper for making a constructor depth. -- -- Note that this is only intended to be more readable than directly -- using a tuple with withDepths and for the ability to be used in -- places where RebindableSyntax overrides the number literal -- resolution. cstr :: forall (n :: Nat). KnownNat n => [Natural] -> CstrDepth -- | Helper for making a field depth. -- -- Note that this is only intended to be more readable than directly -- using a tuple with withDepths and for the ability to be used in -- places where RebindableSyntax overrides the number literal -- resolution. fld :: forall (n :: Nat). KnownNat n => Natural customGeneric :: String -> GenericStrategy -> Q [Dec] -- | If a Type type is given, this function will generate a new -- Generic instance with it, and generate the appropriate "to" and -- "from" methods. -- -- Otherwise, it'll generate a new Type instance as well. customGeneric' :: Maybe Type -> Name -> Type -> [Con] -> GenericStrategy -> Q [Dec] -- | Reifies info from a type name (given as a String). The lookup -- happens from the current splice's scope (see lookupTypeName) -- and the only accepted result is a "plain" data type (no GADTs). reifyDataType :: Name -> Q (Name, Cxt, Maybe Kind, [TyVarBndr ()], [Con]) -- | Derives, as well as possible, a type definition from its name, its -- kind (where known) and its variables. deriveFullType :: Name -> Maybe Kind -> [TyVarBndr flag] -> TypeQ -- | Patch a given strategy by applying a transformation function to -- constructor names before passing them through ordering function. mangleGenericStrategyConstructors :: (Text -> Text) -> GenericStrategy -> GenericStrategy -- | Patch a given strategy by applying a transformation function to field -- names before passing them through ordering function. mangleGenericStrategyFields :: (Text -> Text) -> GenericStrategy -> GenericStrategy -- | Default layout in LIGO. -- -- To be used with customGeneric, see this method for more info. -- -- This is similar to leftBalanced, but -- -- ligoLayout :: GenericStrategy -- | Comb layout in LIGO ( [@layout:comb] ). -- -- To be used with customGeneric. -- -- Note: to make comb layout work for sum types, make sure that in LIGO -- all the constructors are preceded by the bar symbol in your type -- declaration: -- --
--   type my_type =
--     [@layout:comb]
--     | Ctor1 of nat  ← bar symbol _must_ be here
--     | Ctor2 of int
--     ...
--   
-- -- Though the situation may change: -- https://gitlab.com/ligolang/ligo/-/issues/1104. ligoCombLayout :: GenericStrategy -- | A piece of markdown document. -- -- This is opposed to Text type, which in turn is not supposed to -- contain markup elements. type Markdown = Builder -- | Set of constraints that Michelson applies to pushed constants. -- -- Not just a type alias in order to be able to partially apply it class (SingI t, WellTyped t, HasNoOp t, HasNoBigMap t, HasNoContract t, HasNoTicket t, HasNoSaplingState t) => ConstantScope (t :: T) -- | Proxy for a label type that includes the KnownSymbol constraint data Label (name :: Symbol) [Label] :: forall (name :: Symbol). KnownSymbol name => Label name -- | A locked chest data Chest -- | A chest "key" with proof that it was indeed opened fairly. data ChestKey -- | Entrypoint name. -- -- There are two properties we care about: -- --
    --
  1. Special treatment of the default entrypoint name. -- default is prohibited in the CONTRACT instruction -- and in values of address and contract types. -- However, it is not prohibited in the SELF instruction. Hence, -- the value inside EpName can be "default", so -- that we can distinguish SELF and SELF %default. It -- is important to distinguish them because their binary representation -- that is inserted into blockchain is different. For example, -- typechecking SELF %default consumes more gas than -- SELF. In this module, we provide several smart constructors -- with different handling of default, please use the -- appropriate one for your use case.
  2. --
  3. The set of permitted characters. Intuitively, an entrypoint name -- should be valid only if it is a valid annotation (because entrypoints -- are defined using field annotations). However, it is not enforced in -- Tezos. It is not clear whether this behavior is intended. There is an -- upstream issue which received bug label, so probably -- it is considered a bug. Currently we treat it as a bug and deviate -- from upstream implementation by probiting entrypoint names that are -- not valid annotations. If Tezos developers fix it soon, we will be -- happy. If they don't, we should (maybe temporarily) remove this -- limitation from our code. There is an issue in our repo as -- well.
  4. --
data EpName -- | This is a bidirectional pattern that can be used for two purposes: -- --
    --
  1. Construct an EpName referring to the default -- entrypoint.
  2. --
  3. Use it in pattern-matching or in equality comparison to check -- whether EpName refers to the default entrypoint. This is -- trickier because there are two possible EpName values referring -- to the default entrypoints. DefEpName will match only the most -- common one (no entrypoint). However, there is a special case: -- SELF instruction can have explicit %default -- reference. For this reason, it is recommended to use -- isDefEpName instead. Pattern-matching on DefEpName is -- still permitted for backwards compatibility and for the cases when you -- are sure that EpName does not come from the SELF -- instruction.
  4. --
pattern DefEpName :: EpName -- | An element of an algebraic number field (scalar), used for multiplying -- Bls12381G1 and Bls12381G2. data Bls12381Fr -- | G2 point on the curve. data Bls12381G2 -- | G1 point on the curve. data Bls12381G1 -- | Michelson string value. -- -- This is basically a mere text with limits imposed by the language: -- https://tezos.gitlab.io/whitedoc/michelson.html#constants -- Although, this document seems to be not fully correct, and thus we -- applied constraints deduced empirically. -- -- You construct an item of this type using one of the following ways: -- -- -- --
--   >>> [mt|Some text|]
--   UnsafeMText {unMText = "Some text"}
--   
-- -- data MText -- | QuasyQuoter for constructing Michelson strings. -- -- Validity of result will be checked at compile time. Note: -- -- mt :: QuasiQuoter -- | Convenience synonym for an on-chain public key hash. type KeyHash = Hash 'HashKindPublicKey -- | Cryptographic signatures used by Tezos. Constructors correspond to -- PublicKey constructors. -- -- Tezos distinguishes signatures for different curves. For instance, -- ed25519 signatures and secp256k1 signatures are printed differently -- (have different prefix). However, signatures are packed without -- information about the curve. For this purpose there is a generic -- signature which only stores bytes and doesn't carry information about -- the curve. Apparently unpacking from bytes always produces such -- signature. Unpacking from string produces a signature with curve -- information. data Signature -- | Public cryptographic key used by Tezos. There are three cryptographic -- curves each represented by its own constructor. data PublicKey -- | Identifier of a network (babylonnet, mainnet, test network or other). -- Evaluated as hash of the genesis block. -- -- The only operation supported for this type is packing. Use case: -- multisig contract, for instance, now includes chain ID into signed -- data "in order to add extra replay protection between the main chain -- and the test chain". data ChainId -- | Time in the real world. Use the functions below to convert it to/from -- Unix time in seconds. data Timestamp -- | Mutez is a wrapper over integer data type. 1 mutez is 1 token (μTz). -- -- The constructor is marked Unsafe since GHC does not warn on -- overflowing literals (exceeding custom Word63 type bounds), -- thus the resultant Mutez value may get truncated silently. -- --
--   >>> UnsafeMutez 9223372036854775809
--   UnsafeMutez {unMutez = 1}
--   
data Mutez -- | Quotes a Mutez value. -- -- The value is in XTZ, i.e. 1e6 Mutez, with optional suffix -- representing a unit: -- -- -- -- This is the safest and recommended way to create Mutez from a -- numeric literal. -- -- The suffix can be separated from the number by whitespace. You can -- also use underscores as a delimiter (those will be ignored), and -- scientific notation, e.g. 123.456e6. Note that if the -- scientific notation represents a mutez fraction, that is a -- compile-time error. -- --
--   >>> [tz|123|]
--   UnsafeMutez {unMutez = 123000000}
--   
-- --
--   >>> [tz|123k|]
--   UnsafeMutez {unMutez = 123000000000}
--   
-- --
--   >>> [tz|123 kilo|]
--   UnsafeMutez {unMutez = 123000000000}
--   
-- --
--   >>> [tz|123M|]
--   UnsafeMutez {unMutez = 123000000000000}
--   
-- --
--   >>> [tz|123 Mega|]
--   UnsafeMutez {unMutez = 123000000000000}
--   
-- --
--   >>> [tz|123 mega|]
--   UnsafeMutez {unMutez = 123000000000000}
--   
-- --
--   >>> [tz|123e6|]
--   UnsafeMutez {unMutez = 123000000000000}
--   
-- --
--   >>> [tz|123m|]
--   UnsafeMutez {unMutez = 123000}
--   
-- --
--   >>> [tz|123 milli|]
--   UnsafeMutez {unMutez = 123000}
--   
-- --
--   >>> [tz|123u|]
--   UnsafeMutez {unMutez = 123}
--   
-- --
--   >>> [tz|123μ|]
--   UnsafeMutez {unMutez = 123}
--   
-- --
--   >>> [tz|123 micro|]
--   UnsafeMutez {unMutez = 123}
--   
-- --
--   >>> [tz| 123.456_789 |]
--   UnsafeMutez {unMutez = 123456789}
--   
-- --
--   >>> [tz|123.456u|]
--   ...
--   ... error:
--   ...  • The number is a mutez fraction. The smallest possible subdivision is 0.000001 XTZ
--   ...
--   
-- --
--   >>> [tz|0.012_345_6|]
--   ...
--   ... error:
--   ...  • The number is a mutez fraction. The smallest possible subdivision is 0.000001 XTZ
--   ...
--   
-- --
--   >>> [tz| 9223372.036854775807 M |]
--   UnsafeMutez {unMutez = 9223372036854775807}
--   
-- --
--   >>> [tz| 9223372.036854775808 M |]
--   ...
--   ... error:
--   ...  • The number is out of mutez bounds. It must be between 0 and 9223372036854.775807 XTZ (inclusive).
--   ...
--   
-- --
--   >>> [tz| -1 |]
--   ...
--   ... error:
--   ...  • The number is out of mutez bounds. It must be between 0 and 9223372036854.775807 XTZ (inclusive).
--   ...
--   
tz :: QuasiQuoter -- | Safely create Mutez. -- -- When constructing literals, you'll need to specify the type of the -- literal. GHC will check for literal overflow on builtin types like -- Word16 and Word32, but not on Word62 or -- Word63, so those can overflow silently. -- -- It's recommended to use tz quasiquote for literals instead. toMutez :: (Integral a, CheckIntSubType a Word63) => a -> Mutez zeroMutez :: Mutez oneMutez :: Mutez timestampFromSeconds :: Integer -> Timestamp timestampFromUTCTime :: UTCTime -> Timestamp -- | Quote a value of type Timestamp in -- yyyy-mm-ddThh:mm:ss[.sss]Z format. -- --
--   >>> formatTimestamp [timestampQuote| 2019-02-21T16:54:12.2344523Z |]
--   "2019-02-21T16:54:12Z"
--   
-- -- Inspired by 'time-quote' library. timestampQuote :: QuasiQuoter -- | Data type corresponding to address structure in Tezos. type Address = Constrained NullConstraint :: AddressKind -> Constraint KindedAddress -- | Get the term-level type of notes, preserving annotations. mkUType :: forall (x :: T). Notes x -> Ty -- | Address with optional entrypoint name attached to it. data EpAddress EpAddress' :: Address -> EpName -> EpAddress -- | Address itself [eaAddress] :: EpAddress -> Address -- | Entrypoint name (might be empty) [eaEntrypoint] :: EpAddress -> EpName pattern EpAddress :: forall (kind :: AddressKind). () => KindedAddress kind -> EpName -> EpAddress -- | Constraint ensuring the given code does not appear on the top level of -- a view. Some Michelson instructions are forbidden on the top level of -- views, but allowed in main contract code, and also inside lambdas in -- views. Hence, this constraint can be provided by mkContractCode -- or by mkVLam. class IsNotInView -- | Keeps documentation gathered for some piece of contract code. -- -- Used for building documentation of a contract. data ContractDoc ContractDoc :: DocBlock -> DocBlock -> Set SomeDocDefinitionItem -> Set DocItemId -> ContractDoc -- | All inlined doc items. [cdContents] :: ContractDoc -> DocBlock -- | Definitions used in document. -- -- Usually you put some large and repetitive descriptions here. This -- differs from the document content in that it contains sections which -- are always at top-level, disregard the nesting. -- -- All doc items which define docItemId method go here, and only -- they. [cdDefinitions] :: ContractDoc -> DocBlock -- | We remember all already declared entries to avoid cyclic dependencies -- in documentation items discovery. [cdDefinitionsSet] :: ContractDoc -> Set SomeDocDefinitionItem -- | We remember all already used identifiers. (Documentation naturally -- should not declare multiple items with the same identifier because -- that would make references to the respective anchors ambiguous). [cdDefinitionIds] :: ContractDoc -> Set DocItemId -- | A part of documentation to be grouped. Essentially incapsulates -- DocBlock. newtype SubDoc SubDoc :: DocBlock -> SubDoc -- | Several doc items of the same type. data DocSection DocSection :: (NonEmpty $ DocElem d) -> DocSection -- | A doc item which we store, along with related information. data DocElem d DocElem :: d -> Maybe SubDoc -> DocElem d -- | Doc item itself. [deItem] :: DocElem d -> d -- | Subdocumentation, if given item is a group. [deSub] :: DocElem d -> Maybe SubDoc -- | Hides some documentation item which is put to "definitions" section. data SomeDocDefinitionItem [SomeDocDefinitionItem] :: forall d. (DocItem d, DocItemPlacement d ~ 'DocItemInDefinitions) => d -> SomeDocDefinitionItem -- | Hides some documentation item. data SomeDocItem [SomeDocItem] :: forall d. DocItem d => d -> SomeDocItem -- | How to render section name. data DocSectionNameStyle -- | Suitable for block name. DocSectionNameBig :: DocSectionNameStyle -- | Suitable for subsection title within block. DocSectionNameSmall :: DocSectionNameStyle data DocItemRef (p :: DocItemPlacementKind) (r :: DocItemReferencedKind) [DocItemRef] :: DocItemId -> DocItemRef 'DocItemInDefinitions 'True [DocItemRefInlined] :: DocItemId -> DocItemRef 'DocItemInlined 'True [DocItemNoRef] :: DocItemRef 'DocItemInlined 'False -- | Where do we place given doc item. data DocItemPlacementKind -- | Placed in the document content itself. DocItemInlined :: DocItemPlacementKind -- | Placed in dedicated definitions section; can later be referenced. DocItemInDefinitions :: DocItemPlacementKind -- | Position of all doc items of some type. newtype DocItemPos DocItemPos :: (Natural, Text) -> DocItemPos -- | Some unique identifier of a doc item. -- -- All doc items which should be refer-able need to have this identifier. newtype DocItemId DocItemId :: Text -> DocItemId -- | A piece of documentation describing one property of a thing, be it a -- name or description of a contract, or an error throwable by given -- endpoint. -- -- Items of the same type appear close to each other in a rendered -- documentation and form a section. -- -- Doc items are later injected into a contract code via a dedicated -- nop-like instruction. Normally doc items which belong to one section -- appear in resulting doc in the same order in which they appeared in -- the contract. -- -- While documentation framework grows, this typeclass acquires more and -- more methods for fine tuning of existing rendering logic because we -- don't want to break backward compatibility, hope one day we will make -- everything concise :( E.g. all rendering and reording stuff could be -- merged in one method, and we could have several template -- implementations for it which would allow user to specify only stuff -- relevant to his case. class (Typeable d, DOrd d) => DocItem d where { -- | Defines where given doc item should be put. There are two options: 1. -- Inline right here (default behaviour); 2. Put into definitions -- section. -- -- Note that we require all doc items with "in definitions" placement to -- have Eq and Ord instances which comply the following -- law: if two documentation items describe the same entity or property, -- they should be considered equal. type family DocItemPlacement d :: DocItemPlacementKind; type family DocItemReferenced d :: DocItemReferencedKind; type DocItemPlacement d = 'DocItemInlined; type DocItemReferenced d = 'False; } -- | Position of this item in the resulting documentation; the smaller the -- value, the higher the section with this element will be placed. If the -- position is the same as other doc items, they will be placed base on -- their name, alphabetically. -- -- Documentation structure is not necessarily flat. If some doc item -- consolidates a whole documentation block within it, this block will -- have its own placement of items independent from outer parts of the -- doc. docItemPos :: DocItem d => Natural -- | When multiple items of the same type belong to one section, how this -- section will be called. -- -- If not provided, section will contain just untitled content. docItemSectionName :: DocItem d => Maybe Text -- | Description of a section. -- -- Can be used to mention some common things about all elements of this -- section. Markdown syntax is permitted here. docItemSectionDescription :: DocItem d => Maybe Markdown -- | How to render section name. -- -- Takes effect only if section name is set. docItemSectionNameStyle :: DocItem d => DocSectionNameStyle -- | Defines a function which constructs an unique identifier of given doc -- item, if it has been decided to put the doc item into definitions -- section. -- -- Identifier should be unique both among doc items of the same type and -- items of other types. Thus, consider using "typeId-contentId" pattern. docItemRef :: DocItem d => d -> DocItemRef (DocItemPlacement d) (DocItemReferenced d) -- | Render given doc item to Markdown, preferably one line, optionally -- with header. -- -- Accepts the smallest allowed level of header. (Using smaller value -- than provided one will interfere with existing headers thus delivering -- mess). docItemToMarkdown :: DocItem d => HeaderLevel -> d -> Markdown -- | Render table of contents entry for given doc item to Markdown. docItemToToc :: DocItem d => HeaderLevel -> d -> Markdown -- | All doc items which this doc item refers to. -- -- They will automatically be put to definitions as soon as given doc -- item is detected. docItemDependencies :: DocItem d => d -> [SomeDocDefinitionItem] -- | This function accepts doc items put under the same section in the -- order in which they appeared in the contract and returns their new -- desired order. It's also fine to use this function for filtering or -- merging doc items. -- -- Default implementation * leaves inlined items as is; * for items put -- to definitions, lexicographically sorts them by their id. docItemsOrder :: DocItem d => [d] -> [d] -- | Defines where given doc item should be put. There are two options: 1. -- Inline right here (default behaviour); 2. Put into definitions -- section. -- -- Note that we require all doc items with "in definitions" placement to -- have Eq and Ord instances which comply the following -- law: if two documentation items describe the same entity or property, -- they should be considered equal. type family DocItemPlacement d :: DocItemPlacementKind type family DocItemReferenced d :: DocItemReferencedKind -- | Generate DToc entry anchor from docItemRef. mdTocFromRef :: (DocItem d, DocItemReferenced d ~ 'True) => HeaderLevel -> Markdown -> d -> Markdown -- | Get doc item position at term-level. docItemPosition :: DocItem d => DocItemPos -- | Make a reference to doc item in definitions. docDefinitionRef :: (DocItem d, DocItemPlacement d ~ 'DocItemInDefinitions) => Markdown -> d -> Markdown -- | Reference to the given section. -- -- Will return Nothing if sections of given doc item type are -- not assumed to be referred outside. docItemSectionRef :: DocItem di => Maybe Markdown -- | Render documentation for SubDoc. subDocToMarkdown :: HeaderLevel -> SubDoc -> Markdown -- | A hand-made anchor. data DAnchor DAnchor :: Anchor -> DAnchor -- | Comment in the doc (mostly used for licenses) data DComment DComment :: Text -> DComment -- | Repository settings for DGitRevision. newtype GitRepoSettings GitRepoSettings :: (Text -> Text) -> GitRepoSettings -- | By commit sha make up a url to that commit in remote repository. [grsMkGitRevision] :: GitRepoSettings -> Text -> Text data DGitRevision DGitRevisionKnown :: DGitRevisionInfo -> DGitRevision DGitRevisionUnknown :: DGitRevision -- | Description of something. data DDescription DDescription :: Markdown -> DDescription -- | Give a name to document block. data DName DName :: Text -> SubDoc -> DName -- | General (meta-)information about the contract such as git revision, -- contract's authors, etc. Should be relatively short (not several -- pages) because it is put somewhere close to the beginning of -- documentation. newtype DGeneralInfoSection DGeneralInfoSection :: SubDoc -> DGeneralInfoSection -- | Often there is some tuning recommended prior to rendering the -- contract, like attaching git revision info; this type designates that -- those last changes were applied. -- -- For example, at Michelson level you may want to use -- attachDocCommons. -- -- If you want no special tuning (e.g. for tests), say that explicitly -- with finalizedAsIs. data WithFinalizedDoc a -- | Some contract languages may support documentation update. class ContainsDoc a => ContainsUpdateableDoc a -- | Modify all documentation items recursively. modifyDocEntirely :: ContainsUpdateableDoc a => (SomeDocItem -> SomeDocItem) -> a -> a -- | Everything that contains doc items that can be used to render the -- documentation. class ContainsDoc a -- | Gather documentation. -- -- Calling this method directly is discouraged in prod, see -- buildDoc instead. Using this method in tests is fine though. buildDocUnfinalized :: ContainsDoc a => a -> ContractDoc -- | A function which groups a piece of doc under one doc item. type DocGrouping = SubDoc -> SomeDocItem -- | Render given contract documentation to markdown document. contractDocToMarkdown :: ContractDoc -> LText -- | Mark the code with doc as finalized without any changes. finalizedAsIs :: a -> WithFinalizedDoc a -- | Gather documenation. buildDoc :: ContainsDoc a => WithFinalizedDoc a -> ContractDoc -- | Construct and format documentation in textual form. buildMarkdownDoc :: ContainsDoc a => WithFinalizedDoc a -> LText -- | Recursevly traverse doc items and modify those that match given type. -- -- If mapper returns Nothing, doc item will remain unmodified. modifyDoc :: (ContainsUpdateableDoc a, DocItem i1, DocItem i2) => (i1 -> Maybe i2) -> a -> a morleyRepoSettings :: GitRepoSettings -- | Make DGitRevision. -- --
--   >>> :t $mkDGitRevision
--   ...
--   ... :: GitRepoSettings -> DGitRevision
--   
mkDGitRevision :: ExpQ -- | Attach common information that is available only in the end. attachDocCommons :: ContainsUpdateableDoc a => DGitRevision -> a -> WithFinalizedDoc a type Operation = Operation' Instr type Value = Value' Instr data BigMap k v -- | Phantom type that represents the ID of a big_map with keys of type -- k and values of type v. newtype BigMapId (k2 :: k) (v :: k1) BigMapId :: Natural -> BigMapId (k2 :: k) (v :: k1) [unBigMapId] :: BigMapId (k2 :: k) (v :: k1) -> Natural -- | Ticket type. data Ticket arg Ticket :: Address -> arg -> Natural -> Ticket arg [tTicketer] :: Ticket arg -> Address [tData] :: Ticket arg -> arg [tAmount] :: Ticket arg -> Natural -- | Since Contract name is used to designate contract code, lets -- call analogy of TContract type as follows. -- -- Note that type argument always designates an argument of entrypoint. -- If a contract has explicit default entrypoint (and no root -- entrypoint), ContractRef referring to it can never have the -- entire parameter as its type argument. data ContractRef arg ContractRef :: Address -> SomeEntrypointCall arg -> ContractRef arg [crAddress] :: ContractRef arg -> Address [crEntrypoint] :: ContractRef arg -> SomeEntrypointCall arg type WellTypedToT a = (IsoValue a, WellTyped ToT a) type SomeEntrypointCall arg = SomeEntrypointCallT ToT arg type EntrypointCall param arg = EntrypointCallT ToT param ToT arg -- | Isomorphism between Michelson values and plain Haskell types. -- -- Default implementation of this typeclass converts ADTs to Michelson -- "pair"s and "or"s. class WellTypedToT a => IsoValue a where { -- | Type function that converts a regular Haskell type into a T -- type. type family ToT a :: T; type ToT a = GValueType Rep a; } -- | Converts a Haskell structure into Value representation. toVal :: IsoValue a => a -> Value (ToT a) -- | Converts a Value into Haskell type. fromVal :: IsoValue a => Value (ToT a) -> a -- | Type function that converts a regular Haskell type into a T -- type. type family ToT a :: T -- | Replace type argument of ContractRef with isomorphic one. coerceContractRef :: ToT a ~ ToT b => ContractRef a -> ContractRef b -- | Constraint for instrConstruct and gInstrConstructStack. type InstrConstructC dt = (GenericIsoValue dt, GInstrConstruct Rep dt '[] :: [Type]) -- | Types of all fields in a datatype. type ConstructorFieldTypes dt = GFieldTypes Rep dt '[] :: [Type] -- | Require this type to be homomorphic. class IsHomomorphic (a :: k) -- | Require two types to be built from the same type constructor. -- -- E.g. HaveCommonTypeCtor (Maybe Integer) (Maybe Natural) is -- defined, while HaveCmmonTypeCtor (Maybe Integer) [Integer] is -- not. class HaveCommonTypeCtor (a :: k) (b :: k1) -- | Doc element with description of a type. data DType [DType] :: forall a. TypeHasDoc a => Proxy a -> DType -- | Data hides some type implementing TypeHasDoc. data SomeTypeWithDoc [SomeTypeWithDoc] :: forall td. TypeHasDoc td => Proxy td -> SomeTypeWithDoc -- | Description for a Haskell type appearing in documentation. class (Typeable a, SingI TypeDocFieldDescriptions a, FieldDescriptionsValid TypeDocFieldDescriptions a a) => TypeHasDoc a where { -- | Description of constructors and fields of a. -- -- See FieldDescriptions documentation for an example of usage. -- -- Descriptions will be checked at compile time to make sure that only -- existing constructors and fields are referenced. -- -- For that check to work instance Generic a is required -- whenever TypeDocFieldDescriptions is not empty. -- -- For implementation of the check see FieldDescriptionsValid type -- family. type family TypeDocFieldDescriptions a :: FieldDescriptions; type TypeDocFieldDescriptions a = '[] :: [(Symbol, (Maybe Symbol, [(Symbol, Symbol)]))]; } -- | Name of type as it appears in definitions section. -- -- Each type must have its own unique name because it will be used in -- identifier for references. -- -- Default definition derives name from Generics. If it does not fit, -- consider defining this function manually. (We tried using -- Data.Data for this, but it produces names including module -- names which is not do we want). typeDocName :: TypeHasDoc a => Proxy a -> Text -- | Explanation of a type. Markdown formatting is allowed. typeDocMdDescription :: TypeHasDoc a => Markdown -- | How reference to this type is rendered, in Markdown. -- -- Examples: -- -- -- -- Consider using one of the following functions as default -- implementation; which one to use depends on number of type arguments -- in your type: -- -- -- -- If none of them fits your purposes precisely, consider using -- customTypeDocMdReference. typeDocMdReference :: TypeHasDoc a => Proxy a -> WithinParens -> Markdown -- | All types which this type directly contains. -- -- Used in automatic types discovery. typeDocDependencies :: TypeHasDoc a => Proxy a -> [SomeDocDefinitionItem] -- | For complex types - their immediate Haskell representation. -- -- For primitive types set this to Nothing. -- -- For homomorphic types use homomorphicTypeDocHaskellRep -- implementation. -- -- For polymorphic types consider using concreteTypeDocHaskellRep -- as implementation. -- -- Modifier haskellRepNoFields can be used to hide names of -- fields, beneficial for newtypes. -- -- Use haskellRepAdjust or haskellRepMap for more involved -- adjustments. -- -- Also, consider defining an instance of -- TypeHasFieldNamingStrategy instead of defining this method -- -- the former can be used downstream, e.g. in lorentz, for better naming -- consistency. typeDocHaskellRep :: TypeHasDoc a => TypeDocHaskellRep a -- | Final michelson representation of a type. -- -- For homomorphic types use homomorphicTypeDocMichelsonRep -- implementation. -- -- For polymorphic types consider using -- concreteTypeDocMichelsonRep as implementation. typeDocMichelsonRep :: TypeHasDoc a => TypeDocMichelsonRep a -- | Description of constructors and fields of a. -- -- See FieldDescriptions documentation for an example of usage. -- -- Descriptions will be checked at compile time to make sure that only -- existing constructors and fields are referenced. -- -- For that check to work instance Generic a is required -- whenever TypeDocFieldDescriptions is not empty. -- -- For implementation of the check see FieldDescriptionsValid type -- family. type family TypeDocFieldDescriptions a :: FieldDescriptions -- | Field naming strategy used by a type. id by default. -- -- Some common options include: > typeFieldNamingStrategy = -- stripFieldPrefix > typeFieldNamingStrategy = toSnake . dropPrefix -- -- This is used by the default implementation of typeDocHaskellRep -- and intended to be reused downstream. -- -- You can also use DerivingVia together with -- FieldCamelCase and FieldSnakeCase to easily define -- instances of this class: -- --
--   data MyType = ... deriving TypeHasFieldNamingStrategy via FieldCamelCase
--   
class TypeHasFieldNamingStrategy (a :: k) typeFieldNamingStrategy :: TypeHasFieldNamingStrategy a => Text -> Text -- | Fully render Michelson representation of a type. typeDocBuiltMichelsonRep :: TypeHasDoc a => Proxy a -> Builder -- | Create a DType in form suitable for putting to -- typeDocDependencies. dTypeDep :: TypeHasDoc t => SomeDocDefinitionItem -- | Shortcut for DStorageType. dStorage :: TypeHasDoc store => DStorageType -- | Render a reference to a type which consists of type constructor (you -- have to provide name of this type constructor and documentation for -- the whole type) and zero or more type arguments. customTypeDocMdReference :: (Text, DType) -> [DType] -> WithinParens -> Markdown -- | Derive typeDocMdReference, for homomorphic types only. homomorphicTypeDocMdReference :: (Typeable t, TypeHasDoc t, IsHomomorphic t) => Proxy t -> WithinParens -> Markdown -- | Derive typeDocMdReference, for polymorphic type with one type -- argument, like Maybe Integer. poly1TypeDocMdReference :: forall (t :: Type -> Type) r a. (r ~ t a, Typeable t, Each '[TypeHasDoc] '[r, a], IsHomomorphic t) => Proxy r -> WithinParens -> Markdown -- | Derive typeDocMdReference, for polymorphic type with two type -- arguments, like Lambda Integer Natural. 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 -- | Implement typeDocDependencies via getting all immediate fields -- of a datatype. -- -- Note: this will not include phantom types, I'm not sure yet how this -- scenario should be handled (@martoon). genericTypeDocDependencies :: (Generic a, GTypeHasDoc (Rep a)) => Proxy a -> [SomeDocDefinitionItem] -- | Implement typeDocHaskellRep for a homomorphic type. -- -- Note that it does not require your type to be of IsHomomorphic -- instance, which can be useful for some polymorphic types which, for -- documentation purposes, we want to consider homomorphic. -- -- Example: Operation is in fact polymorphic, but we don't want -- this fact to be reflected in the documentation. homomorphicTypeDocHaskellRep :: (Generic a, GTypeHasDoc (Rep a)) => TypeDocHaskellRep a -- | Implement typeDocHaskellRep on example of given concrete type. -- -- This is a best effort attempt to implement typeDocHaskellRep -- for polymorphic types, as soon as there is no simple way to preserve -- type variables when automatically deriving Haskell representation of a -- type. concreteTypeDocHaskellRep :: (Typeable a, GenericIsoValue a, GTypeHasDoc (Rep a), HaveCommonTypeCtor b a) => TypeDocHaskellRep b -- | Version of concreteTypeDocHaskellRep which does not ensure -- whether the type for which representation is built is any similar to -- the original type which you implement a TypeHasDoc instance -- for. unsafeConcreteTypeDocHaskellRep :: (Typeable a, GenericIsoValue a, GTypeHasDoc (Rep a)) => TypeDocHaskellRep b -- | Erase fields from Haskell datatype representation. -- -- Use this when rendering fields names is undesired. haskellRepNoFields :: TypeDocHaskellRep a -> TypeDocHaskellRep a -- | Map over fields with stripFieldPrefix. Equivalent to -- haskellRepMap stripFieldPrefix. Left for compatibility. haskellRepStripFieldPrefix :: TypeDocHaskellRep a -> TypeDocHaskellRep a -- | Add field name for newtype. -- -- Since newtype field is automatically erased. Use this -- function to add the desired field name. haskellAddNewtypeField :: Text -> TypeDocHaskellRep a -> TypeDocHaskellRep a -- | Implement typeDocMichelsonRep for homomorphic type. homomorphicTypeDocMichelsonRep :: KnownIsoT a => TypeDocMichelsonRep a -- | Implement typeDocMichelsonRep on example of given concrete -- type. -- -- This function exists for the same reason as -- concreteTypeDocHaskellRep. concreteTypeDocMichelsonRep :: forall {k} a (b :: k). (Typeable a, KnownIsoT a, HaveCommonTypeCtor b a) => TypeDocMichelsonRep b -- | Version of unsafeConcreteTypeDocHaskellRep which does not -- ensure whether the type for which representation is built is any -- similar to the original type which you implement a TypeHasDoc -- instance for. unsafeConcreteTypeDocMichelsonRep :: forall {k} a (b :: k). (Typeable a, KnownIsoT a) => TypeDocMichelsonRep b -- | error that takes Text as an argument. error :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => Text -> a -- | 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 -- | 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]) -- | Statically safe converter between Integral types, which is just -- intCast under the hood. -- -- It is used to turn the value of type a into the value of type -- b such that a is subtype of b. It is needed -- to prevent silent unsafe conversions. -- --
--   >>> fromIntegral @Int @Word 1
--   ...
--   ... error:
--   ... Can not safely cast 'Int' to 'Word':
--   ... 'Int' is not a subtype of 'Word'
--   ...
--   
--   >>> fromIntegral @Word @Natural 1
--   1
--   
fromIntegral :: (Integral a, Integral b, CheckIntSubType a b) => a -> b mkBigMap :: ToBigMap m => m -> BigMap (ToBigMapKey m) (ToBigMapValue m) -- |
--   >>> :t [annQ||]
--   ... :: forall {k} {tag :: k}. Annotation tag
--   
-- --
--   >>> :t [annQ|abc|]
--   ... :: forall {k} {tag :: k}. Annotation tag
--   
annQ :: QuasiQuoter -- | A convenience synonym for field Annotation type FieldAnn = Annotation FieldTag -- | Similar to unsafe converter, but with the use of monadic -- fail and returning the result wrapped in a monad. unsafeM :: (MonadFail m, Buildable a) => Either a b -> m b -- | Unsafe converter from Either, which uses buildable Left -- to throw an exception with error. -- -- It is primarily needed for making unsafe counter-parts of safe -- functions. In particular, for replacing unsafeFName x = either -- (error . pretty) id constructors and converters, which produce -- many similar functions at the call site, with unsafe . fName $ -- x. unsafe :: (HasCallStack, Buildable a) => Either a b -> b -- | A version of show that requires the value to have a -- human-readable Show instance. show :: forall b a. (PrettyShow a, Show a, IsString b) => a -> b -- | An open type family for types having a human-readable Show -- representation. The kind is Constraint in case we need to -- further constrain the instance, and also for convenience to avoid -- explicitly writing ~ 'True everywhere. type family PrettyShow a -- | Statically safe converter between Integral types checking for -- overflow/underflow. Returns Right value if conversion does -- not produce overflow/underflow and Left ArithException with -- corresponding ArithException -- (Overflow/Underflow) otherwise. -- -- Note the function is strict in its argument. -- --
--   >>> fromIntegralNoOverflow @Int @Word 123
--   Right 123
--   
--   >>> fromIntegralNoOverflow @Int @Word (-123)
--   Left arithmetic underflow
--   
--   >>> fromIntegralNoOverflow @Int @Integer (-123)
--   Right (-123)
--   
--   >>> fromIntegralNoOverflow @Int @Natural (-123)
--   Left arithmetic underflow
--   
--   >>> fromIntegralNoOverflow @Int @Int8 127
--   Right 127
--   
--   >>> fromIntegralNoOverflow @Int @Int8 128
--   Left arithmetic overflow
--   
fromIntegralNoOverflow :: (Integral a, Integral b) => a -> Either ArithException b -- | Runtime-safe converter between Integral types, which is just -- fromIntegral under the hood. -- -- It is needed to semantically distinguish usages, where overflow is -- intended, from those that have to fail on overflow. E.g. Int8 -- -> Word8 with intended bits reinterpretation from lossy -- Integer -> Int. -- --
--   >>> fromIntegralOverflowing @Int8 @Word8 (-1)
--   255
--   
--   >>> fromIntegralOverflowing @Natural @Int8 450
--   -62
--   
-- -- Please note that like fromIntegral from base, this -- will throw on some conversions! -- --
--   >>> fromIntegralOverflowing @Int @Natural (-1)
--   *** Exception: arithmetic underflow
--   
-- -- See fromIntegralNoOverflow for an alternative that doesn't -- throw. fromIntegralOverflowing :: (Integral a, Num b) => a -> b -- | Statically safe converter between Integral and RealFrac -- types. Could be applied to cast common types like Float, -- Double and Scientific. -- -- It is primarily needed to replace usages of fromIntegral, which -- are safe actually as integral numbers are being casted to fractional -- ones. fromIntegralToRealFrac :: (Integral a, RealFrac b, CheckIntSubType a Integer) => a -> b -- | Statically safe converter between Integral types, which is just -- intCastMaybe under the hood. Unlike fromIntegral accept -- any a and b. Return Just value if -- conversion is possible at runtime and Nothing otherwise. fromIntegralMaybe :: (Integral a, Integral b, Bits a, Bits b) => a -> Maybe b -- | Constraint synonym equivalent to IsIntSubType a b ~ -- 'True, but with better error messages type CheckIntSubType a b = (CheckIntSubTypeErrors a b IsIntSubType a b, IsIntSubType a b ~ 'True) -- | A version of all that works on NonEmpty, thus doesn't -- require BooleanMonoid instance. -- --
--   >>> all1 (\x -> if x > 50 then Yay else Nay) $ 100 :| replicate 10 51
--   Yay
--   
all1 :: Boolean b => (a -> b) -> NonEmpty a -> b -- | A version of any that works on NonEmpty, thus doesn't -- require BooleanMonoid instance. -- --
--   >>> any1 (\x -> if x > 50 then Yay else Nay) $ 50 :| replicate 10 0
--   Nay
--   
any1 :: Boolean b => (a -> b) -> NonEmpty a -> b -- | Generalized all. -- --
--   >>> all (\x -> if x > 50 then Yay else Nay) [1..100]
--   Nay
--   
all :: (Container c, BooleanMonoid b) => (Element c -> b) -> c -> b -- | Generalized any. -- --
--   >>> any (\x -> if x > 50 then Yay else Nay) [1..100]
--   Yay
--   
any :: (Container c, BooleanMonoid b) => (Element c -> b) -> c -> b -- | A version of and that works on NonEmpty, thus doesn't -- require BooleanMonoid instance. -- --
--   >>> and1 $ Yay :| [Nay]
--   Nay
--   
and1 :: Boolean a => NonEmpty a -> a -- | A version of or that works on NonEmpty, thus doesn't -- require BooleanMonoid instance. -- --
--   >>> or1 $ Yay :| [Nay]
--   Yay
--   
or1 :: Boolean a => NonEmpty a -> a -- | Generalized boolean operators. -- -- This is useful for defining things that behave like booleans, e.g. -- predicates, or EDSL for predicates. -- --
--   >>> Yay && Nay
--   Nay
--   
--   >>> and1 $ Yay :| replicate 9 Yay
--   Yay
--   
-- -- There are also instances for these types lifted into IO and -- (->) a: -- --
--   >>> (const Yay) && (const Nay) $ ()
--   Nay
--   
--   >>> (const Yay) || (const Nay) $ ()
--   Yay
--   
class Boolean a -- | Generalized True and False. -- -- This is useful to complete the isomorphism between regular and -- generalized booleans. It's a separate class because not all -- boolean-like things form a monoid. -- --
--   >>> or $ replicate 10 Nay
--   Nay
--   
class Boolean a => BooleanMonoid a false :: BooleanMonoid a => a true :: BooleanMonoid a => a -- | A generalized version of All monoid wrapper. -- --
--   >>> All Nay <> All Nay
--   All {getAll = Nay}
--   
--   >>> All Yay <> All Nay
--   All {getAll = Nay}
--   
--   >>> All Yay <> All Yay
--   All {getAll = Yay}
--   
newtype All a All :: a -> All a [getAll] :: All a -> a -- | A generalized version of Any monoid wrapper. -- --
--   >>> Any Nay <> Any Nay
--   Any {getAny = Nay}
--   
--   >>> Any Yay <> Any Nay
--   Any {getAny = Yay}
--   
--   >>> Any Yay <> Any Yay
--   Any {getAny = Yay}
--   
newtype Any a Any :: a -> Any a [getAny] :: Any a -> a -- | A newtype for deriving a Boolean instance for any -- Applicative type constructor using DerivingVia. newtype ApplicativeBoolean (f :: k -> Type) (bool :: k) ApplicativeBoolean :: f bool -> ApplicativeBoolean (f :: k -> Type) (bool :: k) -- | Shorter alias for pure (). -- --
--   >>> pass :: Maybe ()
--   Just ()
--   
pass :: Applicative f => f () -- | Similar to some, but reflects in types that a non-empty list is -- returned. someNE :: Alternative f => f a -> f (NonEmpty a) -- | 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 $! -- | 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 -- | 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 <<$>> -- | Lifted to MonadIO version of newEmptyMVar. newEmptyMVar :: MonadIO m => m (MVar a) -- | Lifted to MonadIO version of newMVar. newMVar :: MonadIO m => a -> m (MVar a) -- | Lifted to MonadIO version of putMVar. putMVar :: MonadIO m => MVar a -> a -> m () -- | Lifted to MonadIO version of readMVar. readMVar :: 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 takeMVar. takeMVar :: MonadIO m => MVar a -> m a -- | Lifted to MonadIO version of tryPutMVar. tryPutMVar :: MonadIO m => MVar a -> a -> m Bool -- | Lifted to MonadIO version of tryReadMVar. tryReadMVar :: MonadIO m => MVar a -> m (Maybe a) -- | Lifted to MonadIO version of tryTakeMVar. tryTakeMVar :: MonadIO m => MVar a -> m (Maybe a) -- | Lifted to MonadIO version of atomically. atomically :: MonadIO m => STM a -> m a -- | Lifted to MonadIO version of newTVarIO. newTVarIO :: MonadIO m => a -> m (TVar a) -- | Lifted to MonadIO version of readTVarIO. readTVarIO :: MonadIO m => TVar a -> m a -- | Like modifyMVar, but modification is specified as a -- State computation. -- -- This method is strict in produced s value. updateMVar' :: MonadIO m => MVar s -> StateT s IO a -> m a -- | Like 'modifyTVar'', but modification is specified as a State -- monad. updateTVar' :: TVar s -> StateT s STM a -> STM a -- | Lifted version of exitWith. exitWith :: MonadIO m => ExitCode -> m a -- | Lifted version of exitFailure. exitFailure :: MonadIO m => m a -- | Lifted version of exitSuccess. exitSuccess :: MonadIO m => m a -- | 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 appendFile. appendFile :: MonadIO m => FilePath -> Text -> m () -- | Lifted version of getLine. getLine :: MonadIO m => m Text -- | Lifted version of openFile. -- -- See also withFile for more information. openFile :: MonadIO m => FilePath -> IOMode -> m Handle -- | Close a file handle -- -- See also withFile for more information. hClose :: MonadIO m => Handle -> m () -- | 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 -- | Lifted version of newIORef. newIORef :: MonadIO m => a -> m (IORef a) -- | Lifted version of readIORef. readIORef :: MonadIO m => IORef a -> m a -- | Lifted version of writeIORef. writeIORef :: MonadIO m => IORef a -> a -> m () -- | 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 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 atomicWriteIORef. atomicWriteIORef :: MonadIO m => IORef a -> a -> 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 () -- | Monadic version of whenJust. whenJustM :: Monad m => m (Maybe a) -> (a -> m ()) -> m () -- | 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 -- | 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 () -- | Monadic version of whenNothing. whenNothingM :: Monad m => m (Maybe a) -> m a -> m a -- | Monadic version of whenNothingM_. whenNothingM_ :: Monad m => m (Maybe a) -> m () -> m () -- | 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 -- | 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 -- | Maps left part of Either to Maybe. -- --
--   >>> leftToMaybe (Left True)
--   Just True
--   
--   >>> leftToMaybe (Right "aba")
--   Nothing
--   
leftToMaybe :: Either l r -> Maybe l -- | Maps right part of Either to Maybe. -- --
--   >>> rightToMaybe (Left True)
--   Nothing
--   
--   >>> rightToMaybe (Right "aba")
--   Just "aba"
--   
rightToMaybe :: Either l r -> Maybe 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 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 -- | Monadic version of whenLeft. whenLeftM :: Monad m => m (Either l r) -> (l -> m ()) -> m () -- | Monadic version of whenRight. whenRightM :: Monad m => m (Either l r) -> (r -> m ()) -> m () -- | Shorter and more readable alias for flip runReaderT. usingReaderT :: r -> ReaderT r m a -> m a -- | Shorter and more readable alias for flip runReader. usingReader :: r -> Reader r a -> a -- | Shorter and more readable alias for flip runStateT. usingStateT :: s -> StateT s m a -> m (a, s) -- | Shorter and more readable alias for flip runState. usingState :: s -> State s a -> (a, s) -- | 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 -- | 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 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 execState. It's not shorter but sometimes more -- readable. Done by analogy with using* functions family. executingState :: s -> State s a -> s -- | Lift a Maybe to the MaybeT monad hoistMaybe :: forall (m :: Type -> Type) a. Applicative m => Maybe a -> MaybeT m a -- | Lift a Either to the ExceptT monad hoistEither :: forall (m :: Type -> Type) e a. Applicative m => Either e a -> ExceptT e m a -- | Extracts Monoid value from Maybe returning mempty -- if Nothing. -- --
--   >>> maybeToMonoid (Just [1,2,3] :: Maybe [Int])
--   [1,2,3]
--   
--   >>> maybeToMonoid (Nothing :: Maybe [Int])
--   []
--   
maybeToMonoid :: Monoid m => Maybe m -> m -- | 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 type family OneItem x -- | 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 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 notElem :: Container t => Element t -> t -> Bool find :: Container t => (Element t -> Bool) -> t -> Maybe (Element t) safeHead :: Container t => t -> Maybe (Element t) safeMaximum :: Container t => t -> Maybe (Element t) safeMinimum :: Container t => t -> Maybe (Element t) safeFoldr1 :: Container t => (Element t -> Element t -> Element t) -> t -> Maybe (Element t) safeFoldl1 :: Container t => (Element t -> Element t -> Element t) -> t -> Maybe (Element 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 -- | Type class for data types that can be constructed from a list. class FromList l where { type family ListElement l; type family FromListC l; type ListElement l = Item l; type FromListC l = (); } -- | Make a value from list. -- -- For simple types like '[]' and Set: -- --
--   toList . fromList ≡ id
--   fromList . toList ≡ id
--   
--   
-- -- For map-like types: -- --
--   toPairs . fromList ≡ id
--   fromList . toPairs ≡ id
--   
--   
fromList :: FromList l => [ListElement l] -> l type family ListElement l type family FromListC l -- | 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] -- | 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 -- | 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 -- | 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 -- | Constrained to Container version of traverse_. -- --
--   >>> traverse_ putTextLn ["foo", "bar"]
--   foo
--   bar
--   
traverse_ :: (Container t, Applicative f) => (Element t -> f b) -> t -> f () -- | 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 mapM_. -- --
--   >>> mapM_ print [True, False]
--   True
--   False
--   
mapM_ :: (Container t, Monad m) => (Element t -> m b) -> t -> m () -- | 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 sequenceA_. -- --
--   >>> sequenceA_ [putTextLn "foo", print True]
--   foo
--   True
--   
sequenceA_ :: (Container t, Applicative f, Element t ~ f a) => t -> f () -- | 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 asum. -- --
--   >>> asum [Nothing, Just [False, True], Nothing, Just [True]]
--   Just [False,True]
--   
asum :: (Container t, Alternative f, Element t ~ f a) => t -> f a -- | 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 -- | 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 -- | 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 -- | 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 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 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 -- | 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]) -- | 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 () -- | Monadic version of whenNotNull. whenNotNullM :: Monad m => m [a] -> (NonEmpty a -> m ()) -> m () -- | A variant of foldl that has no base case, and thus may only -- be applied to NonEmpty. -- --
--   >>> foldl1 (+) (1 :| [2,3,4,5])
--   15
--   
foldl1 :: (a -> a -> a) -> NonEmpty a -> a -- | A variant of foldr that has no base case, and thus may only -- be applied to NonEmpty. -- --
--   >>> foldr1 (+) (1 :| [2,3,4,5])
--   15
--   
foldr1 :: (a -> a -> a) -> NonEmpty a -> a -- | The least element of a NonEmpty with respect to the given -- comparison function. minimumBy :: (a -> a -> Ordering) -> NonEmpty a -> a -- | The least element of a NonEmpty. -- --
--   >>> minimum (1 :| [2,3,4,5])
--   1
--   
minimum :: Ord a => NonEmpty a -> a -- | The largest element of a NonEmpty with respect to the given -- comparison function. maximumBy :: (a -> a -> Ordering) -> NonEmpty a -> a -- | The largest element of a NonEmpty. -- --
--   >>> maximum (1 :| [2,3,4,5])
--   5
--   
maximum :: Ord a => NonEmpty a -> a -- | 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 -- | 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 -- | Generate a pure value which, when forced, will synchronously throw the -- exception wrapped into Bug data type. bug :: (HasCallStack, Exception e) => e -> a -- | Throws error for Maybe if Nothing is given. Operates -- over MonadError. note :: MonadError e m => e -> Maybe a -> m a -- | Lifted alias for evaluate with clearer name. evaluateWHNF :: MonadIO m => a -> m a -- | Like evaluateWNHF but discards value. evaluateWHNF_ :: MonadIO m => a -> m () -- | Alias for evaluateWHNF . force with clearer name. evaluateNF :: (NFData a, MonadIO m) => a -> m a -- | Alias for evaluateWHNF . rnf. Similar to evaluateNF -- but discards resulting value. evaluateNF_ :: (NFData a, MonadIO m) => a -> 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 () -- | 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 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 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 () -- | 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] -- | 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 ordNub but also sorts a list. -- --
--   >>> sortNub [3, 3, 3, 2, 2, -1, 1]
--   [-1,1,2,3]
--   
sortNub :: Ord a => [a] -> [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] -- | Support class to overload writing of string like values. class Print a -- | Write a string like value a to a supplied Handle. hPutStr :: (Print a, MonadIO m) => Handle -> 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 to stdout/. putStr :: (Print a, MonadIO m) => a -> m () -- | Write a string like value to stdout appending a newline -- character. putStrLn :: (Print a, MonadIO m) => a -> m () -- | Lifted version of print. print :: forall a m. (MonadIO m, Show a) => a -> m () -- | Lifted version of hPrint hPrint :: (MonadIO m, Show a) => Handle -> a -> m () -- | Specialized to Text version of putStr or forcing type -- inference. putText :: 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. putLText :: MonadIO m => Text -> m () -- | Specialized to Text version of putStrLn or forcing type -- inference. putLTextLn :: MonadIO m => Text -> m () -- | Similar to undefined but data type. data Undefined Undefined :: Undefined -- | Version of trace that leaves a warning and takes Text. trace :: Text -> a -> a -- | Version of traceShow that leaves a warning. traceShow :: Show a => a -> b -> b -- | Version of traceShowId that leaves a warning. traceShowId :: Show a => 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. Useful to tag -- printed data, for instance: -- --
--   traceShowIdWith ("My data: ", ) (veryLargeExpression)
--   
traceShowIdWith :: Show s => (a -> s) -> a -> a -- | Version of traceShowM that leaves a warning. traceShowM :: (Show a, Monad m) => a -> m () -- | Version of traceM that leaves a warning and takes Text. traceM :: Monad m => Text -> m () -- | Version of traceId that leaves a warning. traceId :: Text -> Text -- | Type class for converting other strings to String. class ToString a toString :: ToString a => a -> String -- | Type class for converting other strings to Text. class ToLText a toLText :: ToLText a => a -> Text -- | Type class for converting other strings to Text. class ToText a toText :: ToText a => a -> Text -- | 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 synonym for ByteString. type LByteString = ByteString -- | Type synonym for Text. type LText = Text -- | 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 -- | 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 -- | 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 ... -- | 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 -- | Replace an invalid input byte with the Unicode replacement character -- U+FFFD. lenientDecode :: OnDecodeError -- | Throw a UnicodeException if decoding fails. strictDecode :: OnDecodeError -- | A handler for a decoding error. type OnDecodeError = OnError Word8 Char -- | Function type for handling a coding error. It is supplied with two -- inputs: -- -- -- -- If the handler returns a value wrapped with Just, that value -- will be used in the output as the replacement for the invalid input. -- If it returns Nothing, no value will be used in the output. -- -- Should the handler need to abort processing, it should use -- error or throw an exception (preferably a -- UnicodeException). It may use the description provided to -- construct a more helpful error report. type OnError a b = String -> Maybe a -> Maybe b -- | An exception type for representing Unicode encoding errors. data UnicodeException -- | 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 -- | O(n) Breaks a Text up into a list of Texts at -- newline Chars. The resulting strings do not contain newlines. lines :: Text -> [Text] -- | O(n) Joins lines, after appending a terminating newline to -- each. unlines :: [Text] -> Text -- | O(n) Joins words using single space characters. unwords :: [Text] -> Text -- | O(n) Breaks a Text up into a list of words, delimited by -- Chars representing white space. words :: Text -> [Text] -- | O(c) Convert a strict Text into a lazy Text. fromStrict :: Text -> Text -- | Strict version of modifyTVar. modifyTVar' :: TVar a -> (a -> a) -> STM () -- | Synonym for throw throwM :: (MonadThrow m, Exception e) => e -> m a -- | Same as upstream catch, but will not catch asynchronous -- exceptions catch :: (MonadCatch m, Exception e) => m a -> (e -> m a) -> m a -- | catch specialized to catch all synchronous exception catchAny :: MonadCatch m => m a -> (SomeException -> m a) -> m a -- | Flipped version of catchAny handleAny :: MonadCatch m => (SomeException -> m a) -> m a -> m a -- | Same as upstream try, but will not catch asynchronous -- exceptions try :: (MonadCatch m, Exception e) => m a -> m (Either e a) -- | try specialized to catch all synchronous exceptions tryAny :: MonadCatch m => m a -> m (Either SomeException a) -- | Async safe version of onException onException :: MonadMask m => m a -> m b -> m a -- | Async safe version of bracket bracket :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c -- | Async safe version of bracket_ bracket_ :: MonadMask m => m a -> m b -> m c -> m c -- | Async safe version of finally finally :: MonadMask m => m a -> m b -> m a -- | Async safe version of bracketOnError bracketOnError :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c -- | withState f m executes action m on a state -- modified by applying f. -- -- withState :: (s -> s) -> State s a -> State s 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 state, discarding the final value. -- -- execStateT :: Monad m => StateT s m a -> s -> m s -- | Evaluate a state computation with the given initial state and return -- the final state, discarding the final value. -- -- execState :: State s a -> s -> s -- | Evaluate a state computation with the given initial state and return -- the final 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 value, discarding the final state. -- -- evalState :: State s a -> s -> a -- | Runs a Reader and extracts the final value from it. (The -- inverse of reader.) runReader :: Reader r a -> r -> a -- | A variant of modify in which the computation is strict in the -- new state. modify' :: MonadState s m => (s -> s) -> m () -- | Replicate the old behavior of (#), which ignores anything -- after failing instructions. Indigo relies on this. TODO #62: -- reconsider this. (#) :: (a :-> b) -> (b :-> c) -> a :-> c infixl 8 # -- | 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. data StackVars (stk :: [Type]) [StkElements] :: Rec StkEl stk -> StackVars stk [FailureStack] :: StackVars stk type StackVars' stk = 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, KnownIsoT a) => StkEl a [Ref] :: (KnownValue a, KnownIsoT 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), RecordToList (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 -- | Produce evidence of InstrDeconstructC for a concrete input -- stack, and run a computation with it. withInstrDeconstructC :: forall a st r. InstrDeconstructCGeneral a => (InstrDeconstructCClass a st => r) -> r 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 GenCodeHooks GenCodeHooks :: (forall inp out. Text -> (inp :-> out) -> inp :-> out) -> (forall inp out. Text -> (inp :-> out) -> inp :-> out) -> (forall inp out. Text -> (inp :-> out) -> inp :-> out) -> GenCodeHooks [gchStmtHook] :: GenCodeHooks -> forall inp out. Text -> (inp :-> out) -> inp :-> out [gchAuxiliaryHook] :: GenCodeHooks -> forall inp out. Text -> (inp :-> out) -> inp :-> out [gchExprHook] :: GenCodeHooks -> forall inp out. Text -> (inp :-> out) -> inp :-> out data MetaData inp MetaData :: StackVars inp -> DecomposedObjects -> GenCodeHooks -> MetaData inp [mdStack] :: MetaData inp -> StackVars inp [mdObjects] :: MetaData inp -> DecomposedObjects [mdHooks] :: MetaData inp -> GenCodeHooks 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 emptyGenCodeHooks :: GenCodeHooks stmtHook :: forall inp out any. MetaData any -> Text -> (inp :-> out) -> inp :-> out stmtHookState :: Text -> IndigoState inp out -> IndigoState inp out auxiliaryHook :: forall inp out any. MetaData any -> Text -> (inp :-> out) -> inp :-> out auxiliaryHookState :: Text -> IndigoState inp out -> IndigoState inp out exprHook :: forall inp out any. MetaData any -> Text -> (inp :-> out) -> inp :-> out exprHookState :: Text -> 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 -- | Version of # which performs some optimizations immediately. -- -- In particular, this avoids glueing Nops. (##) :: (a :-> b) -> (b :-> c) -> a :-> c -- | 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), HasDupableGetters (GetFieldType dt fname), HasField (GetFieldType dt fname) targetName targetType) => Label fname -> FieldLens dt targetName targetType -- | 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 r, KnownValue r) => Expr n -> Expr m -> Expr r [Sub] :: (ArithOpHs Sub n m r, KnownValue r) => Expr n -> Expr m -> Expr r [Mul] :: (ArithOpHs Mul n m r, KnownValue r) => Expr n -> Expr m -> Expr r [Div] :: (KnownValue ratio, ArithOpHs EDiv n m (Maybe (ratio, reminder))) => Expr n -> Expr m -> Proxy reminder -> Expr ratio [Mod] :: (KnownValue reminder, ArithOpHs EDiv n m (Maybe (ratio, reminder))) => Expr n -> Expr m -> Proxy ratio -> Expr reminder [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 r, KnownValue r) => Expr n -> Expr m -> Expr r [Lsr] :: (ArithOpHs Lsr n m r, KnownValue r) => Expr n -> Expr m -> Expr r [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 r, KnownValue r) => Expr n -> Expr m -> Expr r [Xor] :: (ArithOpHs Xor n m r, KnownValue r) => Expr n -> Expr m -> Expr r [And] :: (ArithOpHs And n m r, KnownValue r) => Expr n -> Expr m -> Expr r [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, Dupable key, IsError err, Buildable 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), RecordToList (ConstructorFieldTypes dt), KnownValue dt) => Proxy dt -> Rec Expr (ConstructorFieldTypes dt) -> Expr dt [ConstructWithoutNamed] :: ComplexObjectC dt => Proxy 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 (Packed a) [Unpack] :: NiceUnpackedValue a => Expr (Packed a) -> Expr (Maybe a) [PackRaw] :: NicePackedValue a => Expr a -> Expr ByteString [UnpackRaw] :: 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, IsoValue (ContractRef p), ToTAddress p vd addr, ToT addr ~ ToT Address) => Proxy vd -> Expr addr -> Expr (Maybe (ContractRef p)) [Self] :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p, IsoValue (ContractRef p), IsNotInView) => Expr (ContractRef p) [SelfAddress] :: Expr Address [ContractAddress] :: Expr (ContractRef p) -> Expr Address [ContractCallingUnsafe] :: (NiceParameter arg, IsoValue (ContractRef arg)) => EpName -> Expr Address -> Expr (Maybe (ContractRef arg)) [RunFutureContract] :: (NiceParameter p, IsoValue (ContractRef p)) => Expr (FutureContract p) -> Expr (Maybe (ContractRef p)) [ImplicitAccount] :: Expr KeyHash -> Expr (ContractRef ()) [ConvertEpAddressToContract] :: (NiceParameter p, IsoValue (ContractRef 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] :: BytesLike bs => Expr PublicKey -> Expr (TSignature bs) -> Expr bs -> Expr Bool [Sha256] :: BytesLike bs => Expr bs -> Expr (Hash Sha256 bs) [Sha512] :: BytesLike bs => Expr bs -> Expr (Hash Sha512 bs) [Blake2b] :: BytesLike bs => Expr bs -> Expr (Hash Blake2b bs) [Sha3] :: BytesLike bs => Expr bs -> Expr (Hash Sha3 bs) [Keccak] :: BytesLike bs => Expr bs -> Expr (Hash Keccak bs) [HashKey] :: Expr PublicKey -> Expr KeyHash [ChainId] :: Expr ChainId [Level] :: Expr Natural [Now] :: Expr Timestamp [Amount] :: Expr Mutez [Balance] :: Expr Mutez [Sender] :: Expr Address [VotingPower] :: Expr KeyHash -> Expr Natural [TotalVotingPower] :: Expr Natural [Exec] :: KnownValue b => Expr a -> Expr (Lambda a b) -> Expr b [NonZero] :: (NonZero n, KnownValue (Maybe n)) => Expr n -> Expr (Maybe n) 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 ratio reminder = (exN :~> n, exM :~> m, KnownValue reminder, ArithOpHs EDiv n m (Maybe (ratio, reminder))) type IsDivExpr exN exM n m ratio reminder = (exN :~> n, exM :~> m, KnownValue ratio, ArithOpHs EDiv n m (Maybe (ratio, reminder))) type IsArithExpr exN exM a n m r = (exN :~> n, exM :~> m, ArithOpHs a n m r, KnownValue r) 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 toExpr :: forall a. ToExpr a => a -> Expr (ExprType 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 odd :: (ParityExpr n m, ArithOpHs EDiv n m r, exN :~> n) => exN -> Expr Bool even :: (ParityExpr n m, ArithOpHs EDiv n m r, exN :~> n) => exN -> Expr Bool constExpr :: forall a. 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 r => exN -> exM -> Expr r (+) :: IsArithExpr exN exM Add n m r => exN -> exM -> Expr r infixl 6 + sub :: IsArithExpr exN exM Sub n m r => exN -> exM -> Expr r (-) :: IsArithExpr exN exM Sub n m r => exN -> exM -> Expr r infixl 6 - mul :: IsArithExpr exN exM Mul n m r => exN -> exM -> Expr r (*) :: IsArithExpr exN exM Mul n m r => exN -> exM -> Expr r infixl 7 * div :: forall reminder exN exM n m ratio. IsDivExpr exN exM n m ratio reminder => exN -> exM -> Expr ratio (/) :: forall reminder exN exM n m ratio. IsDivExpr exN exM n m ratio reminder => exN -> exM -> Expr ratio infixl 7 / mod :: forall ratio exN exM n m reminder. IsModExpr exN exM n m ratio reminder => exN -> exM -> Expr reminder (%) :: forall ratio exN exM n m reminder. IsModExpr exN exM n m ratio reminder => exN -> exM -> Expr reminder 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 r => exN -> exM -> Expr r (<<<) :: IsArithExpr exN exM Lsl n m r => exN -> exM -> Expr r infixl 8 <<< lsr :: IsArithExpr exN exM Lsr n m r => exN -> exM -> Expr r (>>>) :: IsArithExpr exN exM Lsr n m r => exN -> exM -> Expr r infixl 8 >>> or :: IsArithExpr exN exM Or n m r => exN -> exM -> Expr r (||) :: IsArithExpr exN exM Or n m r => exN -> exM -> Expr r infixr 2 || and :: IsArithExpr exN exM And n m r => exN -> exM -> Expr r (&&) :: IsArithExpr exN exM And n m r => exN -> exM -> Expr r infixr 3 && xor :: IsArithExpr exN exM Xor n m r => exN -> exM -> Expr r (^) :: IsArithExpr exN exM Xor n m r => exN -> exM -> Expr r infixr 2 ^ not :: IsUnaryArithExpr exN Not n => exN -> Expr (UnaryArithResHs Not n) pack :: (ex :~> a, NicePackedValue a) => ex -> Expr (Packed a) unpack :: (NiceUnpackedValue a, exb :~> Packed a) => exb -> Expr (Maybe a) packRaw :: (ex :~> a, NicePackedValue a) => ex -> Expr ByteString unpackRaw :: (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, Dupable key, IsError err, Buildable err, exKey :~> key, exVal :~> value, exStore :~> store) => exStore -> (Label name, err, exKey, exVal) -> Expr store (++@) :: (StoreHasSubmap store name key value, Dupable key, IsError err, Buildable 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), RecordToList (ConstructorFieldTypes dt), fields ~ Rec Expr (ConstructorFieldTypes dt), RecFromTuple fields) => IsoRecTuple fields -> Expr dt constructRec :: (InstrConstructC dt, RMap (ConstructorFieldTypes dt), RecordToList (ConstructorFieldTypes dt), KnownValue dt) => Rec Expr (ConstructorFieldTypes dt) -> Expr dt contract :: forall p vd addr exAddr. (NiceParameterFull p, NoExplicitDefaultEntrypoint p, IsoValue (ContractRef p), ToTAddress p vd addr, ToT addr ~ ToT Address, exAddr :~> addr) => exAddr -> Expr (Maybe (ContractRef p)) self :: (NiceParameterFull p, NoExplicitDefaultEntrypoint p, IsoValue (ContractRef p), IsNotInView) => Expr (ContractRef p) selfAddress :: Expr Address contractAddress :: exc :~> ContractRef p => exc -> Expr Address contractCallingUnsafe :: (NiceParameter arg, IsoValue (ContractRef arg), exAddr :~> Address) => EpName -> exAddr -> Expr (Maybe (ContractRef arg)) contractCallingString :: (NiceParameter arg, IsoValue (ContractRef arg), exAddr :~> Address) => MText -> exAddr -> Expr (Maybe (ContractRef arg)) runFutureContract :: (NiceParameter p, IsoValue (ContractRef p), conExpr :~> FutureContract p) => conExpr -> Expr (Maybe (ContractRef p)) implicitAccount :: exkh :~> KeyHash => exkh -> Expr (ContractRef ()) convertEpAddressToContract :: (NiceParameter p, IsoValue (ContractRef 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 :~> TSignature bs, hashExpr :~> bs, BytesLike bs) => pkExpr -> sigExpr -> hashExpr -> Expr Bool sha256 :: (hashExpr :~> bs, BytesLike bs) => hashExpr -> Expr (Hash Sha256 bs) sha512 :: (hashExpr :~> bs, BytesLike bs) => hashExpr -> Expr (Hash Sha512 bs) blake2b :: (hashExpr :~> bs, BytesLike bs) => hashExpr -> Expr (Hash Blake2b bs) sha3 :: (hashExpr :~> bs, BytesLike bs) => hashExpr -> Expr (Hash Sha3 bs) keccak :: (hashExpr :~> bs, BytesLike bs) => hashExpr -> Expr (Hash Keccak bs) hashKey :: keyExpr :~> PublicKey => keyExpr -> Expr KeyHash chainId :: Expr ChainId balance :: Expr Mutez level :: Expr Natural votingPower :: keyExpr :~> KeyHash => keyExpr -> Expr Natural totalVotingPower :: Expr Natural 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, IsNotInView) => 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 data CommentsVerbosity NoComments :: CommentsVerbosity LogTopLevelFrontendStatements :: CommentsVerbosity LogBackendStatements :: CommentsVerbosity LogAuxCode :: CommentsVerbosity LogExpressionsComputations :: CommentsVerbosity data CommentSettings CommentSettings :: CommentsVerbosity -> Bool -> Bool -> CommentSettings [csVerbosity] :: CommentSettings -> CommentsVerbosity [csPrintFullStackTrace] :: CommentSettings -> Bool [csPrintFileName] :: CommentSettings -> Bool defaultCommentSettings :: CommentsVerbosity -> CommentSettings -- | Simplified version of compileIndigoFull 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. compileIndigoContractFull :: forall param st. (KnownValue param, IsObject st) => CommentSettings -> IndigoContract param st -> ContractCode param st -- | Simplified version of compileIndigoContractFull 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, HasCallStack) => ex -> IndigoM (Var x) -- | Set the given variable to the result of the given expression. setVar :: (IsExpr ex x, HasCallStack) => Var x -> ex -> IndigoM () (=:) :: (IsExpr ex x, HasCallStack) => Var x -> ex -> IndigoM () infixr 0 =: setField :: (ex :~> ftype, IsObject dt, IsObject ftype, HasField dt fname ftype, HasCallStack) => Var dt -> Label fname -> ex -> IndigoM () (+=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Add n m m, HasCallStack) => Var m -> ex1 -> IndigoM () (-=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Sub n m m, HasCallStack) => Var m -> ex1 -> IndigoM () (*=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Mul n m m, HasCallStack) => Var m -> ex1 -> IndigoM () (||=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Or n m m, HasCallStack) => Var m -> ex1 -> IndigoM () (&&=) :: (IsExpr ex1 n, IsObject m, ArithOpHs And n m m, HasCallStack) => Var m -> ex1 -> IndigoM () (^=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Xor n m m, HasCallStack) => Var m -> ex1 -> IndigoM () (<<<=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Lsl n m m, HasCallStack) => Var m -> ex1 -> IndigoM () (>>>=) :: (IsExpr ex1 n, IsObject m, ArithOpHs Lsr n m m, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => Label fname -> IndigoM (Var ftype) if_ :: forall a b ex. (IfConstraint a b, ex :~> Bool, HasCallStack) => ex -> IndigoM a -> IndigoM b -> IndigoM (RetVars a) -- | Run the instruction when the condition is met, do nothing otherwise. when :: (exc :~> Bool, HasCallStack) => exc -> IndigoM () -> IndigoM () -- | Reverse of when. unless :: (exc :~> Bool, HasCallStack) => exc -> IndigoM () -> IndigoM () ifSome :: forall x a b ex. (KnownValue x, ex :~> Maybe x, IfConstraint a b, HasCallStack) => ex -> (Var x -> IndigoM a) -> IndigoM b -> IndigoM (RetVars a) ifNone :: forall x a b ex. (KnownValue x, ex :~> Maybe x, IfConstraint a b, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => exa -> IndigoM () -> IndigoM () ifRight :: forall x y a b ex. (KnownValue x, KnownValue y, ex :~> Either y x, IfConstraint a b, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => ex -> (Var x -> IndigoM ()) -> IndigoM () whenLeft :: forall x y ex. (KnownValue x, KnownValue y, ex :~> Either y x, HasCallStack) => ex -> (Var y -> IndigoM ()) -> IndigoM () ifCons :: forall x a b ex. (KnownValue x, ex :~> List x, IfConstraint a b, HasCallStack) => 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, HasCallStack) => guard -> clauses -> IndigoM (RetVars ret) -- | caseRec for tuples. case_ :: forall dt guard ret clauses. (CaseCommonF (IndigoMCaseClauseL IndigoM) dt ret clauses, RecFromTuple clauses, guard :~> dt, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => IndigoM a -> IndigoFunction a -- | Alias for scope we use in the tutorial. defFunction :: forall a. (ScopeCodeGen a, HasCallStack) => 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 :: HasCallStack => ((HasSideEffects, IsNotInView) => IndigoM ()) -> (HasSideEffects, IsNotInView) => 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, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => 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, HasCallStack) => String -> (Var (ExprType argExpr) -> IndigoM res) -> argExpr -> IndigoM (RetVars res) -- | While statement. while :: forall ex. (ex :~> Bool, HasCallStack) => ex -> IndigoM () -> IndigoM () whileLeft :: forall x y ex. (ex :~> Either y x, KnownValue y, KnownValue x, HasCallStack) => 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, HasCallStack) => e -> (Var (IterOpElHs a) -> IndigoM ()) -> IndigoM () -- | Put a document item. doc :: (DocItem di, HasCallStack) => di -> IndigoM () -- | Group documentation built in the given piece of code into a block -- dedicated to one thing, e.g. to one entrypoint. docGroup :: (DocItem di, HasCallStack) => (SubDoc -> di) -> IndigoM () -> IndigoM () -- | Insert documentation of the contract's storage type. The type should -- be passed using type applications. -- | Deprecated: Use `doc (dStorage @storage)` instead. docStorage :: forall storage. (TypeHasDoc storage, HasCallStack) => IndigoM () -- | Give a name to the given contract. Apply it to the whole contract -- code. -- | Deprecated: Use `docGroup name` instead. contractName :: HasCallStack => Text -> IndigoM () -> IndigoM () -- | Attach general info to the given contract. -- | Deprecated: Use `docGroup DGeneralInfoSection` instead. contractGeneral :: HasCallStack => IndigoM () -> IndigoM () -- | Attach default general info to the contract documentation. contractGeneralDefault :: HasCallStack => 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 :: HasCallStack => Markdown -> IndigoM () -- | Put a DAnchor doc item. anchor :: HasCallStack => Text -> IndigoM () -- | Put a DEntrypointExample doc item. example :: forall a. (NiceParameter a, HasCallStack) => a -> IndigoM () selfCalling :: forall p mname. (NiceParameterFull p, KnownValue (GetEntrypointArgCustom p mname), IsoValue (ContractRef (GetEntrypointArgCustom p mname)), HasCallStack, IsNotInView) => EntrypointRef mname -> IndigoM (Var (ContractRef (GetEntrypointArgCustom p mname))) contractCalling :: forall cp vd epRef epArg addr exAddr. (HasEntrypointArg cp epRef epArg, ToTAddress cp vd addr, ToT addr ~ ToT Address, exAddr :~> addr, KnownValue epArg, IsoValue (ContractRef epArg), HasCallStack) => epRef -> exAddr -> IndigoM (Var (Maybe (ContractRef epArg))) transferTokens :: (IsExpr exp p, IsExpr exm Mutez, IsExpr exc (ContractRef p), NiceParameter p, HasSideEffects, HasCallStack, IsNotInView) => exp -> exm -> exc -> IndigoM () setDelegate :: (HasSideEffects, IsExpr ex (Maybe KeyHash), HasCallStack, IsNotInView) => ex -> IndigoM () -- | Create contract using default compilation options for Lorentz -- compiler. -- -- See Lorentz.Run. createContract :: forall st exk exm exs param. (IsObject st, IsExpr exk (Maybe KeyHash), IsExpr exm Mutez, IsExpr exs st, NiceStorageFull st, NiceParameterFull param, HasSideEffects, HasCallStack, IsNotInView) => (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, NiceViewsDescriptor vd, Typeable vd, HasSideEffects, HasCallStack, IsNotInView) => Contract param st vd -> exk -> exm -> exs -> IndigoM (Var Address) -- | emit tag expression emits a contract event with textual tag -- tag and payload expression. -- -- The tag must be a field annotation. Use annQ quoter to -- construct it from a literal, for example: -- --
--   emit [annQ|tag|] ()
--   
emit :: (HasSideEffects, NicePackedValue a, HasAnnotation a, HasCallStack) => FieldAnn -> Expr a -> IndigoM () failWith :: forall ret a ex. (NiceConstant a, IsExpr ex a, ReturnableValue ret, HasCallStack) => ex -> IndigoM (RetVars ret) failCustom :: forall ret tag err ex. (ReturnableValue ret, MustHaveErrorArg tag (MText, err), CustomErrorHasDoc tag, NiceConstant err, ex :~> err, HasCallStack) => Label tag -> ex -> IndigoM (RetVars ret) failCustom_ :: forall ret tag. (ReturnableValue ret, MustHaveErrorArg tag (MText, ()), CustomErrorHasDoc tag, HasCallStack) => Label tag -> IndigoM (RetVars ret) failCustomNoArg :: forall ret tag. (ReturnableValue ret, MustHaveErrorArg tag MText, CustomErrorHasDoc tag, HasCallStack) => Label tag -> IndigoM (RetVars ret) failUnexpected_ :: forall ret. (ReturnableValue ret, HasCallStack) => MText -> IndigoM (RetVars ret) assert :: forall x ex. (IsError x, Buildable x, IsExpr ex Bool, HasCallStack) => x -> ex -> IndigoM () assertCustom :: forall tag err errEx ex. (MustHaveErrorArg tag (MText, err), CustomErrorHasDoc tag, NiceConstant err, IsExpr errEx err, IsExpr ex Bool, HasCallStack) => Label tag -> errEx -> ex -> IndigoM () assertCustom_ :: forall tag ex. (MustHaveErrorArg tag (MText, ()), CustomErrorHasDoc tag, IsExpr ex Bool, HasCallStack) => Label tag -> ex -> IndigoM () assertCustomNoArg :: forall tag ex. (MustHaveErrorArg tag MText, CustomErrorHasDoc tag, IsExpr ex Bool, HasCallStack) => Label tag -> ex -> IndigoM () assertSome :: forall x err ex. (IsError err, Buildable err, KnownValue x, ex :~> Maybe x, HasCallStack) => err -> ex -> IndigoM () assertNone :: forall x err ex. (IsError err, Buildable err, KnownValue x, ex :~> Maybe x, HasCallStack) => err -> ex -> IndigoM () assertRight :: forall x y err ex. (IsError err, Buildable err, KnownValue x, KnownValue y, ex :~> Either y x, HasCallStack) => err -> ex -> IndigoM () assertLeft :: forall x y err ex. (IsError err, Buildable err, KnownValue x, KnownValue y, ex :~> Either y x, HasCallStack) => err -> ex -> IndigoM () -- | Add a comment in a generated Michelson code justComment :: HasCallStack => Text -> IndigoM () -- | Add a comment in a generated Michelson code comment :: HasCallStack => CommentType -> IndigoM () -- | Add a comment before and after the given Indigo function code. The -- first argument is the name of the function. commentAroundFun :: HasCallStack => 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 :: HasCallStack => Text -> IndigoM a -> IndigoM a -- | Pretty-print an Indigo contract into Michelson code. printIndigoContract :: forall param st. (IsObject st, NiceParameterFull param, NiceStorageFull st) => Bool -> CommentSettings -> IndigoContract param st -> LText -- | Generate an Indigo contract documentation. renderIndigoDoc :: forall param st. (IsObject st, NiceParameterFull param, NiceStorageFull st) => 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, NiceStorageFull st, MonadIO m) => CommentSettings -> 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, NiceStorageFull st, MonadIO m, MonadMask m) => CommentSettings -> IndigoContract param st -> FilePath -> m () -- | Print the generated documentation to the standard output. printDocumentation :: forall param st m. (IsObject st, NiceParameterFull param, NiceStorageFull st, MonadIO m) => IndigoContract param st -> m () -- | Save the generated documentation to the given file. saveDocumentation :: forall param st m. (IsObject st, NiceParameterFull param, NiceStorageFull st, 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, IsNotInView) => (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, IsNotInView) => 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)