-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | Planet Mitchell -- -- Planet Mitchell. -- -- This package provides a curated, highly unstable collection of -- reorganized re-exports. Mostly for personal use at the moment, me but -- please poke around and see README.md for a bit more information ;) @package planet-mitchell @version 0.0.0 module Ala.Compose -- | 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 -> *) (g :: k1 -> k) (a :: k1) :: forall k k1. () => k -> * -> k1 -> k -> k1 -> * Compose :: f g a -> Compose [getCompose] :: Compose -> f g a module Ala.Const -- | The Const functor. newtype Const a (b :: k) :: forall k. () => * -> k -> * Const :: a -> Const a [getConst] :: Const a -> a module Ala.Identity -- | Identity functor and monad. (a non-strict monad) newtype Identity a Identity :: a -> Identity a [runIdentity] :: Identity a -> a -- | The trivial monad transformer, which maps a monad to an equivalent -- monad. newtype IdentityT (f :: k -> *) (a :: k) :: forall k. () => k -> * -> k -> * IdentityT :: f a -> IdentityT [runIdentityT] :: IdentityT -> f a -- | Lift a unary operation to the new monad. mapIdentityT :: () => m a -> n b -> IdentityT m a -> IdentityT n b -- | A function that generalizes the Identity base monad to -- be any monad. generalize :: Monad m => Identity a -> m a module Ala.Product -- | Lifted product of functors. data Product (f :: k -> *) (g :: k -> *) (a :: k) :: forall k. () => k -> * -> k -> * -> k -> * Pair :: f a -> g a -> Product module Ala.Sum -- | Lifted sum of functors. data Sum (f :: k -> *) (g :: k -> *) (a :: k) :: forall k. () => k -> * -> k -> * -> k -> * InL :: f a -> Sum InR :: g a -> Sum module Applicative -- | 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 :: * -> *) -- | Lift a value. pure :: Applicative f => a -> f a -- | Sequential application. -- -- A few functors support an implementation of <*> that is -- more efficient than the default one. (<*>) :: Applicative f => f a -> b -> f a -> f b -- | Lift a binary function to actions. -- -- Some functors support an implementation of liftA2 that is more -- efficient than the default one. In particular, if fmap is an -- expensive operation, it is likely better to use liftA2 than to -- fmap over the structure and then use <*>. liftA2 :: Applicative f => a -> b -> c -> f a -> f b -> f c -- | Sequence actions, discarding the value of the first argument. (*>) :: Applicative f => f a -> f b -> f b -- | Sequence actions, discarding the value of the second argument. (<*) :: Applicative f => f a -> f b -> f a -- | between open close p parses open, followed by -- p and close. Returns the value returned by -- p. -- --
--   braces = between (symbol "{") (symbol "}")
--   
between :: Applicative m => m open -> m close -> m a -> m a -- | This generalizes the list-based filter function. filterM :: Applicative m => a -> m Bool -> [a] -> m [a] -- | forever act repeats the action infinitely. forever :: Applicative f => f a -> f b -- | Lift a ternary function to actions. liftA3 :: Applicative f => a -> b -> c -> d -> f a -> f b -> f c -> f d -- | replicateM n act performs the action n times, -- gathering the results. replicateM :: Applicative m => Int -> m a -> m [a] -- | Like replicateM, but discards the result. replicateM_ :: Applicative m => Int -> m a -> m () -- | The reverse of when. unless :: Applicative f => Bool -> f () -> f () -- | 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 () -- | 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 () -- | A monoid on applicative functors. -- -- If defined, some and many should be the least solutions -- of the equations: -- -- class Applicative f => Alternative (f :: * -> *) -- | The identity of <|> empty :: Alternative f => f a -- | An associative binary operation (<|>) :: Alternative f => f a -> f a -> f a -- | Zero or more. many :: Alternative f => f a -> f [a] -- | endBy p sep parses zero or more occurrences of -- p, separated and ended by sep. Returns a list of -- values returned by p. -- --
--   cStatements = cStatement `endBy` semicolon
--   
endBy :: Alternative m => m a -> m sep -> m [a] -- | endBy1 p sep parses one or more occurrences of -- p, separated and ended by sep. Returns a non-empty -- list of values returned by p. endBy1 :: Alternative m => m a -> m sep -> m NonEmpty a -- | 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 () -- | manyTill p end applies parser p zero -- or more times until parser end succeeds. Returns the list of -- values returned by p. -- -- See also: skipMany, skipManyTill. manyTill :: Alternative m => m a -> m end -> m [a] -- | One or none. optional :: (Alt f, Applicative f) => f a -> f Maybe a -- | sepBy p sep parses zero or more occurrences of -- p, separated by sep. Returns a list of values -- returned by p. -- --
--   commaSep p = p `sepBy` comma
--   
sepBy :: Alternative m => m a -> m sep -> m [a] -- | sepEndBy p sep parses zero or more occurrences -- of p, separated and optionally ended by sep. Returns -- a list of values returned by p. sepEndBy :: Alternative m => m a -> m sep -> m [a] -- | sepBy1 p sep parses one or more occurrences of -- p, separated by sep. Returns a non-empty list of -- values returned by p. sepBy1 :: Alternative m => m a -> m sep -> m NonEmpty a -- | sepEndBy1 p sep parses one or more occurrences -- of p, separated and optionally ended by sep. Returns -- a non-empty list of values returned by p. sepEndBy1 :: Alternative m => m a -> m sep -> m NonEmpty a -- | skipMany p applies the parser p zero -- or more times, skipping its result. -- -- See also: manyTill, skipManyTill. skipMany :: Alternative m => m a -> m () -- | skipManyTill p end applies the parser p -- zero or more times skipping results until parser end -- succeeds. Result parsed by end is then returned. -- -- See also: manyTill, skipMany. skipManyTill :: Alternative m => m a -> m end -> m end -- | skipSome p applies the parser p one or -- more times, skipping its result. -- -- See also: someTill, skipSomeTill. skipSome :: Alternative m => m a -> m () -- | skipSomeTill p end applies the parser p -- one or more times skipping results until parser end -- succeeds. Result parsed by end is then returned. -- -- See also: someTill, skipSome. skipSomeTill :: Alternative m => m a -> m end -> m end -- | some1 x sequences x one or more times. some1 :: Alternative f => f a -> f NonEmpty a -- | someTill p end works similarly to manyTill -- p end, but p should succeed at least once. -- -- See also: skipSome, skipSomeTill. someTill :: Alternative m => m a -> m end -> m NonEmpty a -- | Monoid under <|>. newtype Alt (f :: k -> *) (a :: k) :: forall k. () => k -> * -> k -> * Alt :: f a -> Alt [getAlt] :: Alt -> f a -- | The free Applicative for a Functor f. data Ap (f :: * -> *) a [Pure] :: Ap f a [Ap] :: Ap f a -- | Given a natural transformation from f to g, this -- gives a canonical monoidal natural transformation from Ap -- f to g. -- --
--   runAp t == retractApp . hoistApp t
--   
runAp :: Applicative g => forall x. () => f x -> g x -> Ap f a -> g a -- | Perform a monoidal analysis over free applicative value. -- -- Example: -- --
--   count :: Ap f a -> Int
--   count = getSum . runAp_ (\_ -> Sum 1)
--   
runAp_ :: Monoid m => forall a. () => f a -> m -> Ap f b -> m -- | A version of lift that can be used with just a Functor -- for f. liftAp :: () => f a -> Ap f a -- | Tear down a free Applicative using iteration. iterAp :: Functor g => g a -> a -> Ap g a -> a -- | Given a natural transformation from f to g this -- gives a monoidal natural transformation from Ap f to Ap -- g. hoistAp :: () => forall a. () => f a -> g a -> Ap f b -> Ap g b -- | Interprets the free applicative functor over f using the semantics for -- pure and <*> given by the Applicative instance for -- f. -- --
--   retractApp == runAp id
--   
retractAp :: Applicative f => Ap f a -> f a module Array -- | The type of immutable non-strict (boxed) arrays with indices in -- i and elements in e. data Array i e -- | Construct an array with the specified bounds and containing values for -- given indices within these bounds. -- -- The array is undefined (i.e. bottom) if any index in the list is out -- of bounds. The Haskell 2010 Report further specifies that if any two -- associations in the list have the same index, the value at that index -- is undefined (i.e. bottom). However in GHC's implementation, the value -- at such an index is the value part of the last association with that -- index in the list. -- -- Because the indices must be checked for these errors, array is -- strict in the bounds argument and in the indices of the association -- list, but non-strict in the values. Thus, recurrences such as the -- following are possible: -- --
--   a = array (1,100) ((1,1) : [(i, i * a!(i-1)) | i <- [2..100]])
--   
-- -- Not every index within the bounds of the array need appear in the -- association list, but the values associated with indices that do not -- appear will be undefined (i.e. bottom). -- -- If, in any dimension, the lower bound is greater than the upper bound, -- then the array is legal, but empty. Indexing an empty array always -- gives an array-bounds error, but bounds still yields the bounds -- with which the array was constructed. array :: Ix i => (i, i) -> [(i, e)] -> Array i e -- | The bounds with which an array was constructed. bounds :: () => Array i e -> (i, i) -- | The list of indices of an array in ascending order. indices :: Ix i => Array i e -> [i] -- | The list of associations of an array in index order. assocs :: Ix i => Array i e -> [(i, e)] -- | Constructs an array identical to the first argument except that it has -- been updated by the associations in the right argument. For example, -- if m is a 1-origin, n by n matrix, then -- --
--   m//[((i,i), 0) | i <- [1..n]]
--   
-- -- is the same matrix, except with the diagonal zeroed. -- -- Repeated indices in the association list are handled as for -- array: Haskell 2010 specifies that the resulting array is -- undefined (i.e. bottom), but GHC's implementation uses the last -- association for each index. (//) :: Ix i => Array i e -> [(i, e)] -> Array i e infixl 9 // -- | accum f takes an array and an association list and -- accumulates pairs from the list into the array with the accumulating -- function f. Thus accumArray can be defined using -- accum: -- --
--   accumArray f z b = accum f (array b [(i, z) | i <- range b])
--   
accum :: Ix i => e -> a -> e -> Array i e -> [(i, a)] -> Array i e -- | ixmap allows for transformations on array indices. It may be -- thought of as providing function composition on the right with the -- mapping that the original array embodies. -- -- A similar transformation of array values may be achieved using -- fmap from the Array instance of the Functor -- class. ixmap :: (Ix i, Ix j) => (i, i) -> i -> j -> Array j e -> Array i e module Array.Partial -- | The value at the given index in an array. (!) :: Ix i => Array i e -> i -> e infixl 9 ! module Benchmark -- | An entry point that can be used as a main function. -- --
--   import Gauge.Main
--   
--   fib :: Int -> Int
--   fib 0 = 0
--   fib 1 = 1
--   fib n = fib (n-1) + fib (n-2)
--   
--   main = defaultMain [
--          bgroup "fib" [ bench "10" $ whnf fib 10
--                       , bench "35" $ whnf fib 35
--                       , bench "37" $ whnf fib 37
--                       ]
--                      ]
--   
defaultMain :: [Benchmark] -> IO () -- | Specification of a collection of benchmarks and environments. A -- benchmark may consist of: -- -- data Benchmark -- | Create a single benchmark. bench :: String -> Benchmarkable -> Benchmark -- | Group several benchmarks together under a common name. bgroup :: String -> [Benchmark] -> Benchmark -- | Run a benchmark (or collection of benchmarks) in the given -- environment. The purpose of an environment is to lazily create input -- data to pass to the functions that will be benchmarked. -- -- A common example of environment data is input that is read from a -- file. Another is a large data structure constructed in-place. -- -- By deferring the creation of an environment when its associated -- benchmarks need the its, we avoid two problems that this strategy -- caused: -- -- -- -- Creation. An environment is created right before its related -- benchmarks are run. The IO action that creates the environment -- is run, then the newly created environment is evaluated to normal form -- (hence the NFData constraint) before being passed to the -- function that receives the environment. -- -- Complex environments. If you need to create an environment that -- contains multiple values, simply pack the values into a tuple. -- -- Lazy pattern matching. In situations where a "real" environment -- is not needed, e.g. if a list of benchmark names is being generated, -- undefined will be passed to the function that receives the -- environment. This avoids the overhead of generating an environment -- that will not actually be used. -- -- The function that receives the environment must use lazy pattern -- matching to deconstruct the tuple, as use of strict pattern matching -- will cause a crash if undefined is passed in. -- -- Example. This program runs benchmarks in an environment that -- contains two values. The first value is the contents of a text file; -- the second is a string. Pay attention to the use of a lazy pattern to -- deconstruct the tuple in the function that returns the benchmarks to -- be run. -- --
--   setupEnv = do
--     let small = replicate 1000 (1 :: Int)
--     big <- map length . words <$> readFile "/usr/dict/words"
--     return (small, big)
--   
--   main = defaultMain [
--      -- notice the lazy pattern match here!
--      env setupEnv $ \ ~(small,big) -> bgroup "main" [
--      bgroup "small" [
--        bench "length" $ whnf length small
--      , bench "length . filter" $ whnf (length . filter (==1)) small
--      ]
--    ,  bgroup "big" [
--        bench "length" $ whnf length big
--      , bench "length . filter" $ whnf (length . filter (==1)) big
--      ]
--    ] ]
--   
-- -- Discussion. The environment created in the example above is -- intentionally not ideal. As Haskell's scoping rules suggest, -- the variable big is in scope for the benchmarks that use only -- small. It would be better to create a separate environment -- for big, so that it will not be kept alive while the -- unrelated benchmarks are being run. env :: NFData env => IO env -> env -> Benchmark -> Benchmark -- | Same as env, but but allows for an additional callback to clean -- up the environment. Resource clean up is exception safe, that is, it -- runs even if the Benchmark throws an exception. envWithCleanup :: NFData env => IO env -> env -> IO a -> env -> Benchmark -> Benchmark -- | A pure function or impure action that can be benchmarked. The function -- to be benchmarked is wrapped into a function (runRepeatedly) -- that takes an Int64 parameter which indicates the number of -- times to run the given function or action. The wrapper is constructed -- automatically by the APIs provided in this library to construct -- Benchmarkable. -- -- When perRun is not set then runRepeatedly is invoked to -- perform all iterations in one measurement interval. When perRun -- is set, runRepeatedly is always invoked with 1 iteration in one -- measurement interval, before a measurement allocEnv is invoked -- and after the measurement cleanEnv is invoked. The performance -- counters for each iteration are then added together for all -- iterations. data Benchmarkable -- | Perform an action, then evaluate its result to normal form. This is -- particularly useful for forcing a lazy IO action to be -- completely performed. nfIO :: NFData a => IO a -> Benchmarkable -- | Perform an action, then evaluate its result to weak head normal form -- (WHNF). This is useful for forcing an IO action whose result is -- an expression to be evaluated down to a more useful value. whnfIO :: () => IO a -> Benchmarkable -- | Apply an argument to a function, and evaluate the result to normal -- form (NF). nf :: NFData b => a -> b -> a -> Benchmarkable -- | Apply an argument to a function, and evaluate the result to weak head -- normal form (WHNF). whnf :: () => a -> b -> a -> Benchmarkable -- | Create a Benchmarkable where a fresh environment is allocated for -- every batch of runs of the benchmarkable. -- -- The environment is evaluated to normal form before the benchmark is -- run. -- -- When using whnf, whnfIO, etc. Gauge creates a -- Benchmarkable whichs runs a batch of N repeat runs of -- that expressions. Gauge may run any number of these batches to get -- accurate measurements. Environments created by env and -- envWithCleanup, are shared across all these batches of runs. -- -- This is fine for simple benchmarks on static input, but when -- benchmarking IO operations where these operations can modify (and -- especially grow) the environment this means that later batches might -- have their accuracy effected due to longer, for example, longer -- garbage collection pauses. -- -- An example: Suppose we want to benchmark writing to a Chan, if we -- allocate the Chan using environment and our benchmark consists of -- writeChan env (), the contents and thus size of the Chan will -- grow with every repeat. If Gauge runs a 1,000 batches of 1,000 -- repeats, the result is that the channel will have 999,000 items in it -- by the time the last batch is run. Since GHC GC has to copy the live -- set for every major GC this means our last set of writes will suffer a -- lot of noise of the previous repeats. -- -- By allocating a fresh environment for every batch of runs this -- function should eliminate this effect. perBatchEnv :: (NFData env, NFData b) => Int64 -> IO env -> env -> IO b -> Benchmarkable -- | Same as perBatchEnv, but but allows for an additional callback -- to clean up the environment. Resource clean up is exception safe, that -- is, it runs even if the Benchmark throws an exception. perBatchEnvWithCleanup :: (NFData env, NFData b) => Int64 -> IO env -> Int64 -> env -> IO () -> env -> IO b -> Benchmarkable -- | Create a Benchmarkable where a fresh environment is allocated for -- every run of the operation to benchmark. This is useful for -- benchmarking mutable operations that need a fresh environment, such as -- sorting a mutable Vector. -- -- As with env and perBatchEnv the environment is evaluated -- to normal form before the benchmark is run. -- -- This introduces extra noise and result in reduce accuracy compared to -- other Gauge benchmarks. But allows easier benchmarking for mutable -- operations than was previously possible. perRunEnv :: (NFData env, NFData b) => IO env -> env -> IO b -> Benchmarkable -- | Same as perRunEnv, but but allows for an additional callback to -- clean up the environment. Resource clean up is exception safe, that -- is, it runs even if the Benchmark throws an exception. perRunEnvWithCleanup :: (NFData env, NFData b) => IO env -> env -> IO () -> env -> IO b -> Benchmarkable module Bifoldable -- | Bifoldable identifies foldable structures with two different -- varieties of elements (as opposed to Foldable, which has one -- variety of element). Common examples are Either and '(,)': -- --
--   instance Bifoldable Either where
--     bifoldMap f _ (Left  a) = f a
--     bifoldMap _ g (Right b) = g b
--   
--   instance Bifoldable (,) where
--     bifoldr f g z (a, b) = f a (g b z)
--   
-- -- A minimal Bifoldable definition consists of either -- bifoldMap or bifoldr. When defining more than this -- minimal set, one should ensure that the following identities hold: -- --
--   bifoldbifoldMap id id
--   bifoldMap f g ≡ bifoldr (mappend . f) (mappend . g) mempty
--   bifoldr f g z t ≡ appEndo (bifoldMap (Endo . f) (Endo . g) t) z
--   
-- -- If the type is also a Bifunctor instance, it should satisfy: -- --
--   'bifoldMap' f g ≡ 'bifold' . 'bimap' f g
--   
-- -- which implies that -- --
--   'bifoldMap' f g . 'bimap' h i ≡ 'bifoldMap' (f . h) (g . i)
--   
class Bifoldable (p :: * -> * -> *) -- | Combines the elements of a structure using a monoid. -- --
--   bifoldbifoldMap id id
--   
bifold :: (Bifoldable p, Monoid m) => p m m -> m -- | Combines the elements of a structure, given ways of mapping them to a -- common monoid. -- --
--   bifoldMap f g
--        ≡ bifoldr (mappend . f) (mappend . g) mempty
--   
bifoldMap :: (Bifoldable p, Monoid m) => a -> m -> b -> m -> p a b -> m -- | Combines the elements of a structure in a right associative manner. -- Given a hypothetical function toEitherList :: p a b -> [Either -- a b] yielding a list of all elements of a structure in order, the -- following would hold: -- --
--   bifoldr f g z ≡ foldr (either f g) z . toEitherList
--   
bifoldr :: Bifoldable p => a -> c -> c -> b -> c -> c -> c -> p a b -> c -- | As bifoldr, but strict in the result of the reduction functions -- at each step. bifoldr' :: Bifoldable t => a -> c -> c -> b -> c -> c -> c -> t a b -> c -- | Right associative monadic bifold over a structure. bifoldrM :: (Bifoldable t, Monad m) => a -> c -> m c -> b -> c -> m c -> c -> t a b -> m c -- | As bifoldl, but strict in the result of the reduction functions -- at each step. -- -- This ensures that each step of the bifold is forced to weak head -- normal form before being applied, avoiding the collection of thunks -- that would otherwise occur. This is often what you want to strictly -- reduce a finite structure to a single, monolithic result (e.g., -- bilength). bifoldl' :: Bifoldable t => a -> b -> a -> a -> c -> a -> a -> t b c -> a -- | Left associative monadic bifold over a structure. bifoldlM :: (Bifoldable t, Monad m) => a -> b -> m a -> a -> c -> m a -> a -> t b c -> m a -- | Map each element of a structure using one of two actions, evaluate -- these actions from left to right, and ignore the results. For a -- version that doesn't ignore the results, see bitraverse. bitraverse_ :: (Bifoldable t, Applicative f) => a -> f c -> b -> f d -> t a b -> f () -- | As bitraverse_, but with the structure as the primary argument. -- For a version that doesn't ignore the results, see bifor. -- --
--   >>> > bifor_ ('a', "bc") print (print . reverse)
--   'a'
--   "cb"
--   
bifor_ :: (Bifoldable t, Applicative f) => t a b -> a -> f c -> b -> f d -> f () -- | Evaluate each action in the structure from left to right, and ignore -- the results. For a version that doesn't ignore the results, see -- bisequence. bisequence_ :: (Bifoldable t, Applicative f) => t f a f b -> f () -- | The sum of a collection of actions, generalizing biconcat. biasum :: (Bifoldable t, Alternative f) => t f a f a -> f a -- | Collects the list of elements of a structure, from left to right. biList :: Bifoldable t => t a a -> [a] -- | Test whether the structure is empty. binull :: Bifoldable t => t a b -> Bool -- | Returns the size/length of a finite structure as an Int. bilength :: Bifoldable t => t a b -> Int -- | Does the element occur in the structure? bielem :: (Bifoldable t, Eq a) => a -> t a a -> Bool -- | The bisum function computes the sum of the numbers of a -- structure. bisum :: (Bifoldable t, Num a) => t a a -> a -- | The biproduct function computes the product of the numbers of a -- structure. biproduct :: (Bifoldable t, Num a) => t a a -> a -- | Given a means of mapping the elements of a structure to lists, -- computes the concatenation of all such lists in order. biconcatMap :: Bifoldable t => a -> [c] -> b -> [c] -> t a b -> [c] -- | biand returns the conjunction of a container of Bools. For the -- result to be True, the container must be finite; False, -- however, results from a False value finitely far from the left -- end. biand :: Bifoldable t => t Bool Bool -> Bool -- | bior returns the disjunction of a container of Bools. For the -- result to be False, the container must be finite; True, -- however, results from a True value finitely far from the left -- end. bior :: Bifoldable t => t Bool Bool -> Bool -- | Determines whether any element of the structure satisfies its -- appropriate predicate argument. biany :: Bifoldable t => a -> Bool -> b -> Bool -> t a b -> Bool -- | Determines whether all elements of the structure satisfy their -- appropriate predicate argument. biall :: Bifoldable t => a -> Bool -> b -> Bool -> t a b -> Bool -- | binotElem is the negation of bielem. binotElem :: (Bifoldable t, Eq a) => a -> t a a -> Bool -- | The bifind function takes a predicate and a structure and -- returns the leftmost element of the structure matching the predicate, -- or Nothing if there is no such element. bifind :: Bifoldable t => a -> Bool -> t a a -> Maybe a class Bifoldable t => Bifoldable1 (t :: * -> * -> *) bifold1 :: (Bifoldable1 t, Semigroup m) => t m m -> m bifoldMap1 :: (Bifoldable1 t, Semigroup m) => a -> m -> b -> m -> t a b -> m bitraverse1_ :: (Bifoldable1 t, Apply f) => a -> f b -> c -> f d -> t a c -> f () bifor1_ :: (Bifoldable1 t, Apply f) => t a c -> a -> f b -> c -> f d -> f () bisequenceA1_ :: (Bifoldable1 t, Apply f) => t f a f b -> f () module Bifoldable.Partial -- | A variant of bifoldl that has no base case, and thus may only -- be applied to non-empty structures. bifoldl1 :: Bifoldable t => a -> a -> a -> t a a -> a -- | A variant of bifoldr that has no base case, and thus may only -- be applied to non-empty structures. bifoldr1 :: Bifoldable t => a -> a -> a -> t a a -> a -- | The largest element of a non-empty structure. bimaximum :: (Bifoldable t, Ord a) => t a a -> a -- | The largest element of a non-empty structure with respect to the given -- comparison function. bimaximumBy :: Bifoldable t => a -> a -> Ordering -> t a a -> a -- | The least element of a non-empty structure. biminimum :: (Bifoldable t, Ord a) => t a a -> a -- | The least element of a non-empty structure with respect to the given -- comparison function. biminimumBy :: Bifoldable t => a -> a -> Ordering -> t a a -> a module Bifunctor -- | 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 :: * -> * -> *) -- | 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 -- | This class provides for symmetric bifunctors. class Bifunctor p => Swapped (p :: * -> * -> *) -- |
--   swapped . swappedid
--   first f . swapped = swapped . second f
--   second g . swapped = swapped . first g
--   bimap f g . swapped = swapped . bimap g f
--   
-- --
--   >>> (1,2)^.swapped
--   (2,1)
--   
swapped :: (Swapped p, Profunctor p, Functor f) => p p b a f p d c -> p p a b f p c d class Bifunctor p => Biapply (p :: * -> * -> *) (<<.>>) :: Biapply p => p a -> b c -> d -> p a c -> p b d -- |
--   a .> b ≡ const id <$> a <.> b
--   
(.>>) :: Biapply p => p a b -> p c d -> p c d -- |
--   a <. b ≡ const <$> a <.> b
--   
(<<.) :: Biapply p => p a b -> p c d -> p a b module Bitraversable -- | Bitraversable identifies bifunctorial data structures whose -- elements can be traversed in order, performing Applicative or -- Monad actions at each element, and collecting a result -- structure with the same shape. -- -- As opposed to Traversable data structures, which have one -- variety of element on which an action can be performed, -- Bitraversable data structures have two such varieties of -- elements. -- -- A definition of bitraverse must satisfy the following laws: -- -- -- -- where an applicative transformation is a function -- --
--   t :: (Applicative f, Applicative g) => f a -> g a
--   
-- -- preserving the Applicative operations: -- --
--   t (pure x) = pure x
--   t (f <*> x) = t f <*> t x
--   
-- -- and the identity functor Identity and composition functors -- Compose are defined as -- --
--   newtype Identity a = Identity { runIdentity :: a }
--   
--   instance Functor Identity where
--     fmap f (Identity x) = Identity (f x)
--   
--   instance Applicative Identity where
--     pure = Identity
--     Identity f <*> Identity x = Identity (f x)
--   
--   newtype Compose f g a = Compose (f (g a))
--   
--   instance (Functor f, Functor g) => Functor (Compose f g) where
--     fmap f (Compose x) = Compose (fmap (fmap f) x)
--   
--   instance (Applicative f, Applicative g) => Applicative (Compose f g) where
--     pure = Compose . pure . pure
--     Compose f <*> Compose x = Compose ((<*>) <$> f <*> x)
--   
-- -- Some simple examples are Either and '(,)': -- --
--   instance Bitraversable Either where
--     bitraverse f _ (Left x) = Left <$> f x
--     bitraverse _ g (Right y) = Right <$> g y
--   
--   instance Bitraversable (,) where
--     bitraverse f g (x, y) = (,) <$> f x <*> g y
--   
-- -- Bitraversable relates to its superclasses in the following -- ways: -- --
--   bimap f g ≡ runIdentity . bitraverse (Identity . f) (Identity . g)
--   bifoldMap f g = getConst . bitraverse (Const . f) (Const . g)
--   
-- -- These are available as bimapDefault and bifoldMapDefault -- respectively. class (Bifunctor t, Bifoldable t) => Bitraversable (t :: * -> * -> *) -- | Evaluates the relevant functions at each element in the structure, -- running the action, and builds a new structure with the same shape, -- using the results produced from sequencing the actions. -- --
--   bitraverse f g ≡ bisequenceA . bimap f g
--   
-- -- For a version that ignores the results, see bitraverse_. bitraverse :: (Bitraversable t, Applicative f) => a -> f c -> b -> f d -> t a b -> f t c d -- | Sequences all the actions in a structure, building a new structure -- with the same shape using the results of the actions. For a version -- that ignores the results, see bisequence_. -- --
--   bisequencebitraverse id id
--   
bisequence :: (Bitraversable t, Applicative f) => t f a f b -> f t a b -- | bifor is bitraverse with the structure as the first -- argument. For a version that ignores the results, see bifor_. bifor :: (Bitraversable t, Applicative f) => t a b -> a -> f c -> b -> f d -> f t c d -- | The bimapAccumL function behaves like a combination of -- bimap and bifoldl; it traverses a structure from left to -- right, threading a state of type a and using the given -- actions to compute new elements for the structure. bimapAccumL :: Bitraversable t => a -> b -> (a, c) -> a -> d -> (a, e) -> a -> t b d -> (a, t c e) -- | The bimapAccumR function behaves like a combination of -- bimap and bifoldl; it traverses a structure from right -- to left, threading a state of type a and using the given -- actions to compute new elements for the structure. bimapAccumR :: Bitraversable t => a -> b -> (a, c) -> a -> d -> (a, e) -> a -> t b d -> (a, t c e) -- | A default definition of bimap in terms of the -- Bitraversable operations. -- --
--   bimapDefault f g ≡
--        runIdentity . bitraverse (Identity . f) (Identity . g)
--   
bimapDefault :: Bitraversable t => a -> b -> c -> d -> t a c -> t b d -- | A default definition of bifoldMap in terms of the -- Bitraversable operations. -- --
--   bifoldMapDefault f g ≡
--       getConst . bitraverse (Const . f) (Const . g)
--   
bifoldMapDefault :: (Bitraversable t, Monoid m) => a -> m -> b -> m -> t a b -> m class (Bifoldable1 t, Bitraversable t) => Bitraversable1 (t :: * -> * -> *) bitraverse1 :: (Bitraversable1 t, Apply f) => a -> f b -> c -> f d -> t a c -> f t b d bisequence1 :: (Bitraversable1 t, Apply f) => t f a f b -> f t a b bifoldMap1Default :: (Bitraversable1 t, Semigroup m) => a -> m -> b -> m -> t a b -> m module Bits -- | The Bits class defines bitwise operations over integral types. -- -- class Eq a => Bits a -- | Bitwise "and" (.&.) :: Bits a => a -> a -> a -- | Bitwise "or" (.|.) :: Bits a => a -> a -> a -- | Bitwise "xor" xor :: Bits a => a -> a -> a -- | Reverse all the bits in the argument complement :: Bits a => a -> a -- | shift x i shifts x left by i bits if -- i is positive, or right by -i bits otherwise. Right -- shifts perform sign extension on signed number types; i.e. they fill -- the top bits with 1 if the x is negative and with 0 -- otherwise. -- -- An instance can define either this unified shift or -- shiftL and shiftR, depending on which is more convenient -- for the type in question. shift :: Bits a => a -> Int -> a -- | rotate x i rotates x left by i bits -- if i is positive, or right by -i bits otherwise. -- -- For unbounded types like Integer, rotate is equivalent -- to shift. -- -- An instance can define either this unified rotate or -- rotateL and rotateR, depending on which is more -- convenient for the type in question. rotate :: Bits a => a -> Int -> a -- | zeroBits is the value with all bits unset. -- -- The following laws ought to hold (for all valid bit indices -- n): -- -- -- -- This method uses clearBit (bit 0) 0 as its -- default implementation (which ought to be equivalent to -- zeroBits for types which possess a 0th bit). zeroBits :: Bits a => a -- | bit i is a value with the ith bit set -- and all other bits clear. -- -- Can be implemented using bitDefault if a is also an -- instance of Num. -- -- See also zeroBits. bit :: Bits a => Int -> a -- | x `setBit` i is the same as x .|. bit i setBit :: Bits a => a -> Int -> a -- | x `clearBit` i is the same as x .&. complement (bit -- i) clearBit :: Bits a => a -> Int -> a -- | x `complementBit` i is the same as x `xor` bit i complementBit :: Bits a => a -> Int -> a -- | Return True if the nth bit of the argument is 1 -- -- Can be implemented using testBitDefault if a is also -- an instance of Num. testBit :: Bits a => a -> Int -> Bool -- | Return the number of bits in the type of the argument. The actual -- value of the argument is ignored. Returns Nothing for types that do -- not have a fixed bitsize, like Integer. bitSizeMaybe :: Bits a => a -> Maybe Int -- | Return the number of bits in the type of the argument. The actual -- value of the argument is ignored. The function bitSize is -- undefined for types that do not have a fixed bitsize, like -- Integer. bitSize :: Bits a => a -> Int -- | Return True if the argument is a signed type. The actual value -- of the argument is ignored isSigned :: Bits a => a -> Bool -- | Shift the argument left by the specified number of bits (which must be -- non-negative). -- -- An instance can define either this and shiftR or the unified -- shift, depending on which is more convenient for the type in -- question. shiftL :: Bits a => a -> Int -> a -- | Shift the argument left by the specified number of bits. The result is -- undefined for negative shift amounts and shift amounts greater or -- equal to the bitSize. -- -- Defaults to shiftL unless defined explicitly by an instance. unsafeShiftL :: Bits a => a -> Int -> a -- | Shift the first argument right by the specified number of bits. The -- result is undefined for negative shift amounts and shift amounts -- greater or equal to the bitSize. -- -- Right shifts perform sign extension on signed number types; i.e. they -- fill the top bits with 1 if the x is negative and with 0 -- otherwise. -- -- An instance can define either this and shiftL or the unified -- shift, depending on which is more convenient for the type in -- question. shiftR :: Bits a => a -> Int -> a -- | Shift the first argument right by the specified number of bits, which -- must be non-negative and smaller than the number of bits in the type. -- -- Right shifts perform sign extension on signed number types; i.e. they -- fill the top bits with 1 if the x is negative and with 0 -- otherwise. -- -- Defaults to shiftR unless defined explicitly by an instance. unsafeShiftR :: Bits a => a -> Int -> a -- | Rotate the argument left by the specified number of bits (which must -- be non-negative). -- -- An instance can define either this and rotateR or the unified -- rotate, depending on which is more convenient for the type in -- question. rotateL :: Bits a => a -> Int -> a -- | Rotate the argument right by the specified number of bits (which must -- be non-negative). -- -- An instance can define either this and rotateL or the unified -- rotate, depending on which is more convenient for the type in -- question. rotateR :: Bits a => a -> Int -> a -- | Return the number of set bits in the argument. This number is known as -- the population count or the Hamming weight. -- -- Can be implemented using popCountDefault if a is also -- an instance of Num. popCount :: Bits a => a -> Int -- | Shift Right Logical (i.e., without sign extension) -- -- NB: When used on negative Integers, hilarity may ensue. srl :: Bits b => b -> Int -> b -- | Attempt to convert an Integral type a to an -- Integral type b using the size of the types as -- measured by Bits methods. -- -- A simpler version of this function is: -- --
--   toIntegral :: (Integral a, Integral b) => a -> Maybe b
--   toIntegral x
--     | toInteger x == y = Just (fromInteger y)
--     | otherwise        = Nothing
--     where
--       y = toInteger x
--   
-- -- This version requires going through Integer, which can be -- inefficient. However, toIntegralSized is optimized to allow -- GHC to statically determine the relative type sizes (as measured by -- bitSizeMaybe and isSigned) and avoid going through -- Integer for many types. (The implementation uses -- fromIntegral, which is itself optimized with rules for -- base types but may go through Integer for some type -- pairs.) toIntegralSized :: (Integral a, Integral b, Bits a, Bits b) => a -> Maybe b -- | The FiniteBits class denotes types with a finite, fixed number -- of bits. class Bits b => FiniteBits b -- | Return the number of bits in the type of the argument. The actual -- value of the argument is ignored. Moreover, finiteBitSize is -- total, in contrast to the deprecated bitSize function it -- replaces. -- --
--   finiteBitSize = bitSize
--   bitSizeMaybe = Just . finiteBitSize
--   
finiteBitSize :: FiniteBits b => b -> Int -- | Count number of zero bits preceding the most significant set bit. -- --
--   countLeadingZeros (zeroBits :: a) = finiteBitSize (zeroBits :: a)
--   
-- -- countLeadingZeros can be used to compute log base 2 via -- --
--   logBase2 x = finiteBitSize x - 1 - countLeadingZeros x
--   
-- -- Note: The default implementation for this method is intentionally -- naive. However, the instances provided for the primitive integral -- types are implemented using CPU specific machine instructions. countLeadingZeros :: FiniteBits b => b -> Int -- | Count number of zero bits following the least significant set bit. -- --
--   countTrailingZeros (zeroBits :: a) = finiteBitSize (zeroBits :: a)
--   countTrailingZeros . negate = countTrailingZeros
--   
-- -- The related find-first-set operation can be expressed in terms -- of countTrailingZeros as follows -- --
--   findFirstSet x = 1 + countTrailingZeros x
--   
-- -- Note: The default implementation for this method is intentionally -- naive. However, the instances provided for the primitive integral -- types are implemented using CPU specific machine instructions. countTrailingZeros :: FiniteBits b => b -> Int class (Num t, FiniteBits t) => Ranked t -- | Calculate the least significant set bit using a debruijn -- multiplication table. NB: The result of this function is -- undefined when given 0. lsb :: Ranked t => t -> Int -- | Calculate the number of trailing 0 bits. rank :: Ranked t => t -> Int -- | Calculate the number of leading zeros. nlz :: Ranked t => t -> Int -- | Calculate the most significant set bit. msb :: Ranked t => t -> Int -- | Default implementation for bit. -- -- Note that: bitDefault i = 1 shiftL i bitDefault :: (Bits a, Num a) => Int -> a -- | Default implementation for testBit. -- -- Note that: testBitDefault x i = (x .&. bit i) /= 0 testBitDefault :: (Bits a, Num a) => a -> Int -> Bool -- | Default implementation for popCount. -- -- This implementation is intentionally naive. Instances are expected to -- provide an optimized implementation for their size. popCountDefault :: (Bits a, Num a) => a -> Int module Bool data Bool False :: Bool True :: Bool -- | Boolean "and" (&&) :: Bool -> Bool -> Bool infixr 3 && -- | Boolean "or" (||) :: Bool -> Bool -> Bool infixr 2 || -- | Boolean "not" not :: Bool -> Bool -- | otherwise is defined as the value True. It helps to make -- guards more readable. eg. -- --
--   f x | x < 0     = ...
--       | otherwise = ...
--   
otherwise :: Bool -- | 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 -- | Boolean monoid under conjunction (&&). -- --
--   >>> getAll (All True <> mempty <> All False)
--   False
--   
-- --
--   >>> getAll (mconcat (map (\x -> All (even x)) [2,4,6,7,8]))
--   False
--   
newtype All All :: Bool -> All [getAll] :: All -> Bool -- | Boolean monoid under disjunction (||). -- --
--   >>> getAny (Any True <> mempty <> Any False)
--   True
--   
-- --
--   >>> getAny (mconcat (map (\x -> Any (even x)) [2,4,6,7,8]))
--   True
--   
newtype Any Any :: Bool -> Any [getAny] :: Any -> Bool -- | Type-level If. If True a b ==> a; If -- False a b ==> b -- | Type-level "and" -- | Type-level "or" -- | Type-level "not". An injective type family since 4.10.0.0. module Bounded -- | 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 -- | The greatest lower bound of s. -- -- Laws: -- -- If s is Bounded, we require lowerBound and -- minBound to agree: -- --
--   lowerBound = minBound
--   
-- -- If s is a Join semilattice, lowerBound must -- be the identity of \/: -- --
--   lowerBound \/ a = a
--   
-- -- If s is a Meet semilattice, lowerBound must -- be the absorbing element of /\: -- --
--   lowerBound /\ a = lowerBound
--   
-- -- If s is Ordered, lowerBound must be at least as -- small as every terminating value: -- --
--   compare lowerBound a /= GT
--   
class Lower s lowerBound :: Lower s => s -- | The least upper bound of s. -- -- Laws: -- -- If s is Bounded, we require upperBound and -- maxBound to agree: -- --
--   upperBound = maxBound
--   
-- -- If s is a Meet semilattice, upperBound must -- be the identity of /\: -- --
--   upperBound /\ a = a
--   
-- -- If s is a Join semilattice, upperBound must -- be the absorbing element of \/: -- --
--   upperBound \/ a = upperBound
--   
-- -- If s is Ordered, upperBound must be at least as -- large as every terminating value: -- --
--   compare upperBound a /= LT
--   
class Upper s upperBound :: Upper s => s -- | A convenience bridging Bounded to Lower and -- Upper. newtype Bound a Bound :: a -> Bound a [getBound] :: Bound a -> a module ByteString -- | 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 -- | O(n) Applied to a predicate and a ByteString, all -- determines if all elements of the ByteString satisfy the -- predicate. all :: Word8 -> Bool -> ByteString -> Bool -- | O(n) Applied to a predicate and a ByteString, any -- determines if any element of the ByteString satisfies the -- predicate. any :: Word8 -> Bool -> ByteString -> Bool -- | Convert a bitvector into a lower-case ASCII hexadecimal string. This -- is helpful for visualizing raw binary data, rather than for parsing as -- such. asHexadecimal :: ByteString -> ByteString -- | O(n) Append two ByteStrings append :: ByteString -> ByteString -> ByteString -- | break p is equivalent to span (not . -- p). -- -- Under GHC, a rewrite rule will transform break (==) into a call to the -- specialised breakByte: -- --
--   break ((==) x) = breakByte x
--   break (==x) = breakByte x
--   
break :: Word8 -> Bool -> ByteString -> (ByteString, ByteString) -- | breakEnd behaves like break but from the end of the -- ByteString -- -- breakEnd p == spanEnd (not.p) breakEnd :: Word8 -> Bool -> ByteString -> (ByteString, ByteString) -- | Break a string on a substring, returning a pair of the part of the -- string prior to the match, and the rest of the string. -- -- The following relationships hold: -- --
--   break (== c) l == breakSubstring (singleton c) l
--   
-- -- and: -- --
--   findSubstring s l ==
--      if null s then Just 0
--                else case breakSubstring s l of
--                         (x,y) | null y    -> Nothing
--                               | otherwise -> Just (length x)
--   
-- -- For example, to tokenise a string, dropping delimiters: -- --
--   tokenise x y = h : if null t then [] else tokenise x (drop (length x) t)
--       where (h,t) = breakSubstring x y
--   
-- -- To skip to the first occurence of a string: -- --
--   snd (breakSubstring x y)
--   
-- -- To take the parts of a string before a delimiter: -- --
--   fst (breakSubstring x y)
--   
-- -- Note that calling `breakSubstring x` does some preprocessing work, so -- you should avoid unnecessarily duplicating breakSubstring calls with -- the same pattern. breakSubstring :: ByteString -> ByteString -> (ByteString, ByteString) -- | O(n) Concatenate a list of ByteStrings. concat :: [ByteString] -> ByteString -- | Map a function over a ByteString and concatenate the results concatMap :: Word8 -> ByteString -> ByteString -> ByteString -- | O(n) cons is analogous to (:) for lists, but of -- different complexity, as it requires making a copy. cons :: Word8 -> ByteString -> ByteString infixr 5 `cons` -- | O(n) Make a copy of the ByteString with its own storage. -- This is mainly useful to allow the rest of the data pointed to by the -- ByteString to be garbage collected, for example if a large -- string has been read in, and only a small part of it is needed in the -- rest of the program. copy :: ByteString -> ByteString -- | count returns the number of times its argument appears in the -- ByteString -- --
--   count = length . elemIndices
--   
-- -- But more efficiently than using length on the intermediate list. count :: Word8 -> ByteString -> Int -- | O(1) drop n xs returns the suffix of -- xs after the first n elements, or [] if -- n > length xs. drop :: Int -> ByteString -> ByteString -- | dropWhile p xs returns the suffix remaining after -- takeWhile p xs. dropWhile :: Word8 -> Bool -> ByteString -> ByteString -- | O(n) elem is the ByteString membership predicate. elem :: Word8 -> ByteString -> Bool -- | O(n) The elemIndex function returns the index of the -- first element in the given ByteString which is equal to the -- query element, or Nothing if there is no such element. This -- implementation uses memchr(3). elemIndex :: Word8 -> ByteString -> Maybe Int -- | O(n) The elemIndexEnd function returns the last index of -- the element in the given ByteString which is equal to the query -- element, or Nothing if there is no such element. The following -- holds: -- --
--   elemIndexEnd c xs ==
--   (-) (length xs - 1) `fmap` elemIndex c (reverse xs)
--   
elemIndexEnd :: Word8 -> ByteString -> Maybe Int -- | O(n) The elemIndices function extends elemIndex, -- by returning the indices of all elements equal to the query element, -- in ascending order. This implementation uses memchr(3). elemIndices :: Word8 -> ByteString -> [Int] -- | O(1) The empty ByteString empty :: ByteString -- | O(n) filter, applied to a predicate and a ByteString, -- returns a ByteString containing those characters that satisfy the -- predicate. filter :: Word8 -> Bool -> ByteString -> ByteString -- | O(n) The find function takes a predicate and a -- ByteString, and returns the first element in matching the predicate, -- or Nothing if there is no such element. -- --
--   find f p = case findIndex f p of Just n -> Just (p ! n) ; _ -> Nothing
--   
find :: Word8 -> Bool -> ByteString -> Maybe Word8 -- | The findIndex function takes a predicate and a -- ByteString and returns the index of the first element in the -- ByteString satisfying the predicate. findIndex :: Word8 -> Bool -> ByteString -> Maybe Int -- | The findIndices function extends findIndex, by returning -- the indices of all elements satisfying the predicate, in ascending -- order. findIndices :: Word8 -> Bool -> ByteString -> [Int] -- | foldl' is like foldl, but strict in the accumulator. foldl' :: () => a -> Word8 -> a -> a -> ByteString -> a -- | foldr, applied to a binary operator, a starting value -- (typically the right-identity of the operator), and a ByteString, -- reduces the ByteString using the binary operator, from right to left. foldr :: () => Word8 -> a -> a -> a -> ByteString -> a -- | The group function takes a ByteString and returns a list of -- ByteStrings 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. It is about 40% faster than groupBy -- (==) group :: ByteString -> [ByteString] -- | The groupBy function is the non-overloaded version of -- group. groupBy :: Word8 -> Word8 -> Bool -> ByteString -> [ByteString] -- | O(1) ByteString index (subscript) operator, starting -- from 0. index :: ByteString -> Int -> Word8 -- | O(n) Return all initial segments of the given -- ByteString, shortest first. inits :: ByteString -> [ByteString] -- | O(n) The intercalate function takes a ByteString -- and a list of ByteStrings and concatenates the list after -- interspersing the first argument between each element of the list. intercalate :: ByteString -> [ByteString] -> ByteString -- | O(n) The intersperse function takes a Word8 and a -- ByteString and `intersperses' that byte between the elements of -- the ByteString. It is analogous to the intersperse function on -- Lists. intersperse :: Word8 -> ByteString -> ByteString -- | Check whether one string is a substring of another. isInfixOf p -- s is equivalent to not (null (findSubstrings p s)). isInfixOf :: ByteString -> ByteString -> Bool -- | O(n) The isPrefixOf function takes two ByteStrings and -- returns True if the first is a prefix of the second. isPrefixOf :: ByteString -> ByteString -> Bool -- | O(n) The isSuffixOf function takes two ByteStrings and -- returns True iff the first is a suffix of the second. -- -- The following holds: -- --
--   isSuffixOf x y == reverse x `isPrefixOf` reverse y
--   
-- -- However, the real implemenation uses memcmp to compare the end of the -- string only, with no reverse required.. isSuffixOf :: ByteString -> ByteString -> Bool -- | O(1) length returns the length of a ByteString as an -- Int. length :: ByteString -> Int -- | O(n) map f xs is the ByteString obtained by -- applying f to each element of xs. map :: Word8 -> Word8 -> ByteString -> ByteString -- | The mapAccumL function behaves like a combination of map -- and foldl; it applies a function to each element of a -- ByteString, passing an accumulating parameter from left to right, and -- returning a final value of this accumulator together with the new -- list. mapAccumL :: () => acc -> Word8 -> (acc, Word8) -> acc -> ByteString -> (acc, ByteString) -- | The mapAccumR function behaves like a combination of map -- and foldr; it applies a function to each element of a -- ByteString, passing an accumulating parameter from right to left, and -- returning a final value of this accumulator together with the new -- ByteString. mapAccumR :: () => acc -> Word8 -> (acc, Word8) -> acc -> ByteString -> (acc, ByteString) -- | O(n) notElem is the inverse of elem notElem :: Word8 -> ByteString -> Bool -- | O(1) Test whether a ByteString is empty. null :: ByteString -> Bool -- | O(n) Convert a [Word8] into a -- ByteString. -- -- For applications with large numbers of string literals, pack can be a -- bottleneck. In such cases, consider using packAddress (GHC only). pack :: [Word8] -> ByteString -- | O(n). Construct a new ByteString from a -- CString. The resulting ByteString is an immutable -- copy of the original CString, and is managed on the Haskell -- heap. The original CString must be null terminated. packCString :: CString -> IO ByteString -- | O(n). Construct a new ByteString from a -- CStringLen. The resulting ByteString is an immutable -- copy of the original CStringLen. The ByteString is a -- normal Haskell value and will be managed on the Haskell heap. packCStringLen :: CStringLen -> IO ByteString -- | O(n) The partition function takes a predicate a -- ByteString and returns the pair of ByteStrings with elements which do -- and do not satisfy the predicate, respectively; i.e., -- --
--   partition p bs == (filter p xs, filter (not . p) xs)
--   
partition :: Word8 -> Bool -> ByteString -> (ByteString, ByteString) -- | O(n) replicate n x is a ByteString of length -- n with x the value of every element. The following -- holds: -- --
--   replicate w c = unfoldr w (\u -> Just (u,u)) c
--   
-- -- This implemenation uses memset(3) replicate :: Int -> Word8 -> ByteString -- | O(n) reverse xs efficiently returns the -- elements of xs in reverse order. reverse :: ByteString -> ByteString -- | scanl is similar to foldl, but returns a list of -- successive reduced values from the left. This function will fuse. -- --
--   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 :: Word8 -> Word8 -> Word8 -> Word8 -> ByteString -> ByteString -- | scanl1 is a variant of scanl that has no starting value -- argument. This function will fuse. -- --
--   scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
--   
scanl1 :: Word8 -> Word8 -> Word8 -> ByteString -> ByteString -- | scanr is the right-to-left dual of scanl. scanr :: Word8 -> Word8 -> Word8 -> Word8 -> ByteString -> ByteString -- | scanr1 is a variant of scanr that has no starting value -- argument. scanr1 :: Word8 -> Word8 -> Word8 -> ByteString -> ByteString -- | O(1) Convert a Word8 into a ByteString singleton :: Word8 -> ByteString -- | O(n) Append a byte to the end of a ByteString snoc :: ByteString -> Word8 -> ByteString infixl 5 `snoc` -- | O(n) Sort a ByteString efficiently, using counting sort. sort :: ByteString -> ByteString -- | span p xs breaks the ByteString into two segments. It -- is equivalent to (takeWhile p xs, dropWhile p -- xs) span :: Word8 -> Bool -> ByteString -> (ByteString, ByteString) -- | spanEnd behaves like span but from the end of the -- ByteString. We have -- --
--   spanEnd (not.isSpace) "x y z" == ("x y ","z")
--   
-- -- and -- --
--   spanEnd (not . isSpace) ps
--      ==
--   let (x,y) = span (not.isSpace) (reverse ps) in (reverse y, reverse x)
--   
spanEnd :: Word8 -> Bool -> ByteString -> (ByteString, ByteString) -- | O(n) Break a ByteString into pieces separated by the -- byte argument, consuming the delimiter. I.e. -- --
--   split '\n' "a\nb\nd\ne" == ["a","b","d","e"]
--   split 'a'  "aXaXaXa"    == ["","X","X","X",""]
--   split 'x'  "x"          == ["",""]
--   
-- -- and -- --
--   intercalate [c] . split c == id
--   split == splitWith . (==)
--   
-- -- As for all splitting functions in this library, this function does not -- copy the substrings, it just constructs new ByteStrings that -- are slices of the original. split :: Word8 -> ByteString -> [ByteString] -- | O(1) splitAt n xs is equivalent to -- (take n xs, drop n xs). splitAt :: Int -> ByteString -> (ByteString, ByteString) -- | O(n) Splits a ByteString into components delimited by -- separators, where the predicate returns True for a separator element. -- The resulting components do not contain the separators. Two adjacent -- separators result in an empty component in the output. eg. -- --
--   splitWith (=='a') "aabbaca" == ["","","bb","c",""]
--   splitWith (=='a') []        == []
--   
splitWith :: Word8 -> Bool -> ByteString -> [ByteString] -- | O(n) The stripPrefix function takes two ByteStrings and -- returns Just the remainder of the second iff the first is its -- prefix, and otherwise Nothing. stripPrefix :: ByteString -> ByteString -> Maybe ByteString -- | O(n) The stripSuffix function takes two ByteStrings and -- returns Just the remainder of the second iff the first is its -- suffix, and otherwise Nothing. stripSuffix :: ByteString -> ByteString -> Maybe ByteString -- | O(n) Return all final segments of the given ByteString, -- longest first. tails :: ByteString -> [ByteString] -- | O(1) take n, applied to a ByteString -- xs, returns the prefix of xs of length n, -- or xs itself if n > length xs. take :: Int -> ByteString -> ByteString -- | takeWhile, applied to a predicate p and a ByteString -- xs, returns the longest prefix (possibly empty) of -- xs of elements that satisfy p. takeWhile :: Word8 -> Bool -> ByteString -> ByteString -- | The transpose function transposes the rows and columns of its -- ByteString argument. transpose :: [ByteString] -> [ByteString] -- | O(1) Extract the head and tail of a ByteString, returning -- Nothing if it is empty. uncons :: ByteString -> Maybe (Word8, ByteString) -- | O(n), where n is the length of the result. The -- unfoldr function is analogous to the List 'unfoldr'. -- unfoldr builds a ByteString from a seed value. The function -- takes the element and returns Nothing if it is done producing -- the ByteString or returns Just (a,b), in which case, -- a is the next byte in the string, and b is the seed -- value for further production. -- -- Examples: -- --
--      unfoldr (\x -> if x <= 5 then Just (x, x + 1) else Nothing) 0
--   == pack [0, 1, 2, 3, 4, 5]
--   
unfoldr :: () => a -> Maybe (Word8, a) -> a -> ByteString -- | O(n) Like unfoldr, unfoldrN builds a ByteString -- from a seed value. However, the length of the result is limited by the -- first argument to unfoldrN. This function is more efficient -- than unfoldr when the maximum length of the result is known. -- -- The following equation relates unfoldrN and unfoldr: -- --
--   fst (unfoldrN n f s) == take n (unfoldr f s)
--   
unfoldrN :: () => Int -> a -> Maybe (Word8, a) -> a -> (ByteString, Maybe a) -- | O(n) Converts a ByteString to a [Word8]. unpack :: ByteString -> [Word8] -- | O(1) Extract the init and last of a ByteString, -- returning Nothing if it is empty. unsnoc :: ByteString -> Maybe (ByteString, Word8) -- | O(n) unzip transforms a list of pairs of bytes into a -- pair of ByteStrings. Note that this performs two pack -- operations. unzip :: [(Word8, Word8)] -> (ByteString, ByteString) -- | O(n) construction Use a ByteString with a function -- requiring a null-terminated CString. The CString is -- a copy and will be freed automatically; it must not be stored or used -- after the subcomputation finishes. useAsCString :: () => ByteString -> CString -> IO a -> IO a -- | O(n) construction Use a ByteString with a function -- requiring a CStringLen. As for useAsCString this -- function makes a copy of the original ByteString. It must not -- be stored or used after the subcomputation finishes. useAsCStringLen :: () => ByteString -> CStringLen -> IO a -> IO a -- | O(n) zip takes two ByteStrings and returns a list of -- corresponding pairs of bytes. If one input ByteString is short, excess -- elements of the longer ByteString are discarded. This is equivalent to -- a pair of unpack operations. zip :: ByteString -> ByteString -> [(Word8, Word8)] -- | zipWith generalises zip by zipping with the function -- given as the first argument, instead of a tupling function. For -- example, zipWith (+) is applied to two ByteStrings to -- produce the list of corresponding sums. zipWith :: () => Word8 -> Word8 -> a -> ByteString -> ByteString -> [a] -- | Traverse each Word8 in a strict or lazy ByteString -- -- This Traversal walks each strict ByteString chunk in a -- tree-like fashion enable zippers to seek to locations more quickly and -- accelerate many monoidal queries, but up to associativity (and -- constant factors) it is equivalent to the much slower: -- --
--   bytesunpackedBytes . traversed
--   
-- --
--   anyOf bytes (== 0x80) :: ByteString -> Bool
--   
bytes :: IsByteString t => IndexedTraversal' Int t Word8 -- | pack (or unpack) a list of bytes into a strict or lazy -- ByteString. -- --
--   pack x ≡ x ^. packedBytes
--   unpack x ≡ x ^. from packedBytes
--   packedBytesfrom unpackedBytes
--   
packedBytes :: IsByteString t => Iso' [Word8] t -- | unpack (or pack) a ByteString into a list of -- bytes -- --
--   unpackedBytesfrom packedBytes
--   unpack x ≡ x ^. unpackedBytes
--   pack x ≡  x ^. from unpackedBytes
--   
-- --
--   unpackedBytes :: Iso' ByteString [Word8]
--   unpackedBytes :: Iso' ByteString [Word8]
--   
unpackedBytes :: IsByteString t => Iso' t [Word8] module ByteString.Base16 -- | Encode a string into base16 form. The result will always be a multiple -- of 2 bytes in length. -- -- Example: -- --
--   encode "foo"  == "666f6f"
--   
encode :: ByteString -> ByteString -- | Decode a string from base16 form. The first element of the returned -- tuple contains the decoded data. The second element starts at the -- first invalid base16 sequence in the original string. -- -- Examples: -- --
--   decode "666f6f"  == ("foo", "")
--   decode "66quux"  == ("f", "quux")
--   decode "666quux" == ("f", "6quux")
--   
decode :: ByteString -> (ByteString, ByteString) module ByteString.Latin1 -- | Applied to a predicate and a ByteString, all determines -- if all elements of the ByteString satisfy the predicate. all :: Char -> Bool -> ByteString -> Bool -- | Applied to a predicate and a ByteString, any determines if any -- element of the ByteString satisfies the predicate. any :: Char -> Bool -> ByteString -> Bool -- | O(n) Append two ByteStrings append :: ByteString -> ByteString -> ByteString -- | break p is equivalent to span (not . -- p). break :: Char -> Bool -> ByteString -> (ByteString, ByteString) -- | breakEnd behaves like break but from the end of the -- ByteString -- -- breakEnd p == spanEnd (not.p) breakEnd :: Char -> Bool -> ByteString -> (ByteString, ByteString) -- | Break a string on a substring, returning a pair of the part of the -- string prior to the match, and the rest of the string. -- -- The following relationships hold: -- --
--   break (== c) l == breakSubstring (singleton c) l
--   
-- -- and: -- --
--   findSubstring s l ==
--      if null s then Just 0
--                else case breakSubstring s l of
--                         (x,y) | null y    -> Nothing
--                               | otherwise -> Just (length x)
--   
-- -- For example, to tokenise a string, dropping delimiters: -- --
--   tokenise x y = h : if null t then [] else tokenise x (drop (length x) t)
--       where (h,t) = breakSubstring x y
--   
-- -- To skip to the first occurence of a string: -- --
--   snd (breakSubstring x y)
--   
-- -- To take the parts of a string before a delimiter: -- --
--   fst (breakSubstring x y)
--   
-- -- Note that calling `breakSubstring x` does some preprocessing work, so -- you should avoid unnecessarily duplicating breakSubstring calls with -- the same pattern. breakSubstring :: ByteString -> ByteString -> (ByteString, ByteString) -- | O(n) Concatenate a list of ByteStrings. concat :: [ByteString] -> ByteString -- | Map a function over a ByteString and concatenate the results concatMap :: Char -> ByteString -> ByteString -> ByteString -- | O(n) cons is analogous to (:) for lists, but of -- different complexity, as it requires a memcpy. cons :: Char -> ByteString -> ByteString infixr 5 `cons` -- | O(n) Make a copy of the ByteString with its own storage. -- This is mainly useful to allow the rest of the data pointed to by the -- ByteString to be garbage collected, for example if a large -- string has been read in, and only a small part of it is needed in the -- rest of the program. copy :: ByteString -> ByteString -- | count returns the number of times its argument appears in the -- ByteString -- --
--   count = length . elemIndices
--   
-- -- Also -- --
--   count '\n' == length . lines
--   
-- -- But more efficiently than using length on the intermediate list. count :: Char -> ByteString -> Int -- | O(1) drop n xs returns the suffix of -- xs after the first n elements, or [] if -- n > length xs. drop :: Int -> ByteString -> ByteString -- | dropWhile p xs returns the suffix remaining after -- takeWhile p xs. dropWhile :: Char -> Bool -> ByteString -> ByteString -- | O(n) elem is the ByteString membership predicate. -- This implementation uses memchr(3). elem :: Char -> ByteString -> Bool -- | O(n) The elemIndex function returns the index of the -- first element in the given ByteString which is equal (by -- memchr) to the query element, or Nothing if there is no such -- element. elemIndex :: Char -> ByteString -> Maybe Int -- | O(n) The elemIndexEnd function returns the last index of -- the element in the given ByteString which is equal to the query -- element, or Nothing if there is no such element. The following -- holds: -- --
--   elemIndexEnd c xs ==
--   (-) (length xs - 1) `fmap` elemIndex c (reverse xs)
--   
elemIndexEnd :: Char -> ByteString -> Maybe Int -- | O(n) The elemIndices function extends elemIndex, -- by returning the indices of all elements equal to the query element, -- in ascending order. elemIndices :: Char -> ByteString -> [Int] -- | O(1) The empty ByteString empty :: ByteString -- | O(n) filter, applied to a predicate and a ByteString, -- returns a ByteString containing those characters that satisfy the -- predicate. filter :: Char -> Bool -> ByteString -> ByteString -- | O(n) The find function takes a predicate and a -- ByteString, and returns the first element in matching the predicate, -- or Nothing if there is no such element. find :: Char -> Bool -> ByteString -> Maybe Char -- | The findIndex function takes a predicate and a -- ByteString and returns the index of the first element in the -- ByteString satisfying the predicate. findIndex :: Char -> Bool -> ByteString -> Maybe Int -- | The findIndices function extends findIndex, by returning -- the indices of all elements satisfying the predicate, in ascending -- order. findIndices :: Char -> Bool -> ByteString -> [Int] -- | 'foldl\'' is like foldl, but strict in the accumulator. foldl' :: () => a -> Char -> a -> a -> ByteString -> a -- | 'foldr\'' is a strict variant of foldr foldr' :: () => Char -> a -> a -> a -> ByteString -> a -- | foldr, applied to a binary operator, a starting value -- (typically the right-identity of the operator), and a packed string, -- reduces the packed string using the binary operator, from right to -- left. foldr :: () => Char -> a -> a -> a -> ByteString -> a -- | The group function takes a ByteString and returns a list of -- ByteStrings 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. It is about 40% faster than groupBy -- (==) group :: ByteString -> [ByteString] -- | The groupBy function is the non-overloaded version of -- group. groupBy :: Char -> Char -> Bool -> ByteString -> [ByteString] -- | O(n) Return all initial segments of the given -- ByteString, shortest first. inits :: ByteString -> [ByteString] -- | O(n) The intercalate function takes a ByteString -- and a list of ByteStrings and concatenates the list after -- interspersing the first argument between each element of the list. intercalate :: ByteString -> [ByteString] -> ByteString -- | O(n) The intersperse function takes a Char and a -- ByteString and `intersperses' that Char between the elements of -- the ByteString. It is analogous to the intersperse function on -- Lists. intersperse :: Char -> ByteString -> ByteString -- | Check whether one string is a substring of another. isInfixOf p -- s is equivalent to not (null (findSubstrings p s)). isInfixOf :: ByteString -> ByteString -> Bool -- | O(n) The isPrefixOf function takes two ByteStrings and -- returns True if the first is a prefix of the second. isPrefixOf :: ByteString -> ByteString -> Bool -- | O(n) The isSuffixOf function takes two ByteStrings and -- returns True iff the first is a suffix of the second. -- -- The following holds: -- --
--   isSuffixOf x y == reverse x `isPrefixOf` reverse y
--   
-- -- However, the real implemenation uses memcmp to compare the end of the -- string only, with no reverse required.. isSuffixOf :: ByteString -> ByteString -> Bool -- | O(1) length returns the length of a ByteString as an -- Int. length :: ByteString -> Int -- | lines breaks a ByteString up into a list of ByteStrings at -- newline Chars. The resulting strings do not contain newlines. lines :: ByteString -> [ByteString] -- | O(n) map f xs is the ByteString obtained by -- applying f to each element of xs map :: Char -> Char -> ByteString -> ByteString -- | The mapAccumL function behaves like a combination of map -- and foldl; it applies a function to each element of a -- ByteString, passing an accumulating parameter from left to right, and -- returning a final value of this accumulator together with the new -- list. mapAccumL :: () => acc -> Char -> (acc, Char) -> acc -> ByteString -> (acc, ByteString) -- | The mapAccumR function behaves like a combination of map -- and foldr; it applies a function to each element of a -- ByteString, passing an accumulating parameter from right to left, and -- returning a final value of this accumulator together with the new -- ByteString. mapAccumR :: () => acc -> Char -> (acc, Char) -> acc -> ByteString -> (acc, ByteString) -- | O(n) notElem is the inverse of elem notElem :: Char -> ByteString -> Bool -- | O(1) Test whether a ByteString is empty. null :: ByteString -> Bool -- | O(n) Convert a String into a ByteString -- -- For applications with large numbers of string literals, pack can be a -- bottleneck. pack :: String -> ByteString -- | O(n). Construct a new ByteString from a -- CString. The resulting ByteString is an immutable -- copy of the original CString, and is managed on the Haskell -- heap. The original CString must be null terminated. packCString :: CString -> IO ByteString -- | O(n). Construct a new ByteString from a -- CStringLen. The resulting ByteString is an immutable -- copy of the original CStringLen. The ByteString is a -- normal Haskell value and will be managed on the Haskell heap. packCStringLen :: CStringLen -> IO ByteString -- | Convert a non-negative integer into an (unsigned) ASCII decimal -- string. Returns Nothing on negative inputs. packDecimal :: Integral a => a -> Maybe ByteString -- | Convert a non-negative integer into a lower-case ASCII hexadecimal -- string. Returns Nothing on negative inputs. packHexadecimal :: Integral a => a -> Maybe ByteString -- | Convert a non-negative integer into an ASCII octal string. Returns -- Nothing on negative inputs. packOctal :: Integral a => a -> Maybe ByteString -- | Read an unsigned/non-negative integral value in ASCII decimal format. -- Returns Nothing if there is no integer at the beginning of -- the string, otherwise returns Just the integer read and the -- remainder of the string. -- -- If you are extremely concerned with performance, then it is more -- performant to use this function at Int or Word and -- then to call fromIntegral to perform the conversion at the end. -- However, doing this will make your code succeptible to overflow bugs -- if the target type is larger than Int. readDecimal :: Integral a => ByteString -> Maybe (a, ByteString) -- | readInt reads an Int from the beginning of the ByteString. If there is -- no integer at the beginning of the string, it returns Nothing, -- otherwise it just returns the int read, and the rest of the string. readInt :: ByteString -> Maybe (Int, ByteString) -- | readInteger reads an Integer from the beginning of the ByteString. If -- there is no integer at the beginning of the string, it returns -- Nothing, otherwise it just returns the int read, and the rest of the -- string. readInteger :: ByteString -> Maybe (Integer, ByteString) -- | Read a non-negative integral value in ASCII hexadecimal format. -- Returns Nothing if there is no integer at the beginning of -- the string, otherwise returns Just the integer read and the -- remainder of the string. -- -- This function does not recognize the various hexadecimal sigils like -- "0x", but because there are so many different variants, those are best -- handled by helper functions which then use this function for the -- actual numerical parsing. This function recognizes both upper-case, -- lower-case, and mixed-case hexadecimal. readHexadecimal :: Integral a => ByteString -> Maybe (a, ByteString) -- | Read a non-negative integral value in ASCII octal format. Returns -- Nothing if there is no integer at the beginning of the -- string, otherwise returns Just the integer read and the -- remainder of the string. -- -- This function does not recognize the various octal sigils like "0o", -- but because there are different variants, those are best handled by -- helper functions which then use this function for the actual numerical -- parsing. readOctal :: Integral a => ByteString -> Maybe (a, ByteString) -- | Adjust a reading function to recognize an optional leading sign. As -- with the other functions, we assume an ASCII-compatible encoding of -- the sign characters. readSigned :: Num a => ByteString -> Maybe (a, ByteString) -> ByteString -> Maybe (a, ByteString) -- | O(n) replicate n x is a ByteString of length -- n with x the value of every element. The following -- holds: -- --
--   replicate w c = unfoldr w (\u -> Just (u,u)) c
--   
-- -- This implemenation uses memset(3) replicate :: Int -> Char -> ByteString -- | O(n) reverse xs efficiently returns the -- elements of xs in reverse order. reverse :: ByteString -> ByteString -- | 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 :: Char -> Char -> Char -> Char -> ByteString -> ByteString -- | scanl1 is a variant of scanl that has no starting value -- argument: -- --
--   scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
--   
scanl1 :: Char -> Char -> Char -> ByteString -> ByteString -- | scanr is the right-to-left dual of scanl. scanr :: Char -> Char -> Char -> Char -> ByteString -> ByteString -- | scanr1 is a variant of scanr that has no starting value -- argument. scanr1 :: Char -> Char -> Char -> ByteString -> ByteString -- | O(1) Convert a Char into a ByteString singleton :: Char -> ByteString -- | O(n) Append a Char to the end of a ByteString. Similar -- to cons, this function performs a memcpy. snoc :: ByteString -> Char -> ByteString infixl 5 `snoc` -- | O(n) Sort a ByteString efficiently, using counting sort. sort :: ByteString -> ByteString -- | span p xs breaks the ByteString into two segments. It -- is equivalent to (takeWhile p xs, dropWhile p -- xs) span :: Char -> Bool -> ByteString -> (ByteString, ByteString) -- | spanEnd behaves like span but from the end of the -- ByteString. We have -- --
--   spanEnd (not.isSpace) "x y z" == ("x y ","z")
--   
-- -- and -- --
--   spanEnd (not . isSpace) ps
--      ==
--   let (x,y) = span (not.isSpace) (reverse ps) in (reverse y, reverse x)
--   
spanEnd :: Char -> Bool -> ByteString -> (ByteString, ByteString) -- | O(n) Break a ByteString into pieces separated by the -- byte argument, consuming the delimiter. I.e. -- --
--   split '\n' "a\nb\nd\ne" == ["a","b","d","e"]
--   split 'a'  "aXaXaXa"    == ["","X","X","X",""]
--   split 'x'  "x"          == ["",""]
--   
-- -- and -- --
--   intercalate [c] . split c == id
--   split == splitWith . (==)
--   
-- -- As for all splitting functions in this library, this function does not -- copy the substrings, it just constructs new ByteStrings that -- are slices of the original. split :: Char -> ByteString -> [ByteString] -- | O(1) splitAt n xs is equivalent to -- (take n xs, drop n xs). splitAt :: Int -> ByteString -> (ByteString, ByteString) -- | O(n) Splits a ByteString into components delimited by -- separators, where the predicate returns True for a separator element. -- The resulting components do not contain the separators. Two adjacent -- separators result in an empty component in the output. eg. -- --
--   splitWith (=='a') "aabbaca" == ["","","bb","c",""]
--   
splitWith :: Char -> Bool -> ByteString -> [ByteString] -- | O(n) The stripPrefix function takes two ByteStrings and -- returns Just the remainder of the second iff the first is its -- prefix, and otherwise Nothing. stripPrefix :: ByteString -> ByteString -> Maybe ByteString -- | O(n) The stripSuffix function takes two ByteStrings and -- returns Just the remainder of the second iff the first is its -- suffix, and otherwise Nothing. stripSuffix :: ByteString -> ByteString -> Maybe ByteString -- | O(n) Return all final segments of the given ByteString, -- longest first. tails :: ByteString -> [ByteString] -- | O(1) take n, applied to a ByteString -- xs, returns the prefix of xs of length n, -- or xs itself if n > length xs. take :: Int -> ByteString -> ByteString -- | takeWhile, applied to a predicate p and a ByteString -- xs, returns the longest prefix (possibly empty) of -- xs of elements that satisfy p. takeWhile :: Char -> Bool -> ByteString -> ByteString -- | The transpose function transposes the rows and columns of its -- ByteString argument. transpose :: [ByteString] -> [ByteString] -- | O(1) Extract the head and tail of a ByteString, returning -- Nothing if it is empty. uncons :: ByteString -> Maybe (Char, ByteString) -- | O(n), where n is the length of the result. The -- unfoldr function is analogous to the List 'unfoldr'. -- unfoldr builds a ByteString from a seed value. The function -- takes the element and returns Nothing if it is done producing -- the ByteString or returns Just (a,b), in which case, -- a is the next character in the string, and b is the -- seed value for further production. -- -- Examples: -- --
--   unfoldr (\x -> if x <= '9' then Just (x, succ x) else Nothing) '0' == "0123456789"
--   
unfoldr :: () => a -> Maybe (Char, a) -> a -> ByteString -- | O(n) Like unfoldr, unfoldrN builds a ByteString -- from a seed value. However, the length of the result is limited by the -- first argument to unfoldrN. This function is more efficient -- than unfoldr when the maximum length of the result is known. -- -- The following equation relates unfoldrN and unfoldr: -- --
--   unfoldrN n f s == take n (unfoldr f s)
--   
unfoldrN :: () => Int -> a -> Maybe (Char, a) -> a -> (ByteString, Maybe a) -- | unlines is an inverse operation to lines. It joins -- lines, after appending a terminating newline to each. unlines :: [ByteString] -> ByteString -- | O(n) Converts a ByteString to a String. unpack :: ByteString -> [Char] -- | O(1) Extract the init and last of a ByteString, -- returning Nothing if it is empty. unsnoc :: ByteString -> Maybe (ByteString, Char) -- | The unwords function is analogous to the unlines -- function, on words. unwords :: [ByteString] -> ByteString -- | unzip transforms a list of pairs of Chars into a pair of -- ByteStrings. Note that this performs two pack operations. unzip :: [(Char, Char)] -> (ByteString, ByteString) -- | O(n) construction Use a ByteString with a function -- requiring a null-terminated CString. The CString is -- a copy and will be freed automatically; it must not be stored or used -- after the subcomputation finishes. useAsCString :: () => ByteString -> CString -> IO a -> IO a -- | O(n) construction Use a ByteString with a function -- requiring a CStringLen. As for useAsCString this -- function makes a copy of the original ByteString. It must not -- be stored or used after the subcomputation finishes. useAsCStringLen :: () => ByteString -> CStringLen -> IO a -> IO a -- | words breaks a ByteString up into a list of words, which were -- delimited by Chars representing white space. words :: ByteString -> [ByteString] -- | O(n) zip takes two ByteStrings and returns a list of -- corresponding pairs of Chars. If one input ByteString is short, excess -- elements of the longer ByteString are discarded. This is equivalent to -- a pair of unpack operations, and so space usage may be large -- for multi-megabyte ByteStrings zip :: ByteString -> ByteString -> [(Char, Char)] -- | zipWith generalises zip by zipping with the function -- given as the first argument, instead of a tupling function. For -- example, zipWith (+) is applied to two ByteStrings to -- produce the list of corresponding sums. zipWith :: () => Char -> Char -> a -> ByteString -> ByteString -> [a] -- | Traverse the individual bytes in a strict or lazy ByteString as -- characters. -- -- When writing back to the ByteString it is assumed that every -- Char lies between '\x00' and '\xff'. -- -- This Traversal walks each strict ByteString chunk in a -- tree-like fashion enable zippers to seek to locations more quickly and -- accelerate many monoidal queries, but up to associativity (and -- constant factors) it is equivalent to the much slower: -- --
--   charsunpackedChars . traversed
--   
-- --
--   anyOf chars (== 'c') :: ByteString -> Bool
--   
chars :: IsByteString t => IndexedTraversal' Int t Char -- | pack (or unpack) a list of characters into a strict or -- lazy ByteString. -- -- When writing back to the ByteString it is assumed that every -- Char lies between '\x00' and '\xff'. -- --
--   pack x ≡ x ^. packedChars
--   unpack x ≡ x ^. from packedChars
--   packedCharsfrom unpackedChars
--   
packedChars :: IsByteString t => Iso' String t -- | unpack (or pack) a list of characters into a strict (or -- lazy) ByteString -- -- When writing back to the ByteString it is assumed that every -- Char lies between '\x00' and '\xff'. -- --
--   unpackedCharsfrom packedChars
--   unpack x ≡ x ^. unpackedChars
--   pack x ≡ x ^. from unpackedChars
--   
-- --
--   unpackedChars :: Iso' ByteString String
--   unpackedChars :: Iso' ByteString String
--   
unpackedChars :: IsByteString t => Iso' t String module ByteString.Latin1.Partial -- | A strict version of foldl1 foldl1' :: Char -> Char -> Char -> ByteString -> Char -- | foldr1 is a variant of foldr that has no starting value -- argument, and thus must be applied to non-empty ByteStrings foldr1 :: Char -> Char -> Char -> ByteString -> Char -- | A strict variant of foldr1 foldr1' :: Char -> Char -> Char -> ByteString -> Char -- | O(1) Extract the first element of a ByteString, which must be -- non-empty. head :: ByteString -> Char -- | O(1) ByteString index (subscript) operator, starting -- from 0. index :: ByteString -> Int -> Char -- | O(1) Return all the elements of a ByteString except the -- last one. An exception will be thrown in the case of an empty -- ByteString. init :: ByteString -> ByteString -- | O(1) Extract the last element of a packed string, which must be -- non-empty. last :: ByteString -> Char -- | maximum returns the maximum value from a ByteString maximum :: ByteString -> Char -- | minimum returns the minimum value from a ByteString minimum :: ByteString -> Char -- | O(1) Extract the elements after the head of a ByteString, which -- must be non-empty. An exception will be thrown in the case of an empty -- ByteString. tail :: ByteString -> ByteString module ByteString.Lazy -- | Traverse each Word8 in a strict or lazy ByteString -- -- This Traversal walks each strict ByteString chunk in a -- tree-like fashion enable zippers to seek to locations more quickly and -- accelerate many monoidal queries, but up to associativity (and -- constant factors) it is equivalent to the much slower: -- --
--   bytesunpackedBytes . traversed
--   
-- --
--   anyOf bytes (== 0x80) :: ByteString -> Bool
--   
bytes :: IsByteString t => IndexedTraversal' Int t Word8 -- | pack (or unpack) a list of bytes into a strict or lazy -- ByteString. -- --
--   pack x ≡ x ^. packedBytes
--   unpack x ≡ x ^. from packedBytes
--   packedBytesfrom unpackedBytes
--   
packedBytes :: IsByteString t => Iso' [Word8] t -- | unpack (or pack) a ByteString into a list of -- bytes -- --
--   unpackedBytesfrom packedBytes
--   unpack x ≡ x ^. unpackedBytes
--   pack x ≡  x ^. from unpackedBytes
--   
-- --
--   unpackedBytes :: Iso' ByteString [Word8]
--   unpackedBytes :: Iso' ByteString [Word8]
--   
unpackedBytes :: IsByteString t => Iso' t [Word8] module ByteString.Lazy.Base16 -- | Encode a string into base16 form. The result will always be a multiple -- of 2 bytes in length. -- -- Example: -- --
--   encode "foo"  == "666f6f"
--   
encode :: ByteString -> ByteString -- | Decode a string from base16 form. The first element of the returned -- tuple contains the decoded data. The second element starts at the -- first invalid base16 sequence in the original string. -- -- This function operates as lazily as possible over the input chunks. -- The only instance in which it is non-lazy is if an odd-length chunk -- ends with a byte that is valid base16. -- -- Examples: -- --
--   decode "666f6f"  == ("foo", "")
--   decode "66quux"  == ("f", "quux")
--   decode "666quux" == ("f", "6quux")
--   
decode :: ByteString -> (ByteString, ByteString) module ByteString.Lazy.Latin1 module ByteString.Lazy.Utf8 -- | Split a string into two parts: the first is the longest prefix that -- contains only characters that do not satisfy the predicate; the second -- part is the rest of the string. Invalid characters are passed as -- '\0xFFFD' to the predicate. break :: Char -> Bool -> ByteString -> (ByteString, ByteString) -- | drop n s returns the s without its first n -- characters. If s has less than n characters, then we -- return an empty string. drop :: Int64 -> ByteString -> ByteString -- | Traverse a bytestring (left biased). This function is strict in the -- accumulator. foldl :: () => a -> Char -> a -> a -> ByteString -> a -- | Traverse a bytestring (right biased). foldr :: () => Char -> a -> a -> a -> ByteString -> a -- | Converts a Haskell string into a UTF8 encoded bytestring. fromString :: String -> ByteString -- | Counts the number of characters encoded in the bytestring. Note that -- this includes replacement characters. length :: ByteString -> Int -- | Split a string into two parts: the first is the longest prefix that -- contains only characters that satisfy the predicate; the second part -- is the rest of the string. Invalid characters are passed as '\0xFFFD' -- to the predicate. span :: Char -> Bool -> ByteString -> (ByteString, ByteString) -- | Split after a given number of characters. Negative values are treated -- as if they are 0. splitAt :: Int64 -> ByteString -> (ByteString, ByteString) -- | take n s returns the first n characters of -- s. If s has less than n characters, then we -- return the whole of s. take :: Int64 -> ByteString -> ByteString -- | Convert a UTF8 encoded bytestring into a Haskell string. Invalid -- characters are replaced with '\xFFFD'. toString :: ByteString -> String -- | Get the first character of a byte string, if any. Malformed characters -- are replaced by '\0xFFFD'. uncons :: ByteString -> Maybe (Char, ByteString) -- | Encode/Decode a lazy Text to/from lazy ByteString, via -- UTF-8. -- -- Note: This function does not decode lazily, as it must consume the -- entire input before deciding whether or not it fails. -- --
--   >>> ByteString.unpack (utf8 # "☃")
--   [226,152,131]
--   
utf8 :: Prism' ByteString Text module ByteString.Partial -- | 'foldl1\'' is like foldl1, but strict in the accumulator. An -- exception will be thrown in the case of an empty ByteString. foldl1' :: Word8 -> Word8 -> Word8 -> ByteString -> Word8 -- | foldr1 is a variant of foldr that has no starting value -- argument, and thus must be applied to non-empty ByteStrings An -- exception will be thrown in the case of an empty ByteString. foldr1 :: Word8 -> Word8 -> Word8 -> ByteString -> Word8 -- | 'foldr1\'' is a variant of foldr1, but is strict in the -- accumulator. foldr1' :: Word8 -> Word8 -> Word8 -> ByteString -> Word8 -- | O(1) Extract the first element of a ByteString, which must be -- non-empty. An exception will be thrown in the case of an empty -- ByteString. head :: ByteString -> Word8 -- | O(1) Return all the elements of a ByteString except the -- last one. An exception will be thrown in the case of an empty -- ByteString. init :: ByteString -> ByteString -- | O(1) Extract the last element of a ByteString, which must be -- finite and non-empty. An exception will be thrown in the case of an -- empty ByteString. last :: ByteString -> Word8 -- | O(n) maximum returns the maximum value from a -- ByteString This function will fuse. An exception will be thrown -- in the case of an empty ByteString. maximum :: ByteString -> Word8 -- | O(n) minimum returns the minimum value from a -- ByteString This function will fuse. An exception will be thrown -- in the case of an empty ByteString. minimum :: ByteString -> Word8 -- | O(1) Extract the elements after the head of a ByteString, which -- must be non-empty. An exception will be thrown in the case of an empty -- ByteString. tail :: ByteString -> ByteString module ByteString.Short -- | A compact representation of a Word8 vector. -- -- It has a lower memory overhead than a ByteString and and does -- not contribute to heap fragmentation. It can be converted to or from a -- ByteString (at the cost of copying the string data). It -- supports very few other operations. -- -- It is suitable for use as an internal representation for code that -- needs to keep many short strings in memory, but it should not -- be used as an interchange type. That is, it should not generally be -- used in public APIs. The ByteString type is usually more -- suitable for use in interfaces; it is more flexible and it supports a -- wide range of operations. data ShortByteString -- | O(n). Convert a ByteString into a -- ShortByteString. -- -- This makes a copy, so does not retain the input string. toShort :: ByteString -> ShortByteString -- | O(n). Convert a ShortByteString into a -- ByteString. fromShort :: ShortByteString -> ByteString -- | O(n). Convert a list into a ShortByteString pack :: [Word8] -> ShortByteString -- | O(n). Convert a ShortByteString into a list. unpack :: ShortByteString -> [Word8] -- | O(1). The empty ShortByteString. empty :: ShortByteString -- | O(1) Test whether a ShortByteString is empty. null :: ShortByteString -> Bool -- | O(1) The length of a ShortByteString. length :: ShortByteString -> Int module ByteString.Short.Partial -- | O(1) ShortByteString index (subscript) operator, -- starting from 0. index :: ShortByteString -> Int -> Word8 module ByteString.Utf8 -- | Split a string into two parts: the first is the longest prefix that -- contains only characters that do not satisfy the predicate; the second -- part is the rest of the string. Invalid characters are passed as -- '\0xFFFD' to the predicate. break :: Char -> Bool -> ByteString -> (ByteString, ByteString) -- | drop n s returns the s without its first n -- characters. If s has less than n characters, then we -- return an empty string. drop :: Int -> ByteString -> ByteString -- | Traverse a bytestring (left biased). This function is strict in the -- accumulator. foldl :: () => a -> Char -> a -> a -> ByteString -> a -- | Traverse a bytestring (right biased). foldr :: () => Char -> a -> a -> a -> ByteString -> a -- | Converts a Haskell string into a UTF8 encoded bytestring. fromString :: String -> ByteString -- | Counts the number of characters encoded in the bytestring. Note that -- this includes replacement characters. length :: ByteString -> Int -- | Split a string into two parts: the first is the longest prefix that -- contains only characters that satisfy the predicate; the second part -- is the rest of the string. Invalid characters are passed as '\0xFFFD' -- to the predicate. span :: Char -> Bool -> ByteString -> (ByteString, ByteString) -- | Split after a given number of characters. Negative values are treated -- as if they are 0. splitAt :: Int -> ByteString -> (ByteString, ByteString) -- | take n s returns the first n characters of -- s. If s has less than n characters, then we -- return the whole of s. take :: Int -> ByteString -> ByteString -- | Convert a UTF8 encoded bytestring into a Haskell string. Invalid -- characters are replaced with '\xFFFD'. toString :: ByteString -> String -- | Get the first character of a byte string, if any. Malformed characters -- are replaced by '\0xFFFD'. uncons :: ByteString -> Maybe (Char, ByteString) -- | Encode/Decode a strict Text to/from strict ByteString, -- via UTF-8. -- --
--   >>> utf8 # "☃"
--   "\226\152\131"
--   
utf8 :: Prism' ByteString Text module CaseInsensitive module Category -- | A class for categories. Instances should satisfy the laws -- --
--   f . id  =  f  -- (right identity)
--   id . f  =  f  -- (left identity)
--   f . (g . h)  =  (f . g) . h  -- (associativity)
--   
class Category (cat :: k -> k -> *) -- | the identity morphism id :: Category cat => cat a a -- | morphism composition (.) :: Category cat => cat b c -> cat a b -> cat a c -- | Left-to-right composition (>>>) :: Category cat => cat a b -> cat b c -> cat a c infixr 1 >>> -- | Right-to-left composition (<<<) :: Category cat => cat b c -> cat a b -> cat a c infixr 1 <<< module 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 -- | Selects control characters, which are the non-printing characters of -- the Latin-1 subset of Unicode. isControl :: Char -> Bool -- | Returns True for any Unicode space character, and the control -- characters \t, \n, \r, \f, -- \v. isSpace :: Char -> Bool -- | Selects lower-case alphabetic Unicode characters (letters). isLower :: Char -> Bool -- | Selects upper-case or title-case alphabetic Unicode characters -- (letters). Title case is used by a small number of letter ligatures -- like the single-character form of Lj. isUpper :: Char -> Bool -- | Selects alphabetic Unicode characters (lower-case, upper-case and -- title-case letters, plus letters of caseless scripts and modifiers -- letters). This function is equivalent to isLetter. isAlpha :: Char -> Bool -- | Selects alphabetic or numeric digit Unicode characters. -- -- Note that numeric digits outside the ASCII range are selected by this -- function but not by isDigit. Such digits may be part of -- identifiers but are not used by the printer and reader to represent -- numbers. isAlphaNum :: Char -> Bool -- | Selects printable Unicode characters (letters, numbers, marks, -- punctuation, symbols and spaces). isPrint :: Char -> Bool -- | Selects ASCII digits, i.e. '0'..'9'. isDigit :: Char -> Bool -- | Selects ASCII octal digits, i.e. '0'..'7'. isOctDigit :: Char -> Bool -- | Selects ASCII hexadecimal digits, i.e. '0'..'9', -- 'a'..'f', 'A'..'F'. isHexDigit :: Char -> Bool -- | Selects alphabetic Unicode characters (lower-case, upper-case and -- title-case letters, plus letters of caseless scripts and modifiers -- letters). This function is equivalent to isAlpha. -- -- This function returns True if its argument has one of the -- following GeneralCategorys, or False otherwise: -- -- -- -- These classes are defined in the Unicode Character Database, -- part of the Unicode standard. The same document defines what is and is -- not a "Letter". -- --

Examples

-- -- Basic usage: -- --
--   >>> isLetter 'a'
--   True
--   
--   >>> isLetter 'A'
--   True
--   
--   >>> isLetter 'λ'
--   True
--   
--   >>> isLetter '0'
--   False
--   
--   >>> isLetter '%'
--   False
--   
--   >>> isLetter '♥'
--   False
--   
--   >>> isLetter '\31'
--   False
--   
-- -- Ensure that isLetter and isAlpha are equivalent. -- --
--   >>> let chars = [(chr 0)..]
--   
--   >>> let letters = map isLetter chars
--   
--   >>> let alphas = map isAlpha chars
--   
--   >>> letters == alphas
--   True
--   
isLetter :: Char -> Bool -- | Selects Unicode mark characters, for example accents and the like, -- which combine with preceding characters. -- -- This function returns True if its argument has one of the -- following GeneralCategorys, or False otherwise: -- -- -- -- These classes are defined in the Unicode Character Database, -- part of the Unicode standard. The same document defines what is and is -- not a "Mark". -- --

Examples

-- -- Basic usage: -- --
--   >>> isMark 'a'
--   False
--   
--   >>> isMark '0'
--   False
--   
-- -- Combining marks such as accent characters usually need to follow -- another character before they become printable: -- --
--   >>> map isMark "ò"
--   [False,True]
--   
-- -- Puns are not necessarily supported: -- --
--   >>> isMark '✓'
--   False
--   
isMark :: Char -> Bool -- | Selects Unicode numeric characters, including digits from various -- scripts, Roman numerals, et cetera. -- -- This function returns True if its argument has one of the -- following GeneralCategorys, or False otherwise: -- -- -- -- These classes are defined in the Unicode Character Database, -- part of the Unicode standard. The same document defines what is and is -- not a "Number". -- --

Examples

-- -- Basic usage: -- --
--   >>> isNumber 'a'
--   False
--   
--   >>> isNumber '%'
--   False
--   
--   >>> isNumber '3'
--   True
--   
-- -- ASCII '0' through '9' are all numbers: -- --
--   >>> and $ map isNumber ['0'..'9']
--   True
--   
-- -- Unicode Roman numerals are "numbers" as well: -- --
--   >>> isNumber 'Ⅸ'
--   True
--   
isNumber :: Char -> Bool -- | Selects Unicode punctuation characters, including various kinds of -- connectors, brackets and quotes. -- -- This function returns True if its argument has one of the -- following GeneralCategorys, or False otherwise: -- -- -- -- These classes are defined in the Unicode Character Database, -- part of the Unicode standard. The same document defines what is and is -- not a "Punctuation". -- --

Examples

-- -- Basic usage: -- --
--   >>> isPunctuation 'a'
--   False
--   
--   >>> isPunctuation '7'
--   False
--   
--   >>> isPunctuation '♥'
--   False
--   
--   >>> isPunctuation '"'
--   True
--   
--   >>> isPunctuation '?'
--   True
--   
--   >>> isPunctuation '—'
--   True
--   
isPunctuation :: Char -> Bool -- | Selects Unicode symbol characters, including mathematical and currency -- symbols. -- -- This function returns True if its argument has one of the -- following GeneralCategorys, or False otherwise: -- -- -- -- These classes are defined in the Unicode Character Database, -- part of the Unicode standard. The same document defines what is and is -- not a "Symbol". -- --

Examples

-- -- Basic usage: -- --
--   >>> isSymbol 'a'
--   False
--   
--   >>> isSymbol '6'
--   False
--   
--   >>> isSymbol '='
--   True
--   
-- -- The definition of "math symbol" may be a little counter-intuitive -- depending on one's background: -- --
--   >>> isSymbol '+'
--   True
--   
--   >>> isSymbol '-'
--   False
--   
isSymbol :: Char -> Bool -- | Selects Unicode space and separator characters. -- -- This function returns True if its argument has one of the -- following GeneralCategorys, or False otherwise: -- -- -- -- These classes are defined in the Unicode Character Database, -- part of the Unicode standard. The same document defines what is and is -- not a "Separator". -- --

Examples

-- -- Basic usage: -- --
--   >>> isSeparator 'a'
--   False
--   
--   >>> isSeparator '6'
--   False
--   
--   >>> isSeparator ' '
--   True
--   
-- -- Warning: newlines and tab characters are not considered separators. -- --
--   >>> isSeparator '\n'
--   False
--   
--   >>> isSeparator '\t'
--   False
--   
-- -- But some more exotic characters are (like HTML's &nbsp;): -- --
--   >>> isSeparator '\160'
--   True
--   
isSeparator :: Char -> Bool -- | Selects the first 128 characters of the Unicode character set, -- corresponding to the ASCII character set. isAscii :: Char -> Bool -- | Selects ASCII upper-case letters, i.e. characters satisfying both -- isAscii and isUpper. isAsciiUpper :: Char -> Bool -- | Selects ASCII lower-case letters, i.e. characters satisfying both -- isAscii and isLower. isAsciiLower :: Char -> Bool -- | Selects the first 256 characters of the Unicode character set, -- corresponding to the ISO 8859-1 (Latin-1) character set. isLatin1 :: Char -> Bool -- | Unicode General Categories (column 2 of the UnicodeData table) in the -- order they are listed in the Unicode standard (the Unicode Character -- Database, in particular). -- --

Examples

-- -- Basic usage: -- --
--   >>> :t OtherLetter
--   OtherLetter :: GeneralCategory
--   
-- -- Eq instance: -- --
--   >>> UppercaseLetter == UppercaseLetter
--   True
--   
--   >>> UppercaseLetter == LowercaseLetter
--   False
--   
-- -- Ord instance: -- --
--   >>> NonSpacingMark <= MathSymbol
--   True
--   
-- -- Enum instance: -- --
--   >>> enumFromTo ModifierLetter SpacingCombiningMark
--   [ModifierLetter,OtherLetter,NonSpacingMark,SpacingCombiningMark]
--   
-- -- Read instance: -- --
--   >>> read "DashPunctuation" :: GeneralCategory
--   DashPunctuation
--   
--   >>> read "17" :: GeneralCategory
--   *** Exception: Prelude.read: no parse
--   
-- -- Show instance: -- --
--   >>> show EnclosingMark
--   "EnclosingMark"
--   
-- -- Bounded instance: -- --
--   >>> minBound :: GeneralCategory
--   UppercaseLetter
--   
--   >>> maxBound :: GeneralCategory
--   NotAssigned
--   
-- -- Ix instance: -- --
--   >>> import Data.Ix ( index )
--   
--   >>> index (OtherLetter,Control) FinalQuote
--   12
--   
--   >>> index (OtherLetter,Control) Format
--   *** Exception: Error in array index
--   
data GeneralCategory -- | Lu: Letter, Uppercase UppercaseLetter :: GeneralCategory -- | Ll: Letter, Lowercase LowercaseLetter :: GeneralCategory -- | Lt: Letter, Titlecase TitlecaseLetter :: GeneralCategory -- | Lm: Letter, Modifier ModifierLetter :: GeneralCategory -- | Lo: Letter, Other OtherLetter :: GeneralCategory -- | Mn: Mark, Non-Spacing NonSpacingMark :: GeneralCategory -- | Mc: Mark, Spacing Combining SpacingCombiningMark :: GeneralCategory -- | Me: Mark, Enclosing EnclosingMark :: GeneralCategory -- | Nd: Number, Decimal DecimalNumber :: GeneralCategory -- | Nl: Number, Letter LetterNumber :: GeneralCategory -- | No: Number, Other OtherNumber :: GeneralCategory -- | Pc: Punctuation, Connector ConnectorPunctuation :: GeneralCategory -- | Pd: Punctuation, Dash DashPunctuation :: GeneralCategory -- | Ps: Punctuation, Open OpenPunctuation :: GeneralCategory -- | Pe: Punctuation, Close ClosePunctuation :: GeneralCategory -- | Pi: Punctuation, Initial quote InitialQuote :: GeneralCategory -- | Pf: Punctuation, Final quote FinalQuote :: GeneralCategory -- | Po: Punctuation, Other OtherPunctuation :: GeneralCategory -- | Sm: Symbol, Math MathSymbol :: GeneralCategory -- | Sc: Symbol, Currency CurrencySymbol :: GeneralCategory -- | Sk: Symbol, Modifier ModifierSymbol :: GeneralCategory -- | So: Symbol, Other OtherSymbol :: GeneralCategory -- | Zs: Separator, Space Space :: GeneralCategory -- | Zl: Separator, Line LineSeparator :: GeneralCategory -- | Zp: Separator, Paragraph ParagraphSeparator :: GeneralCategory -- | Cc: Other, Control Control :: GeneralCategory -- | Cf: Other, Format Format :: GeneralCategory -- | Cs: Other, Surrogate Surrogate :: GeneralCategory -- | Co: Other, Private Use PrivateUse :: GeneralCategory -- | Cn: Other, Not Assigned NotAssigned :: GeneralCategory -- | The Unicode general category of the character. This relies on the -- Enum instance of GeneralCategory, which must remain in -- the same order as the categories are presented in the Unicode -- standard. -- --

Examples

-- -- Basic usage: -- --
--   >>> generalCategory 'a'
--   LowercaseLetter
--   
--   >>> generalCategory 'A'
--   UppercaseLetter
--   
--   >>> generalCategory '0'
--   DecimalNumber
--   
--   >>> generalCategory '%'
--   OtherPunctuation
--   
--   >>> generalCategory '♥'
--   OtherSymbol
--   
--   >>> generalCategory '\31'
--   Control
--   
--   >>> generalCategory ' '
--   Space
--   
generalCategory :: Char -> GeneralCategory -- | Convert a letter to the corresponding upper-case letter, if any. Any -- other character is returned unchanged. toUpper :: Char -> Char -- | Convert a letter to the corresponding lower-case letter, if any. Any -- other character is returned unchanged. toLower :: Char -> Char -- | Convert a letter to the corresponding title-case or upper-case letter, -- if any. (Title case differs from upper case only for a small number of -- ligature letters.) Any other character is returned unchanged. toTitle :: Char -> Char -- | The fromEnum method restricted to the type Char. ord :: Char -> Int -- | utility function converting a Char to a show function that -- simply prepends the character unchanged. showChar :: Char -> ShowS -- | Convert a character to a string using only printable characters, using -- Haskell source-language escape conventions. For example: -- --
--   showLitChar '\n' s  =  "\\n" ++ s
--   
showLitChar :: Char -> ShowS -- | Read a string representation of a character, using Haskell -- source-language escape conventions. For example: -- --
--   lexLitChar  "\\nHello"  =  [("\\n", "Hello")]
--   
lexLitChar :: ReadS String -- | Read a string representation of a character, using Haskell -- source-language escape conventions, and convert it to the character -- that it encodes. For example: -- --
--   readLitChar "\\nHello"  =  [('\n', "Hello")]
--   
readLitChar :: ReadS Char module Char.Partial -- | Convert a single digit Char to the corresponding Int. -- This function fails unless its argument satisfies isHexDigit, -- but recognises both upper- and lower-case hexadecimal digits (that is, -- '0'..'9', 'a'..'f', -- 'A'..'F'). -- --

Examples

-- -- Characters '0' through '9' are converted properly to -- 0..9: -- --
--   >>> map digitToInt ['0'..'9']
--   [0,1,2,3,4,5,6,7,8,9]
--   
-- -- Both upper- and lower-case 'A' through 'F' are -- converted as well, to 10..15. -- --
--   >>> map digitToInt ['a'..'f']
--   [10,11,12,13,14,15]
--   
--   >>> map digitToInt ['A'..'F']
--   [10,11,12,13,14,15]
--   
-- -- Anything else throws an exception: -- --
--   >>> digitToInt 'G'
--   *** Exception: Char.digitToInt: not a digit 'G'
--   
--   >>> digitToInt '♥'
--   *** Exception: Char.digitToInt: not a digit '\9829'
--   
digitToInt :: Char -> Int -- | Convert an Int in the range 0..15 to the -- corresponding single digit Char. This function fails on other -- inputs, and generates lower-case hexadecimal digits. intToDigit :: Int -> Char -- | The toEnum method restricted to the type Char. chr :: Int -> Char module Clock -- | Return monotonic time in seconds, since some unspecified starting -- point getMonotonicTime :: IO Double -- | Return monotonic time in nanoseconds, since some unspecified starting -- point getMonotonicTimeNSec :: IO Word64 -- | Computation getCPUTime returns the number of picoseconds CPU -- time used by the current program. The precision of this result is -- implementation-dependent. getCPUTime :: IO Integer -- | The cpuTimePrecision constant is the smallest measurable -- difference in CPU time that the implementation can record, and is -- given as an integral number of picoseconds. cpuTimePrecision :: Integer module Coerce -- | Coercible is a two-parameter class that has instances for -- types a and b if the compiler can infer that they -- have the same representation. This class does not have regular -- instances; instead they are created on-the-fly during type-checking. -- Trying to manually declare an instance of Coercible is an -- error. -- -- Nevertheless one can pretend that the following three kinds of -- instances exist. First, as a trivial base-case: -- --
--   instance Coercible a a
--   
-- -- Furthermore, for every type constructor there is an instance that -- allows to coerce under the type constructor. For example, let -- D be a prototypical type constructor (data or -- newtype) with three type arguments, which have roles -- nominal, representational resp. phantom. -- Then there is an instance of the form -- --
--   instance Coercible b b' => Coercible (D a b c) (D a b' c')
--   
-- -- Note that the nominal type arguments are equal, the -- representational type arguments can differ, but need to have -- a Coercible instance themself, and the phantom type -- arguments can be changed arbitrarily. -- -- The third kind of instance exists for every newtype NT = MkNT -- T and comes in two variants, namely -- --
--   instance Coercible a T => Coercible a NT
--   
-- --
--   instance Coercible T b => Coercible NT b
--   
-- -- This instance is only usable if the constructor MkNT is in -- scope. -- -- If, as a library author of a type constructor like Set a, you -- want to prevent a user of your module to write coerce :: Set T -- -> Set NT, you need to set the role of Set's type -- parameter to nominal, by writing -- --
--   type role Set nominal
--   
-- -- For more details about this feature, please refer to Safe -- Coercions by Joachim Breitner, Richard A. Eisenberg, Simon Peyton -- Jones and Stephanie Weirich. class a ~R# b => Coercible (a :: k0) (b :: k0) -- | The function coerce allows you to safely convert between -- values of types that have the same representation with no run-time -- overhead. In the simplest case you can use it instead of a newtype -- constructor, to go from the newtype's concrete type to the abstract -- type. But it also works in more complicated settings, e.g. converting -- a list of newtypes to a list of concrete types. coerce :: Coercible a b => a -> b -- | Representational equality. If Coercion a b is inhabited by -- some terminating value, then the type a has the same -- underlying representation as the type b. -- -- To use this equality in practice, pattern-match on the Coercion a -- b to get out the Coercible a b instance, and then use -- coerce to apply it. data Coercion (a :: k) (b :: k) :: forall k. () => k -> k -> * [Coercion] :: Coercion a b -- | Type-safe cast, using representational equality coerceWith :: () => Coercion a b -> a -> b -- | Generalized form of type-safe cast using representational equality gcoerceWith :: () => Coercion a b -> Coercible a b -> r -> r -- | Symmetry of representational equality sym :: () => Coercion a b -> Coercion b a -- | Transitivity of representational equality trans :: () => Coercion a b -> Coercion b c -> Coercion a c -- | Convert propositional (nominal) equality to representational equality repr :: () => a :~: b -> Coercion a b -- | This class contains types where you can learn the equality of two -- types from information contained in terms. Typically, only -- singleton types should inhabit this class. class TestCoercion (f :: k -> *) -- | Conditionally prove the representational equality of a and -- b. testCoercion :: TestCoercion f => f a -> f b -> Maybe Coercion a b module Coerce.Unsafe unsafeCoerce :: () => a -> b module Comonad -- | There are two ways to define a comonad: -- -- I. Provide definitions for extract and extend satisfying -- these laws: -- --
--   extend extract      = id
--   extract . extend f  = f
--   extend f . extend g = extend (f . extend g)
--   
-- -- In this case, you may simply set fmap = liftW. -- -- These laws are directly analogous to the laws for monads and perhaps -- can be made clearer by viewing them as laws stating that Cokleisli -- composition must be associative, and has extract for a unit: -- --
--   f =>= extract   = f
--   extract =>= f   = f
--   (f =>= g) =>= h = f =>= (g =>= h)
--   
-- -- II. Alternately, you may choose to provide definitions for -- fmap, extract, and duplicate satisfying these -- laws: -- --
--   extract . duplicate      = id
--   fmap extract . duplicate = id
--   duplicate . duplicate    = fmap duplicate . duplicate
--   
-- -- In this case you may not rely on the ability to define fmap in -- terms of liftW. -- -- You may of course, choose to define both duplicate and -- extend. In that case you must also satisfy these laws: -- --
--   extend f  = fmap f . duplicate
--   duplicate = extend id
--   fmap f    = extend (f . extract)
--   
-- -- These are the default definitions of extend and -- duplicate and the definition of liftW respectively. class Functor w => Comonad (w :: * -> *) -- |
--   extract . fmap f = f . extract
--   
extract :: Comonad w => w a -> a -- |
--   duplicate = extend id
--   fmap (fmap f) . duplicate = duplicate . fmap f
--   
duplicate :: Comonad w => w a -> w w a -- |
--   extend f = fmap f . duplicate
--   
extend :: Comonad w => w a -> b -> w a -> w b -- | Comonadic fixed point à la David Menendez wfix :: Comonad w => w w a -> a -> a -- | Comonadic fixed point à la Dominic Orchard cfix :: Comonad w => w a -> a -> w a -- | Comonadic fixed point à la Kenneth Foner: -- -- This is the evaluate function from his "Getting a Quick -- Fix on Comonads" talk. kfix :: ComonadApply w => w w a -> a -> w a -- | Left-to-right Cokleisli composition (=>=) :: Comonad w => w a -> b -> w b -> c -> w a -> c infixr 1 =>= -- | Right-to-left Cokleisli composition (=<=) :: Comonad w => w b -> c -> w a -> b -> w a -> c infixr 1 =<= -- | extend in operator form (<<=) :: Comonad w => w a -> b -> w a -> w b infixr 1 <<= -- | extend with the arguments swapped. Dual to >>= for -- a Monad. (=>>) :: Comonad w => w a -> w a -> b -> w b infixl 1 =>> -- | ComonadApply is to Comonad like Applicative -- is to Monad. -- -- Mathematically, it is a strong lax symmetric semi-monoidal comonad on -- the category Hask of Haskell types. That it to say that -- w is a strong lax symmetric semi-monoidal functor on Hask, -- where both extract and duplicate are symmetric monoidal -- natural transformations. -- -- Laws: -- --
--   (.) <$> u <@> v <@> w = u <@> (v <@> w)
--   extract (p <@> q) = extract p (extract q)
--   duplicate (p <@> q) = (<@>) <$> duplicate p <@> duplicate q
--   
-- -- If our type is both a ComonadApply and Applicative we -- further require -- --
--   (<*>) = (<@>)
--   
-- -- Finally, if you choose to define (<@) and (@>), -- the results of your definitions should match the following laws: -- --
--   a @> b = const id <$> a <@> b
--   a <@ b = const <$> a <@> b
--   
class Comonad w => ComonadApply (w :: * -> *) (<@>) :: ComonadApply w => w a -> b -> w a -> w b (@>) :: ComonadApply w => w a -> w b -> w b (<@) :: ComonadApply w => w a -> w b -> w a -- | A variant of <@> with the arguments reversed. (<@@>) :: ComonadApply w => w a -> w a -> b -> w b infixl 4 <@@> -- | Lift a binary function into a Comonad with zipping liftW2 :: ComonadApply w => a -> b -> c -> w a -> w b -> w c -- | Lift a ternary function into a Comonad with zipping liftW3 :: ComonadApply w => a -> b -> c -> d -> w a -> w b -> w c -> w d -- | The Cokleisli Arrows of a given Comonad newtype Cokleisli (w :: k -> *) (a :: k) b :: forall k. () => k -> * -> k -> * -> * Cokleisli :: w a -> b -> Cokleisli b [runCokleisli] :: Cokleisli b -> w a -> b module CompactRegion -- | A Compact contains fully evaluated, pure, immutable data. -- -- Compact serves two purposes: -- -- -- -- Compacts are self-contained, so compacting data involves copying it; -- if you have data that lives in two Compacts, each will have a -- separate copy of the data. -- -- The cost of compaction is similar to the cost of GC for the same data, -- but it is performed only once. However, because "GHC.Compact.compact" -- does not stop-the-world, retaining internal sharing during the -- compaction process is very costly. The user can choose whether to -- compact or compactWithSharing. -- -- When you have a Compact a, you can get a pointer to -- the actual object in the region using "GHC.Compact.getCompact". The -- Compact type serves as handle on the region itself; you can use -- this handle to add data to a specific Compact with -- compactAdd or compactAddWithSharing (giving you a new -- handle which corresponds to the same compact region, but points to the -- newly added object in the region). At the moment, due to technical -- reasons, it's not possible to get the Compact a if you -- only have an a, so make sure you hold on to the handle as -- necessary. -- -- Data in a compact doesn't ever move, so compacting data is also a way -- to pin arbitrary data structures in memory. -- -- There are some limitations on what can be compacted: -- -- -- -- If compaction encounters any of the above, a CompactionFailed -- exception will be thrown by the compaction operation. data Compact a -- | Compact a value. O(size of unshared data) -- -- If the structure contains any internal sharing, the shared data will -- be duplicated during the compaction process. This will not terminate -- if the structure contains cycles (use compactWithSharing -- instead). -- -- The object in question must not contain any functions or data with -- mutable pointers; if it does, compact will raise an exception. -- In the future, we may add a type class which will help statically -- check if this is the case or not. compact :: () => a -> IO Compact a -- | Compact a value, retaining any internal sharing and cycles. O(size -- of data) -- -- This is typically about 10x slower than compact, because it -- works by maintaining a hash table mapping uncompacted objects to -- compacted objects. -- -- The object in question must not contain any functions or data with -- mutable pointers; if it does, compact will raise an exception. -- In the future, we may add a type class which will help statically -- check if this is the case or not. compactWithSharing :: () => a -> IO Compact a -- | Add a value to an existing Compact. This will help you avoid -- copying when the value contains pointers into the compact region, but -- remember that after compaction this value will only be deallocated -- with the entire compact region. -- -- Behaves exactly like compact with respect to sharing and what -- data it accepts. compactAdd :: () => Compact b -> a -> IO Compact a -- | Add a value to an existing Compact, like compactAdd, but -- behaving exactly like compactWithSharing with respect to -- sharing and what data it accepts. compactAddWithSharing :: () => Compact b -> a -> IO Compact a -- | Transfer a into a new compact region, with a preallocated -- size, possibly preserving sharing or not. If you know how big the data -- structure in question is, you can save time by picking an appropriate -- block size for the compact region. compactSized :: () => Int -> Bool -> a -> IO Compact a -- | Retrieve a direct pointer to the value pointed at by a Compact -- reference. If you have used compactAdd, there may be multiple -- Compact references into the same compact region. Upholds the -- property: -- --
--   inCompact c (getCompact c) == True
--   
getCompact :: () => Compact a -> a -- | Check if the second argument is inside the passed Compact. inCompact :: () => Compact b -> a -> IO Bool -- | Check if the argument is in any Compact. If true, the value in -- question is also fully evaluated, since any value in a compact region -- must be fully evaluated. isCompact :: () => a -> IO Bool -- | Returns the size in bytes of the compact region. compactSize :: () => Compact a -> IO Word -- | Compaction found an object that cannot be compacted. Functions cannot -- be compacted, nor can mutable objects or pinned objects. See -- compact. newtype CompactionFailed CompactionFailed :: String -> CompactionFailed module Concurrency.Chan -- | Create a new channel of the passed size, returning its write and read -- ends. -- -- The passed integer bounds will be rounded up to the next highest power -- of two, n. The queue may grow up to size 2*n (see -- writeChan for details), and the resulting chan pair requires -- O(n) space. newChan :: () => Int -> IO (InChan a, OutChan a) -- | The write end of a channel created with newChan. data InChan a -- | The read end of a channel created with newChan. data OutChan a -- | Read an element from the chan, blocking if the chan is empty. -- -- Note re. exceptions: When an async exception is raised during a -- readChan the message that the read would have returned is -- likely to be lost, even when the read is known to be blocked on an -- empty queue. If you need to handle this scenario, you can use -- readChanOnException. readChan :: () => OutChan a -> IO a -- | Like readChan but allows recovery of the queue element which -- would have been read, in the case that an async exception is raised -- during the read. To be precise exceptions are raised, and the handler -- run, only when readChanOnException is blocking. -- -- The second argument is a handler that takes a blocking IO action -- returning the element, and performs some recovery action. When the -- handler is called, the passed IO a is the only way to access -- the element. readChanOnException :: () => OutChan a -> IO a -> IO () -> IO a -- | Returns immediately with: -- -- -- -- Note re. exceptions: When an async exception is raised during a -- tryReadChan the message that the read would have returned is -- likely to be lost, just as it would be when raised directly after this -- function returns. tryReadChan :: () => OutChan a -> IO (Element a, IO a) -- | An IO action that returns a particular enqueued element when -- and if it becomes available. -- -- Each Element corresponds to a particular enqueued element, -- i.e. a returned Element always offers the only means to -- access one particular enqueued item. The value returned by -- tryRead moves monotonically from Nothing to Just -- a when and if an element becomes available, and is idempotent at -- that point. newtype Element a Element :: IO Maybe a -> Element a [tryRead] :: Element a -> IO Maybe a -- | Return the estimated length of a bounded queue -- -- The more concurrent writes and reads that are happening, the more -- inaccurate the estimate of the chan's size is likely to be. estimatedLength :: () => InChan a -> IO Int -- | Write a value to the channel. If the chan is full this will block. -- -- To be precise this may block when the number of elements in the -- queue >= size, and will certainly block when >= -- size*2, where size is the argument passed to -- newChan, rounded up to the next highest power of two. -- -- Note re. exceptions: In the case that an async exception is -- raised while blocking here, the write will nonetheless succeed. When -- not blocking, exceptions are masked. Thus writes always succeed once -- writeChan is entered. writeChan :: () => InChan a -> a -> IO () -- | Try to write a value to the channel, aborting if the write is likely -- to exceed the bounds, returning a Bool indicating whether the -- write was successful. -- -- This function never blocks, but may occasionally write successfully to -- a queue that is already "full". Unlike writeChan this function -- treats the requested bounds (raised to nearest power of two) strictly, -- rather than using the n .. n*2 range. The more concurrent -- writes and reads that are happening, the more inaccurate the estimate -- of the chan's size is likely to be. tryWriteChan :: () => InChan a -> a -> IO Bool -- | Duplicate a chan: the returned OutChan begins empty, but data -- written to the argument InChan from then on will be available -- from both the original OutChan and the one returned here, -- creating a kind of broadcast channel. -- -- Writers will be blocked only when the fastest reader falls behind the -- bounds; slower readers of duplicated OutChan may fall -- arbitrarily behind. dupChan :: () => InChan a -> IO OutChan a module Concurrency.Counter -- | The type of mutable atomic counters. data AtomicCounter -- | Create a new counter initialized to the given value. newCounter :: Int -> IO AtomicCounter -- | Increment the counter by a given amount. Returns the value AFTER the -- increment (in contrast with the behavior of the underlying instruction -- on architectures like x86.) -- -- Note that UNLIKE with boxed implementations of counters, where -- increment is based on CAS, this increment is O(1). -- Fetch-and-add does not require a retry loop like CAS. incrCounter :: Int -> AtomicCounter -> IO Int -- | An alternate version for when you don't care about the old value. incrCounter_ :: Int -> AtomicCounter -> IO () -- | Equivalent to readCounterForCAS followed by peekCTicket. readCounter :: AtomicCounter -> IO Int -- | Compare and swap for the counter ADT. Similar behavior to -- casIORef, in particular, in both success and failure cases it -- returns a ticket that you should use for the next attempt. (That is, -- in the success case, it actually returns the new value that you -- provided as input, but in ticket form.) casCounter :: AtomicCounter -> CTicket -> Int -> IO (Bool, CTicket) module Concurrency.IORef -- | A mutable variable in the IO monad data IORef a -- | Lifted newIORef. newIORef :: MonadIO m => a -> m IORef a -- | Lifted readIORef. readIORef :: MonadIO m => IORef a -> m a -- | Lifted writeIORef. writeIORef :: MonadIO m => IORef a -> a -> m () -- | Evaluates the value before calling writeIORef. writeIORef' :: () => IORef a -> a -> IO () -- | Lifted modifyIORef. modifyIORef :: MonadIO m => IORef a -> a -> a -> m () -- | Lifted modifyIORef'. modifyIORef' :: MonadIO m => IORef a -> a -> a -> m () -- | Lifted atomicModifyIORef. atomicModifyIORef :: MonadIO m => IORef a -> a -> (a, b) -> m b -- | Lifted atomicModifyIORef'. atomicModifyIORef' :: MonadIO m => IORef a -> a -> (a, b) -> m b -- | Lifted atomicWriteIORef. atomicWriteIORef :: MonadIO m => IORef a -> a -> m () -- | Evaluates the value before calling atomicWriteIORef. atomicWriteIORef' :: () => IORef a -> a -> IO () -- | Unlifted mkWeakIORef. mkWeakIORef :: MonadUnliftIO m => IORef a -> m () -> m Weak IORef a -- | When performing compare-and-swaps, the ticket encapsulates -- proof that a thread observed a specific previous value of a mutable -- variable. It is provided in lieu of the "old" value to -- compare-and-swap. -- -- Design note: Tickets exist to hide objects from the GHC -- compiler, which can normally perform many optimizations that change -- pointer equality. A Ticket, on the other hand, is a first-class object -- that can be handled by the user, but will not have its pointer -- identity changed by compiler optimizations (but will of course, change -- addresses during garbage collection). data Ticket a -- | A ticket contains or can get the usable Haskell value. This function -- does just that. peekTicket :: () => Ticket a -> a -- | Ordinary processor load instruction (non-atomic, not implying any -- memory barriers). -- -- The difference between this function and readIORef, is that it -- returns a ticket, for use in future compare-and-swap -- operations. readForCAS :: () => IORef a -> IO Ticket a -- | Performs a machine-level compare and swap (CAS) operation on an -- IORef. Returns a tuple containing a Bool which is -- True when a swap is performed, along with the most -- current value from the IORef. Note that this differs -- from the more common CAS behavior, which is to return the old -- value before the CAS occured. -- -- The reason for the difference is the ticket API. This function always -- returns the ticket that you should use in your next CAS attempt. In -- case of success, this ticket corresponds to the new value -- which you yourself installed in the IORef, whereas in the case -- of failure it represents the preexisting value currently in the IORef. -- -- Note "compare" here means pointer equality in the sense of -- reallyUnsafePtrEquality#. However, the ticket API absolves the -- user of this module from needing to worry about the pointer equality -- of their values, which in general requires reasoning about the details -- of the Haskell implementation (GHC). -- -- By convention this function is strict in the "new" value argument. -- This isn't absolutely necesary, but we think it's a bad habit to use -- unevaluated thunks in this context. casIORef :: () => IORef a -> Ticket a -> a -> IO (Bool, Ticket a) -- | This variant takes two tickets, i.e. the new value is a -- ticket rather than an arbitrary, lifted, Haskell value. casIORef2 :: () => IORef a -> Ticket a -> Ticket a -> IO (Bool, Ticket a) -- | A drop-in replacement for atomicModifyIORef that optimistically -- attempts to compute the new value and CAS it into place without -- introducing new thunks or locking anything. Note that this is more -- STRICT than its standard counterpart and will only place evaluated -- (WHNF) values in the IORef. -- -- The upside is that sometimes we see a performance benefit. The -- downside is that this version is speculative -- when it retries, it -- must reexecute the compution. atomicModifyIORefCAS :: () => IORef a -> a -> (a, b) -> IO b -- | A simpler version that modifies the state but does not return -- anything. atomicModifyIORefCAS_ :: () => IORef t -> t -> t -> IO () module Concurrency.MVar -- | An MVar (pronounced "em-var") is a synchronising variable, used -- for communication between concurrent threads. It can be thought of as -- a a box, which may be empty or full. data MVar a -- | Lifted newEmptyMVar. newEmptyMVar :: MonadIO m => m MVar a -- | Lifted newMVar. newMVar :: MonadIO m => a -> m MVar a -- | Lifted takeMVar. takeMVar :: MonadIO m => MVar a -> m a -- | Lifted putMVar. putMVar :: MonadIO m => MVar a -> a -> m () -- | Lifted readMVar. readMVar :: MonadIO m => MVar a -> m a -- | Lifted swapMVar. swapMVar :: MonadIO m => MVar a -> a -> m a -- | Lifted tryTakeMVar. tryTakeMVar :: MonadIO m => MVar a -> m Maybe a -- | Lifted tryPutMVar. tryPutMVar :: MonadIO m => MVar a -> a -> m Bool -- | Lifted isEmptyMVar. isEmptyMVar :: MonadIO m => MVar a -> m Bool -- | Unlifted withMVar. withMVar :: MonadUnliftIO m => MVar a -> a -> m b -> m b -- | Unlifted withMVarMasked. withMVarMasked :: MonadUnliftIO m => MVar a -> a -> m b -> m b -- | Unlifted modifyMVar_. modifyMVar_ :: MonadUnliftIO m => MVar a -> a -> m a -> m () -- | Unlifted modifyMVar. modifyMVar :: MonadUnliftIO m => MVar a -> a -> m (a, b) -> m b -- | Unlifted modifyMVarMasked_. modifyMVarMasked_ :: MonadUnliftIO m => MVar a -> a -> m a -> m () -- | Unlifted modifyMVarMasked. modifyMVarMasked :: MonadUnliftIO m => MVar a -> a -> m (a, b) -> m b -- | Lifted tryReadMVar. tryReadMVar :: MonadIO m => MVar a -> m Maybe a -- | Unlifted mkWeakMVar. mkWeakMVar :: MonadUnliftIO m => MVar a -> m () -> m Weak MVar a module Concurrency.QSem -- | QSem is a quantity semaphore in which the resource is aqcuired -- and released in units of one. It provides guaranteed FIFO ordering for -- satisfying blocked waitQSem calls. -- -- The pattern -- --
--   bracket_ waitQSem signalQSem (...)
--   
-- -- is safe; it never loses a unit of the resource. data QSem -- | Build a new QSem with a supplied initial quantity. The initial -- quantity must be at least 0. newQSem :: Int -> IO QSem -- | Wait for a unit to become available waitQSem :: QSem -> IO () -- | Signal that a unit of the QSem is available signalQSem :: QSem -> IO () -- | QSemN is a quantity semaphore in which the resource is aqcuired -- and released in units of one. It provides guaranteed FIFO ordering for -- satisfying blocked waitQSemN calls. -- -- The pattern -- --
--   bracket_ (waitQSemN n) (signalQSemN n) (...)
--   
-- -- is safe; it never loses any of the resource. data QSemN -- | Build a new QSemN with a supplied initial quantity. The initial -- quantity must be at least 0. newQSemN :: Int -> IO QSemN -- | Wait for the specified quantity to become available waitQSemN :: QSemN -> Int -> IO () -- | Signal that a given quantity is now available from the QSemN. signalQSemN :: QSemN -> Int -> IO () module Concurrency.TBChan module Concurrency.TBMChan module Concurrency.TBMQueue module Concurrency.TBQueue -- | TBQueue is an abstract type representing a bounded FIFO -- channel. data TBQueue a -- | Build and returns a new instance of TBQueue newTBQueue :: () => Int -> STM TBQueue a -- | Lifted version of newTBQueueIO newTBQueueIO :: MonadIO m => Int -> m TBQueue a -- | Read the next value from the TBQueue. readTBQueue :: () => TBQueue a -> STM a -- | A version of readTBQueue which does not retry. Instead it -- returns Nothing if no value is available. tryReadTBQueue :: () => TBQueue a -> STM Maybe a -- | Efficiently read the entire contents of a TBQueue into a list. -- This function never retries. flushTBQueue :: () => TBQueue a -> STM [a] -- | Get the next value from the TBQueue without removing it, -- retrying if the channel is empty. peekTBQueue :: () => TBQueue a -> STM a -- | A version of peekTBQueue which does not retry. Instead it -- returns Nothing if no value is available. tryPeekTBQueue :: () => TBQueue a -> STM Maybe a -- | Write a value to a TBQueue; blocks if the queue is full. writeTBQueue :: () => TBQueue a -> a -> STM () -- | Put a data item back onto a channel, where it will be the next item -- read. Blocks if the queue is full. unGetTBQueue :: () => TBQueue a -> a -> STM () -- | Returns True if the supplied TBQueue is empty. isEmptyTBQueue :: () => TBQueue a -> STM Bool -- | Returns True if the supplied TBQueue is full. isFullTBQueue :: () => TBQueue a -> STM Bool module Concurrency.TBimap module Concurrency.TChan -- | TChan is an abstract type representing an unbounded FIFO -- channel. data TChan a -- | Build and return a new instance of TChan newTChan :: () => STM TChan a -- | Lifted version of newTChanIO newTChanIO :: MonadIO m => m TChan a -- | Create a write-only TChan. More precisely, readTChan -- will retry even after items have been written to the channel. -- The only way to read a broadcast channel is to duplicate it with -- dupTChan. -- -- Consider a server that broadcasts messages to clients: -- --
--   serve :: TChan Message -> Client -> IO loop
--   serve broadcastChan client = do
--       myChan <- dupTChan broadcastChan
--       forever $ do
--           message <- readTChan myChan
--           send client message
--   
-- -- The problem with using newTChan to create the broadcast channel -- is that if it is only written to and never read, items will pile up in -- memory. By using newBroadcastTChan to create the broadcast -- channel, items can be garbage collected after clients have seen them. newBroadcastTChan :: () => STM TChan a -- | Lifted version of newBroadcastTChanIO newBroadcastTChanIO :: MonadIO m => m TChan a -- | Duplicate a TChan: the duplicate channel begins empty, but data -- written to either channel from then on will be available from both. -- Hence this creates a kind of broadcast channel, where data written by -- anyone is seen by everyone else. dupTChan :: () => TChan a -> STM TChan a -- | Clone a TChan: similar to dupTChan, but the cloned channel -- starts with the same content available as the original channel. cloneTChan :: () => TChan a -> STM TChan a -- | Read the next value from the TChan. readTChan :: () => TChan a -> STM a -- | A version of readTChan which does not retry. Instead it returns -- Nothing if no value is available. tryReadTChan :: () => TChan a -> STM Maybe a -- | Get the next value from the TChan without removing it, -- retrying if the channel is empty. peekTChan :: () => TChan a -> STM a -- | A version of peekTChan which does not retry. Instead it returns -- Nothing if no value is available. tryPeekTChan :: () => TChan a -> STM Maybe a -- | Write a value to a TChan. writeTChan :: () => TChan a -> a -> STM () -- | Put a data item back onto a channel, where it will be the next item -- read. unGetTChan :: () => TChan a -> a -> STM () -- | Returns True if the supplied TChan is empty. isEmptyTChan :: () => TChan a -> STM Bool module Concurrency.TMChan module Concurrency.TMQueue module Concurrency.TMVar -- | A TMVar is a synchronising variable, used for communication -- between concurrent threads. It can be thought of as a box, which may -- be empty or full. data TMVar a -- | Create a TMVar which contains the supplied value. newTMVar :: () => a -> STM TMVar a -- | Lifted version of newTMVarIO newTMVarIO :: MonadIO m => a -> m TMVar a -- | Create a TMVar which is initially empty. newEmptyTMVar :: () => STM TMVar a -- | Lifted version of newEmptyTMVarIO newEmptyTMVarIO :: MonadIO m => m TMVar a -- | Return the contents of the TMVar. If the TMVar is -- currently empty, the transaction will retry. After a -- takeTMVar, the TMVar is left empty. takeTMVar :: () => TMVar a -> STM a -- | A version of takeTMVar that does not retry. The -- tryTakeTMVar function returns Nothing if the -- TMVar was empty, or Just a if the TMVar -- was full with contents a. After tryTakeTMVar, the -- TMVar is left empty. tryTakeTMVar :: () => TMVar a -> STM Maybe a -- | Put a value into a TMVar. If the TMVar is currently -- full, putTMVar will retry. putTMVar :: () => TMVar a -> a -> STM () -- | A version of putTMVar that does not retry. The -- tryPutTMVar function attempts to put the value a into -- the TMVar, returning True if it was successful, or -- False otherwise. tryPutTMVar :: () => TMVar a -> a -> STM Bool -- | This is a combination of takeTMVar and putTMVar; ie. it -- takes the value from the TMVar, puts it back, and also returns -- it. readTMVar :: () => TMVar a -> STM a -- | A version of readTMVar which does not retry. Instead it returns -- Nothing if no value is available. tryReadTMVar :: () => TMVar a -> STM Maybe a -- | Swap the contents of a TMVar for a new value. swapTMVar :: () => TMVar a -> a -> STM a -- | Check whether a given TMVar is empty. isEmptyTMVar :: () => TMVar a -> STM Bool -- | Lifted version of mkWeakTMVar mkWeakTMVar :: MonadUnliftIO m => TMVar a -> m () -> m Weak TMVar a module Concurrency.TMap module Concurrency.TMultimap module Concurrency.TSem -- | TSem is a transactional semaphore. It holds a certain number of -- units, and units may be acquired or released by waitTSem and -- signalTSem respectively. When the TSem is empty, -- waitTSem blocks. -- -- Note that TSem has no concept of fairness, and there is no -- guarantee that threads blocked in waitTSem will be unblocked in -- the same order; in fact they will all be unblocked at the same time -- and will fight over the TSem. Hence TSem is not suitable -- if you expect there to be a high number of threads contending for the -- resource. However, like other STM abstractions, TSem is -- composable. data TSem -- | Construct new TSem with an initial counter value. -- -- A positive initial counter value denotes availability of units -- waitTSem can acquire. -- -- The initial counter value can be negative which denotes a resource -- "debt" that requires a respective amount of signalTSem -- operations to counter-balance. newTSem :: Int -> STM TSem -- | Wait on TSem (aka P operation). -- -- This operation acquires a unit from the semaphore (i.e. decreases the -- internal counter) and blocks (via retry) if no units are -- available (i.e. if the counter is not positive). waitTSem :: TSem -> STM () -- | Signal a TSem (aka V operation). -- -- This operation adds/releases a unit back to the semaphore (i.e. -- increments the internal counter). signalTSem :: TSem -> STM () -- | Multi-signal a TSem -- -- This operation adds/releases multiple units back to the semaphore -- (i.e. increments the internal counter). -- --
--   signalTSem == signalTSemN 1
--   
signalTSemN :: Word -> TSem -> STM () module Concurrency.TSet module Concurrency.TVar -- | Shared memory locations that support atomic memory transactions. data TVar a -- | Create a new TVar holding a value supplied newTVar :: () => a -> STM TVar a -- | Lifted version of newTVarIO newTVarIO :: MonadIO m => a -> m TVar a -- | Return the current value stored in a TVar. readTVar :: () => TVar a -> STM a -- | Lifted version of readTVarIO readTVarIO :: MonadIO m => TVar a -> m a -- | Write the supplied value into a TVar. writeTVar :: () => TVar a -> a -> STM () -- | Mutate the contents of a TVar. N.B., this version is -- non-strict. modifyTVar :: () => TVar a -> a -> a -> STM () -- | Strict version of modifyTVar. modifyTVar' :: () => TVar a -> a -> a -> STM () -- | Swap the contents of a TVar for a new value. swapTVar :: () => TVar a -> a -> STM a -- | Lifted version of mkWeakTVar mkWeakTVar :: MonadUnliftIO m => TVar a -> m () -> m Weak TVar a module Concurrency -- | Unlifted concurrently. concurrently :: MonadUnliftIO m => m a -> m b -> m (a, b) -- | Unlifted concurrently_. concurrently_ :: MonadUnliftIO m => m a -> m b -> m () -- | Unlifted race. race :: MonadUnliftIO m => m a -> m b -> m Either a b -- | Unlifted race_. race_ :: MonadUnliftIO m => m a -> m b -> m () -- | Unlifted mapConcurrently. mapConcurrently :: (MonadUnliftIO m, Traversable t) => a -> m b -> t a -> m t b -- | Unlifted mapConcurrently_. mapConcurrently_ :: (MonadUnliftIO m, Foldable f) => a -> m b -> f a -> m () -- | Unlifted forConcurrently. forConcurrently :: (MonadUnliftIO m, Traversable t) => t a -> a -> m b -> m t b -- | Unlifted forConcurrently_. forConcurrently_ :: (MonadUnliftIO m, Foldable f) => f a -> a -> m b -> m () -- | Unlifted replicateConcurrently. replicateConcurrently :: MonadUnliftIO m => Int -> m a -> m [a] -- | Unlifted replicateConcurrently_. replicateConcurrently_ :: MonadUnliftIO m => Int -> m a -> m () -- | Unlifted Concurrently. newtype Concurrently (m :: * -> *) a Concurrently :: m a -> Concurrently a [runConcurrently] :: Concurrently a -> m a -- | An asynchronous action spawned by async or withAsync. -- Asynchronous actions are executed in a separate thread, and operations -- are provided for waiting for asynchronous actions to complete and -- obtaining their results (see e.g. wait). data Async a -- | Unlifted async. async :: MonadUnliftIO m => m a -> m Async a -- | Unlifted asyncBound. asyncBound :: MonadUnliftIO m => m a -> m Async a -- | Unlifted asyncOn. asyncOn :: MonadUnliftIO m => Int -> m a -> m Async a -- | Unlifted asyncWithUnmask. asyncWithUnmask :: MonadUnliftIO m => forall b. () => m b -> m b -> m a -> m Async a -- | Unlifted asyncOnWithUnmask. asyncOnWithUnmask :: MonadUnliftIO m => Int -> forall b. () => m b -> m b -> m a -> m Async a -- | Lifted cancel. cancel :: MonadIO m => Async a -> m () -- | Lifted uninterruptibleCancel. uninterruptibleCancel :: MonadIO m => Async a -> m () -- | Lifted cancelWith. Additionally uses toAsyncException to -- ensure async exception safety. cancelWith :: (Exception e, MonadIO m) => Async a -> e -> m () -- | Unlifted withAsync. withAsync :: MonadUnliftIO m => m a -> Async a -> m b -> m b -- | Unlifted withAsyncBound. withAsyncBound :: MonadUnliftIO m => m a -> Async a -> m b -> m b -- | Unlifted withAsyncOn. withAsyncOn :: MonadUnliftIO m => Int -> m a -> Async a -> m b -> m b -- | Unlifted withAsyncWithUnmask. withAsyncWithUnmask :: MonadUnliftIO m => forall c. () => m c -> m c -> m a -> Async a -> m b -> m b -- | Unlifted withAsyncOnWithMask. withAsyncOnWithUnmask :: MonadUnliftIO m => Int -> forall c. () => m c -> m c -> m a -> Async a -> m b -> m b -- | Lifted wait. wait :: MonadIO m => Async a -> m a -- | A version of wait that can be used inside an STM transaction. waitSTM :: () => Async a -> STM a -- | Lifted waitCatch. waitCatch :: MonadIO m => Async a -> m Either SomeException a -- | A version of waitCatch that can be used inside an STM -- transaction. waitCatchSTM :: () => Async a -> STM Either SomeException a -- | Lifted waitAny. waitAny :: MonadIO m => [Async a] -> m (Async a, a) -- | A version of waitAny that can be used inside an STM -- transaction. waitAnySTM :: () => [Async a] -> STM (Async a, a) -- | Lifted waitAnyCatch. waitAnyCatch :: MonadIO m => [Async a] -> m (Async a, Either SomeException a) -- | A version of waitAnyCatch that can be used inside an STM -- transaction. waitAnyCatchSTM :: () => [Async a] -> STM (Async a, Either SomeException a) -- | Lifted waitAnyCancel. waitAnyCancel :: MonadIO m => [Async a] -> m (Async a, a) -- | Lifted waitAnyCatchCancel. waitAnyCatchCancel :: MonadIO m => [Async a] -> m (Async a, Either SomeException a) -- | Lifted waitEither. waitEither :: MonadIO m => Async a -> Async b -> m Either a b -- | A version of waitEither that can be used inside an STM -- transaction. waitEitherSTM :: () => Async a -> Async b -> STM Either a b -- | Lifted waitEither_. waitEither_ :: MonadIO m => Async a -> Async b -> m () -- | A version of waitEither_ that can be used inside an STM -- transaction. waitEitherSTM_ :: () => Async a -> Async b -> STM () -- | Lifted waitEitherCatch. waitEitherCatch :: MonadIO m => Async a -> Async b -> m Either Either SomeException a Either SomeException b -- | A version of waitEitherCatch that can be used inside an STM -- transaction. waitEitherCatchSTM :: () => Async a -> Async b -> STM Either Either SomeException a Either SomeException b -- | Lifted waitEitherCancel. waitEitherCancel :: MonadIO m => Async a -> Async b -> m Either a b -- | Lifted waitEitherCatchCancel. waitEitherCatchCancel :: MonadIO m => Async a -> Async b -> m Either Either SomeException a Either SomeException b -- | Lifted waitBoth. waitBoth :: MonadIO m => Async a -> Async b -> m (a, b) -- | A version of waitBoth that can be used inside an STM -- transaction. waitBothSTM :: () => Async a -> Async b -> STM (a, b) -- | Lifted poll. poll :: MonadIO m => Async a -> m Maybe Either SomeException a -- | A version of poll that can be used inside an STM transaction. pollSTM :: () => Async a -> STM Maybe Either SomeException a -- | Lifted link. link :: MonadIO m => Async a -> m () -- | Lifted link2. link2 :: MonadIO m => Async a -> Async b -> m () -- | Returns the ThreadId of the thread running the given -- Async. asyncThreadId :: Async a -> ThreadId -- | Compare two Asyncs that may have different types compareAsyncs :: () => Async a -> Async b -> Ordering data ExceptionInLinkedThread [ExceptionInLinkedThread] :: ExceptionInLinkedThread -- | The exception thrown by cancel to terminate a thread. data AsyncCancelled AsyncCancelled :: AsyncCancelled -- | Unlifted version of forkIO. forkIO :: MonadUnliftIO m => m () -> m ThreadId -- | Unlifted version of forkIOWithUnmask. forkWithUnmask :: MonadUnliftIO m => forall a. () => m a -> m a -> m () -> m ThreadId -- | Unlifted version of forkOn. forkOn :: MonadUnliftIO m => Int -> m () -> m ThreadId -- | Unlifted version of forkOnWithUnmask. forkOnWithUnmask :: MonadUnliftIO m => Int -> forall a. () => m a -> m a -> m () -> m ThreadId -- | Unlifted version of forkFinally. forkFinally :: MonadUnliftIO m => m a -> Either SomeException a -> m () -> m ThreadId -- | Throw an asynchronous exception to another thread. -- -- Synchronously typed exceptions will be wrapped into an -- AsyncExceptionWrapper, see -- https://github.com/fpco/safe-exceptions#determining-sync-vs-async. -- -- It's usually a better idea to use the UnliftIO.Async module, -- see https://github.com/fpco/safe-exceptions#quickstart. throwTo :: (Exception e, MonadIO m) => ThreadId -> e -> m () -- | Lifted version of killThread. killThread :: MonadIO m => ThreadId -> m () -- | A monad supporting atomic memory transactions. data STM a -- | Lifted version of atomically atomically :: MonadIO m => STM a -> m a -- | Retry execution of the current memory transaction because it has seen -- values in TVars which mean that it should not continue (e.g. -- the TVars represent a shared buffer that is now empty). The -- implementation may block the thread until one of the TVars that -- it has read from has been updated. (GHC only) retry :: () => STM a -- | A variant of throw that can only be used within the STM -- monad. -- -- Throwing an exception in STM aborts the transaction and -- propagates the exception. -- -- Although throwSTM has a type that is an instance of the type of -- throw, the two functions are subtly different: -- --
--   throw e    `seq` x  ===> throw e
--   throwSTM e `seq` x  ===> x
--   
-- -- The first example will cause the exception e to be raised, -- whereas the second one won't. In fact, throwSTM will only cause -- an exception to be raised when it is used within the STM monad. -- The throwSTM variant should be used in preference to -- throw to raise an exception within the STM monad because -- it guarantees ordering with respect to other STM operations, -- whereas throw does not. throwSTM :: Exception e => e -> STM a -- | Exception handling within STM actions. catchSTM :: Exception e => STM a -> e -> STM a -> STM a -- | Unsafely performs IO in the STM monad. Beware: this is a highly -- dangerous thing to do. -- -- unsafeIOToSTM :: () => IO a -> STM a -- | Lifted version of threadDelay. threadDelay :: MonadIO m => Int -> m () -- | Lifted version of registerDelay registerDelay :: MonadIO m => Int -> m TVar Bool -- | Lifted version of yield. yield :: MonadIO m => m () -- | A ThreadId is an abstract type representing a handle to a -- thread. ThreadId is an instance of Eq, Ord and -- Show, where the Ord instance implements an arbitrary -- total ordering over ThreadIds. The Show instance lets -- you convert an arbitrary-valued ThreadId to string form; -- showing a ThreadId value is occasionally useful when debugging -- or diagnosing the behaviour of a concurrent program. -- -- Note: in GHC, if you have a ThreadId, you essentially -- have a pointer to the thread itself. This means the thread itself -- can't be garbage collected until you drop the ThreadId. This -- misfeature will hopefully be corrected at a later date. data ThreadId -- | Lifted version of myThreadId. myThreadId :: MonadIO m => m ThreadId -- | Lifted version of mkWeakThreadId. mkWeakThreadId :: MonadIO m => ThreadId -> m Weak ThreadId -- | The current status of a thread data ThreadStatus -- | the thread is currently runnable or running ThreadRunning :: ThreadStatus -- | the thread has finished ThreadFinished :: ThreadStatus -- | the thread is blocked on some resource ThreadBlocked :: BlockReason -> ThreadStatus -- | the thread received an uncaught exception ThreadDied :: ThreadStatus data BlockReason -- | blocked on MVar BlockedOnMVar :: BlockReason -- | blocked on a computation in progress by another thread BlockedOnBlackHole :: BlockReason -- | blocked in throwTo BlockedOnException :: BlockReason -- | blocked in retry in an STM transaction BlockedOnSTM :: BlockReason -- | currently in a foreign call BlockedOnForeignCall :: BlockReason -- | blocked on some other resource. Without -threaded, I/O and -- threadDelay show up as BlockedOnOther, with -- -threaded they show up as BlockedOnMVar. BlockedOnOther :: BlockReason threadStatus :: ThreadId -> IO ThreadStatus -- | Lifted version of threadCapability. threadCapability :: MonadIO m => ThreadId -> m (Int, Bool) -- | labelThread stores a string as identifier for this thread if -- you built a RTS with debugging support. This identifier will be used -- in the debugging output to make distinction of different threads -- easier (otherwise you only have the thread state object's address in -- the heap). -- -- Other applications like the graphical Concurrent Haskell Debugger -- (http://www.informatik.uni-kiel.de/~fhu/chd/) may choose to -- overload labelThread for their purposes as well. labelThread :: ThreadId -> String -> IO () -- | Lifted version of threadWaitRead. threadWaitRead :: MonadIO m => Fd -> m () -- | Returns an STM action that can be used to wait for data to read from a -- file descriptor. The second returned value is an IO action that can be -- used to deregister interest in the file descriptor. threadWaitReadSTM :: Fd -> IO (STM (), IO ()) -- | Lifted version of threadWaitWrite. threadWaitWrite :: MonadIO m => Fd -> m () -- | Returns an STM action that can be used to wait until data can be -- written to a file descriptor. The second returned value is an IO -- action that can be used to deregister interest in the file descriptor. threadWaitWriteSTM :: Fd -> IO (STM (), IO ()) -- | Close a file descriptor in a concurrency-safe way (GHC only). If you -- are using threadWaitRead or threadWaitWrite to perform -- blocking I/O, you must use this function to close file -- descriptors, or blocked threads may not be woken. -- -- Any threads that are blocked on the file descriptor via -- threadWaitRead or threadWaitWrite will be unblocked by -- having IO exceptions thrown. closeFdWith :: Fd -> IO () -> Fd -> IO () -- | https://hackage.haskell.org/package/constraints module Constraint module Cont -- | Continuation monad. Cont r a is a CPS ("continuation-passing -- style") computation that produces an intermediate result of type -- a within a CPS computation whose final result type is -- r. -- -- The return function simply creates a continuation which -- passes the value on. -- -- The >>= operator adds the bound function into the -- continuation chain. type Cont r = ContT r Identity -- | Construct a continuation-passing computation from a function. (The -- inverse of runCont) cont :: () => a -> r -> r -> Cont r a -- | The result of running a CPS computation with a given final -- continuation. (The inverse of cont) runCont :: () => Cont r a -> a -> r -> r -- | Apply a function to transform the result of a continuation-passing -- computation. -- -- mapCont :: () => r -> r -> Cont r a -> Cont r a -- | Apply a function to transform the continuation passed to a CPS -- computation. -- -- withCont :: () => b -> r -> a -> r -> Cont r a -> Cont r b -- | The continuation monad transformer. Can be used to add continuation -- handling to any type constructor: the Monad instance and most -- of the operations do not require m to be a monad. -- -- ContT is not a functor on the category of monads, and many -- operations cannot be lifted through it. newtype ContT (r :: k) (m :: k -> *) a :: forall k. () => k -> k -> * -> * -> * ContT :: a -> m r -> m r -> ContT a [runContT] :: ContT a -> a -> m r -> m r -- | Apply a function to transform the result of a continuation-passing -- computation. This has a more restricted type than the map -- operations for other monad transformers, because ContT does not -- define a functor in the category of monads. -- -- mapContT :: () => m r -> m r -> ContT r m a -> ContT r m a -- | Apply a function to transform the continuation passed to a CPS -- computation. -- -- withContT :: () => b -> m r -> a -> m r -> ContT r m a -> ContT r m b class Monad m => MonadCont (m :: * -> *) -- | callCC (call-with-current-continuation) calls a function with -- the current continuation as its argument. Provides an escape -- continuation mechanism for use with Continuation monads. Escape -- continuations allow to abort the current computation and return a -- value immediately. They achieve a similar effect to throwError -- and catchError within an Error monad. Advantage of this -- function over calling return is that it makes the -- continuation explicit, allowing more flexibility and better control -- (see examples in Control.Monad.Cont). -- -- The standard idiom used with callCC is to provide a -- lambda-expression to name the continuation. Then calling the named -- continuation anywhere within its scope will escape from the -- computation, even if it is many layers deep within nested -- computations. callCC :: MonadCont m => a -> m b -> m a -> m a module Contravariant -- | The class of contravariant functors. -- -- Whereas in Haskell, one can think of a Functor as containing or -- producing values, a contravariant functor is a functor that can be -- thought of as consuming values. -- -- As an example, consider the type of predicate functions a -> -- Bool. One such predicate might be negative x = x < 0, -- which classifies integers as to whether they are negative. However, -- given this predicate, we can re-use it in other situations, providing -- we have a way to map values to integers. For instance, we can -- use the negative predicate on a person's bank balance to work -- out if they are currently overdrawn: -- --
--   newtype Predicate a = Predicate { getPredicate :: a -> Bool }
--   
--   instance Contravariant Predicate where
--     contramap f (Predicate p) = Predicate (p . f)
--                                            |   `- First, map the input...
--                                            `----- then apply the predicate.
--   
--   overdrawn :: Predicate Person
--   overdrawn = contramap personBankBalance negative
--   
-- -- Any instance should be subject to the following laws: -- --
--   contramap id = id
--   contramap f . contramap g = contramap (g . f)
--   
-- -- Note, that the second law follows from the free theorem of the type of -- contramap and the first law, so you need only check that the -- former condition holds. class Contravariant (f :: * -> *) contramap :: Contravariant f => a -> b -> f b -> f a -- | Replace all locations in the output with the same value. The default -- definition is contramap . const, but this may -- be overridden with a more efficient version. (>$) :: Contravariant f => b -> f b -> f a -- | If f is both Functor and Contravariant then by -- the time you factor in the laws of each of those classes, it can't -- actually use its argument in any meaningful capacity. -- -- This method is surprisingly useful. Where both instances exist and are -- lawful we have the following laws: -- --
--   fmap f ≡ phantom
--   contramap f ≡ phantom
--   
phantom :: (Functor f, Contravariant f) => f a -> f b -- | This is an infix alias for contramap (>$<) :: Contravariant f => a -> b -> f b -> f a infixl 4 >$< -- | This is an infix version of contramap with the arguments -- flipped. (>$$<) :: Contravariant f => f b -> a -> b -> f a infixl 4 >$$< -- | This is >$ with its arguments flipped. ($<) :: Contravariant f => f b -> b -> f a infixl 4 $< -- | This Setter can be used to map over all of the inputs to a -- Contravariant. -- --
--   contramapover contramapped
--   
-- --
--   >>> getPredicate (over contramapped (*2) (Predicate even)) 5
--   True
--   
-- --
--   >>> getOp (over contramapped (*5) (Op show)) 100
--   "500"
--   
-- --
--   >>> Prelude.map ($ 1) $ over (mapped . _Unwrapping' Op . contramapped) (*12) [(*2),(+1),(^3)]
--   [24,13,1728]
--   
contramapped :: Contravariant f => Setter f b f a a b module Copointed -- | Copointed does not require a Functor, as the only -- relationship between copoint and fmap is given by a free -- theorem. class Copointed (p :: * -> *) copoint :: Copointed p => p a -> a module Data -- | A generic applicative transformation that maps over the immediate -- subterms. -- -- gtraverse is to traverse what gmapM is to -- mapM -- -- This really belongs in Data.Data. gtraverse :: (Applicative f, Data a) => forall d. Data d => d -> f d -> a -> f a -- | A Plated type is one where we know how to extract its immediate -- self-similar children. -- -- Example 1: -- --
--   import Control.Applicative
--   import Control.Lens
--   import Control.Lens.Plated
--   import Data.Data
--   import Data.Data.Lens (uniplate)
--   
-- --
--   data Expr
--     = Val Int
--     | Neg Expr
--     | Add Expr Expr
--     deriving (Eq,Ord,Show,Read,Data,Typeable)
--   
-- --
--   instance Plated Expr where
--     plate f (Neg e) = Neg <$> f e
--     plate f (Add a b) = Add <$> f a <*> f b
--     plate _ a = pure a
--   
-- -- or -- --
--   instance Plated Expr where
--     plate = uniplate
--   
-- -- Example 2: -- --
--   import Control.Applicative
--   import Control.Lens
--   import Control.Lens.Plated
--   import Data.Data
--   import Data.Data.Lens (uniplate)
--   
-- --
--   data Tree a
--     = Bin (Tree a) (Tree a)
--     | Tip a
--     deriving (Eq,Ord,Show,Read,Data,Typeable)
--   
-- --
--   instance Plated (Tree a) where
--     plate f (Bin l r) = Bin <$> f l <*> f r
--     plate _ t = pure t
--   
-- -- or -- --
--   instance Data a => Plated (Tree a) where
--     plate = uniplate
--   
-- -- Note the big distinction between these two implementations. -- -- The former will only treat children directly in this tree as -- descendents, the latter will treat trees contained in the values under -- the tips also as descendants! -- -- When in doubt, pick a Traversal and just use the various -- ...Of combinators rather than pollute Plated with -- orphan instances! -- -- If you want to find something unplated and non-recursive with -- biplate use the ...OnOf variant with ignored, -- though those usecases are much better served in most cases by using -- the existing Lens combinators! e.g. -- --
--   toListOf biplateuniverseOnOf biplate ignored
--   
-- -- This same ability to explicitly pass the Traversal in question -- is why there is no analogue to uniplate's Biplate. -- -- Moreover, since we can allow custom traversals, we implement -- reasonable defaults for polymorphic data types, that only -- traverse into themselves, and not their polymorphic -- arguments. class Plated a -- | Traversal of the immediate children of this structure. -- -- If you're using GHC 7.2 or newer and your type has a Data -- instance, plate will default to uniplate and you can -- choose to not override it with your own definition. plate :: Plated a => Traversal' a a -- | Find every occurrence of a given type a recursively that -- doesn't require passing through something of type a using -- Data, while avoiding traversal of areas that cannot contain a -- value of type a. -- -- This is uniplate with a more liberal signature. template :: (Data s, Typeable a) => Traversal' s a -- | Naïve Traversal using Data. This does not attempt to -- optimize the traversal. -- -- This is primarily useful when the children are immediately obvious, -- and for benchmarking. tinplate :: (Data s, Typeable a) => Traversal' s a -- | Find descendants of type a non-transitively, while avoiding -- computation of areas that cannot contain values of type a -- using Data. -- -- uniplate is a useful default definition for plate uniplate :: Data a => Traversal' a a -- | biplate performs like template, except when s ~ -- a, it returns itself and nothing else. biplate :: (Data s, Typeable a) => Traversal' s a -- | Extract the immediate descendants of a Plated container. -- --
--   childrentoListOf plate
--   
children :: Plated a => a -> [a] -- | Rewrite by applying a rule everywhere you can. Ensures that the rule -- cannot be applied anywhere in the result: -- --
--   propRewrite r x = all (isNothing . r) (universe (rewrite r x))
--   
-- -- Usually transform is more appropriate, but rewrite can -- give better compositionality. Given two single transformations -- f and g, you can construct a -> f a -- mplus g a which performs both rewrites until a fixed -- point. rewrite :: Plated a => a -> Maybe a -> a -> a -- | Rewrite by applying a rule everywhere you can. Ensures that the rule -- cannot be applied anywhere in the result: -- --
--   propRewriteOf l r x = all (isNothing . r) (universeOf l (rewriteOf l r x))
--   
-- -- Usually transformOf is more appropriate, but rewriteOf -- can give better compositionality. Given two single transformations -- f and g, you can construct a -> f a -- mplus g a which performs both rewrites until a fixed -- point. -- --
--   rewriteOf :: Iso' a a       -> (a -> Maybe a) -> a -> a
--   rewriteOf :: Lens' a a      -> (a -> Maybe a) -> a -> a
--   rewriteOf :: Traversal' a a -> (a -> Maybe a) -> a -> a
--   rewriteOf :: Setter' a a    -> (a -> Maybe a) -> a -> a
--   
rewriteOf :: () => ASetter a b a b -> b -> Maybe a -> a -> b -- | Rewrite recursively over part of a larger structure. -- --
--   rewriteOn :: Plated a => Iso' s a       -> (a -> Maybe a) -> s -> s
--   rewriteOn :: Plated a => Lens' s a      -> (a -> Maybe a) -> s -> s
--   rewriteOn :: Plated a => Traversal' s a -> (a -> Maybe a) -> s -> s
--   rewriteOn :: Plated a => ASetter' s a   -> (a -> Maybe a) -> s -> s
--   
rewriteOn :: Plated a => ASetter s t a a -> a -> Maybe a -> s -> t -- | Rewrite recursively over part of a larger structure using a specified -- Setter. -- --
--   rewriteOnOf :: Iso' s a       -> Iso' a a       -> (a -> Maybe a) -> s -> s
--   rewriteOnOf :: Lens' s a      -> Lens' a a      -> (a -> Maybe a) -> s -> s
--   rewriteOnOf :: Traversal' s a -> Traversal' a a -> (a -> Maybe a) -> s -> s
--   rewriteOnOf :: Setter' s a    -> Setter' a a    -> (a -> Maybe a) -> s -> s
--   
rewriteOnOf :: () => ASetter s t a b -> ASetter a b a b -> b -> Maybe a -> s -> t -- | Rewrite by applying a monadic rule everywhere you can. Ensures that -- the rule cannot be applied anywhere in the result. rewriteM :: (Monad m, Plated a) => a -> m Maybe a -> a -> m a -- | Rewrite by applying a monadic rule everywhere you recursing with a -- user-specified Traversal. Ensures that the rule cannot be -- applied anywhere in the result. rewriteMOf :: Monad m => LensLike WrappedMonad m a b a b -> b -> m Maybe a -> a -> m b -- | Rewrite by applying a monadic rule everywhere inside of a structure -- located by a user-specified Traversal. Ensures that the rule -- cannot be applied anywhere in the result. rewriteMOn :: (Monad m, Plated a) => LensLike WrappedMonad m s t a a -> a -> m Maybe a -> s -> m t -- | Rewrite by applying a monadic rule everywhere inside of a structure -- located by a user-specified Traversal, using a user-specified -- Traversal for recursion. Ensures that the rule cannot be -- applied anywhere in the result. rewriteMOnOf :: Monad m => LensLike WrappedMonad m s t a b -> LensLike WrappedMonad m a b a b -> b -> m Maybe a -> s -> m t -- | Retrieve all of the transitive descendants of a Plated -- container, including itself. universe :: Plated a => a -> [a] -- | Given a Fold that knows how to locate immediate children, -- retrieve all of the transitive descendants of a node, including -- itself. -- --
--   universeOf :: Fold a a -> a -> [a]
--   
universeOf :: () => Getting [a] a a -> a -> [a] -- | Given a Fold that knows how to find Plated parts of a -- container retrieve them and all of their descendants, recursively. universeOn :: Plated a => Getting [a] s a -> s -> [a] -- | Given a Fold that knows how to locate immediate children, -- retrieve all of the transitive descendants of a node, including itself -- that lie in a region indicated by another Fold. -- --
--   toListOf l ≡ universeOnOf l ignored
--   
universeOnOf :: () => Getting [a] s a -> Getting [a] a a -> s -> [a] -- | Fold over all transitive descendants of a Plated container, -- including itself. cosmos :: Plated a => Fold a a -- | Given a Fold that knows how to locate immediate children, fold -- all of the transitive descendants of a node, including itself. -- --
--   cosmosOf :: Fold a a -> Fold a a
--   
cosmosOf :: (Applicative f, Contravariant f) => LensLike' f a a -> LensLike' f a a -- | Given a Fold that knows how to find Plated parts of a -- container fold them and all of their descendants, recursively. -- --
--   cosmosOn :: Plated a => Fold s a -> Fold s a
--   
cosmosOn :: (Applicative f, Contravariant f, Plated a) => LensLike' f s a -> LensLike' f s a -- | Given a Fold that knows how to locate immediate children, fold -- all of the transitive descendants of a node, including itself that lie -- in a region indicated by another Fold. -- --
--   cosmosOnOf :: Fold s a -> Fold a a -> Fold s a
--   
cosmosOnOf :: (Applicative f, Contravariant f) => LensLike' f s a -> LensLike' f a a -> LensLike' f s a -- | Transform every element in the tree, in a bottom-up manner. -- -- For example, replacing negative literals with literals: -- --
--   negLits = transform $ \x -> case x of
--     Neg (Lit i) -> Lit (negate i)
--     _           -> x
--   
transform :: Plated a => a -> a -> a -> a -- | Transform every element by recursively applying a given Setter -- in a bottom-up manner. -- --
--   transformOf :: Traversal' a a -> (a -> a) -> a -> a
--   transformOf :: Setter' a a    -> (a -> a) -> a -> a
--   
transformOf :: () => ASetter a b a b -> b -> b -> a -> b -- | Transform every element in a region indicated by a Setter by -- recursively applying another Setter in a bottom-up manner. -- --
--   transformOnOf :: Setter' s a -> Traversal' a a -> (a -> a) -> s -> s
--   transformOnOf :: Setter' s a -> Setter' a a    -> (a -> a) -> s -> s
--   
transformOnOf :: () => ASetter s t a b -> ASetter a b a b -> b -> b -> s -> t -- | Transform every element in the tree, in a bottom-up manner, -- monadically. transformM :: (Monad m, Plated a) => a -> m a -> a -> m a -- | Transform every element in a tree using a user supplied -- Traversal in a bottom-up manner with a monadic effect. -- --
--   transformMOf :: Monad m => Traversal' a a -> (a -> m a) -> a -> m a
--   
transformMOf :: Monad m => LensLike WrappedMonad m a b a b -> b -> m b -> a -> m b -- | Transform every element in the tree in a region indicated by a -- supplied Traversal, in a bottom-up manner, monadically. -- --
--   transformMOn :: (Monad m, Plated a) => Traversal' s a -> (a -> m a) -> s -> m s
--   
transformMOn :: (Monad m, Plated a) => LensLike WrappedMonad m s t a a -> a -> m a -> s -> m t -- | Transform every element in a tree that lies in a region indicated by a -- supplied Traversal, walking with a user supplied -- Traversal in a bottom-up manner with a monadic effect. -- --
--   transformMOnOf :: Monad m => Traversal' s a -> Traversal' a a -> (a -> m a) -> s -> m s
--   
transformMOnOf :: Monad m => LensLike WrappedMonad m s t a b -> LensLike WrappedMonad m a b a b -> b -> m b -> s -> m t -- | Return a list of all of the editable contexts for every location in -- the structure, recursively. -- --
--   propUniverse x = universe x == map pos (contexts x)
--   propId x = all (== x) [extract w | w <- contexts x]
--   
-- --
--   contextscontextsOf plate
--   
contexts :: Plated a => a -> [Context a a a] -- | Return a list of all of the editable contexts for every location in -- the structure, recursively, using a user-specified Traversal to -- walk each layer. -- --
--   propUniverse l x = universeOf l x == map pos (contextsOf l x)
--   propId l x = all (== x) [extract w | w <- contextsOf l x]
--   
-- --
--   contextsOf :: Traversal' a a -> a -> [Context a a a]
--   
contextsOf :: () => ATraversal' a a -> a -> [Context a a a] -- | Return a list of all of the editable contexts for every location in -- the structure in an areas indicated by a user supplied -- Traversal, recursively using plate. -- --
--   contextsOn b ≡ contextsOnOf b plate
--   
-- --
--   contextsOn :: Plated a => Traversal' s a -> s -> [Context a a s]
--   
contextsOn :: Plated a => ATraversal s t a a -> s -> [Context a a t] -- | Return a list of all of the editable contexts for every location in -- the structure in an areas indicated by a user supplied -- Traversal, recursively using another user-supplied -- Traversal to walk each layer. -- --
--   contextsOnOf :: Traversal' s a -> Traversal' a a -> s -> [Context a a s]
--   
contextsOnOf :: () => ATraversal s t a a -> ATraversal' a a -> s -> [Context a a t] -- | The one-level version of context. This extracts a list of the -- immediate children as editable contexts. -- -- Given a context you can use pos to see the values, peek -- at what the structure would be like with an edited result, or simply -- extract the original structure. -- --
--   propChildren x = children l x == map pos (holes l x)
--   propId x = all (== x) [extract w | w <- holes l x]
--   
-- --
--   holes = holesOf plate
--   
holes :: Plated a => a -> [Pretext ((->) :: * -> * -> *) a a a] -- | An alias for holesOf, provided for consistency with the other -- combinators. -- --
--   holesOnholesOf
--   
-- --
--   holesOn :: Iso' s a                -> s -> [Pretext (->) a a s]
--   holesOn :: Lens' s a               -> s -> [Pretext (->) a a s]
--   holesOn :: Traversal' s a          -> s -> [Pretext (->) a a s]
--   holesOn :: IndexedLens' i s a      -> s -> [Pretext (Indexed i) a a s]
--   holesOn :: IndexedTraversal' i s a -> s -> [Pretext (Indexed i) a a s]
--   
holesOn :: Conjoined p => Over p Bazaar p a a s t a a -> s -> [Pretext p a a t] -- | Extract one level of holes from a container in a region -- specified by one Traversal, using another. -- --
--   holesOnOf b l ≡ holesOf (b . l)
--   
-- --
--   holesOnOf :: Iso' s a       -> Iso' a a                -> s -> [Pretext (->) a a s]
--   holesOnOf :: Lens' s a      -> Lens' a a               -> s -> [Pretext (->) a a s]
--   holesOnOf :: Traversal' s a -> Traversal' a a          -> s -> [Pretext (->) a a s]
--   holesOnOf :: Lens' s a      -> IndexedLens' i a a      -> s -> [Pretext (Indexed i) a a s]
--   holesOnOf :: Traversal' s a -> IndexedTraversal' i a a -> s -> [Pretext (Indexed i) a a s]
--   
holesOnOf :: Conjoined p => LensLike Bazaar p r r s t a b -> Over p Bazaar p r r a b r r -> s -> [Pretext p r r t] -- | Perform a fold-like computation on each value, technically a -- paramorphism. -- --
--   paraparaOf plate
--   
para :: Plated a => a -> [r] -> r -> a -> r -- | Perform a fold-like computation on each value, technically a -- paramorphism. -- --
--   paraOf :: Fold a a -> (a -> [r] -> r) -> a -> r
--   
paraOf :: () => Getting Endo [a] a a -> a -> [r] -> r -> a -> r -- | Try to apply a traversal to all transitive descendants of a -- Plated container, but do not recurse through matching -- descendants. -- --
--   deep :: Plated s => Fold s a                 -> Fold s a
--   deep :: Plated s => IndexedFold s a          -> IndexedFold s a
--   deep :: Plated s => Traversal s s a b        -> Traversal s s a b
--   deep :: Plated s => IndexedTraversal s s a b -> IndexedTraversal s s a b
--   
deep :: (Conjoined p, Applicative f, Plated s) => Traversing p f s s a b -> Over p f s s a b -- | Fold the immediate children of a Plated container. -- --
--   composOpFold z c f = foldrOf plate (c . f) z
--   
composOpFold :: Plated a => b -> b -> b -> b -> a -> b -> a -> b -- | The original uniplate combinator, implemented in terms of -- Plated as a Lens. -- --
--   partspartsOf plate
--   
-- -- The resulting Lens is safer to use as it ignores -- 'over-application' and deals gracefully with under-application, but it -- is only a proper Lens if you don't change the list -- length! parts :: Plated a => Lens' a [a] module Debug -- | The trace function outputs the trace message given as its first -- argument, before returning the second argument as its result. -- -- For example, this returns the value of f x but first outputs -- the message. -- --
--   >>> let x = 123; f = show
--   
--   >>> trace ("calling f with x = " ++ show x) (f x)
--   "calling f with x = 123
--   123"
--   
-- -- The trace function should only be used for debugging, or -- for monitoring execution. The function is not referentially -- transparent: its type indicates that it is a pure function but it has -- the side effect of outputting the trace message. trace :: () => String -> a -> a -- | Like trace but returns the message instead of a third value. -- --
--   >>> traceId "hello"
--   "hello
--   hello"
--   
traceId :: String -> String -- | Like trace, but uses show on the argument to convert it -- to a String. -- -- This makes it convenient for printing the values of interesting -- variables or expressions inside a function. For example here we print -- the value of the variables x and y: -- --
--   >>> let f x y = traceShow (x,y) (x + y) in f (1+2) 5
--   (3,5)
--   8
--   
traceShow :: Show a => a -> b -> b -- | Like traceShow but returns the shown value instead of a third -- value. -- --
--   >>> traceShowId (1+2+3, "hello" ++ "world")
--   (6,"helloworld")
--   (6,"helloworld")
--   
traceShowId :: Show a => a -> a -- | like trace, but additionally prints a call stack if one is -- available. -- -- In the current GHC implementation, the call stack is only available if -- the program was compiled with -prof; otherwise -- traceStack behaves exactly like trace. Entries in the -- call stack correspond to SCC annotations, so it is a good -- idea to use -fprof-auto or -fprof-auto-calls to add -- SCC annotations automatically. traceStack :: () => String -> a -> a -- | Like trace but returning unit in an arbitrary -- Applicative context. Allows for convenient use in do-notation. -- -- Note that the application of traceM is not an action in the -- Applicative context, as traceIO is in the IO -- type. While the fresh bindings in the following example will force the -- traceM expressions to be reduced every time the -- do-block is executed, traceM "not crashed" would -- only be reduced once, and the message would only be printed once. If -- your monad is in MonadIO, liftIO . traceIO may be a -- better option. -- --
--   >>> :{
--   do
--       x <- Just 3
--       traceM ("x: " ++ show x)
--       y <- pure 12
--       traceM ("y: " ++ show y)
--       pure (x*2 + y)
--   :}
--   x: 3
--   y: 12
--   Just 18
--   
traceM :: Applicative f => String -> f () -- | Like traceM, but uses show on the argument to convert it -- to a String. -- --
--   >>> :{
--   do
--       x <- Just 3
--       traceShowM x
--       y <- pure 12
--       traceShowM y
--       pure (x*2 + y)
--   :}
--   3
--   12
--   Just 18
--   
traceShowM :: (Show a, Applicative f) => a -> f () -- | The traceEvent function behaves like trace with the -- difference that the message is emitted to the eventlog, if eventlog -- profiling is available and enabled at runtime. -- -- It is suitable for use in pure code. In an IO context use -- traceEventIO instead. -- -- Note that when using GHC's SMP runtime, it is possible (but rare) to -- get duplicate events emitted if two CPUs simultaneously evaluate the -- same thunk that uses traceEvent. traceEvent :: () => String -> a -> a -- | The traceEventIO function emits a message to the eventlog, if -- eventlog profiling is available and enabled at runtime. -- -- Compared to traceEvent, traceEventIO sequences the event -- with respect to other IO actions. traceEventIO :: String -> IO () -- | The traceMarker function emits a marker to the eventlog, if -- eventlog profiling is available and enabled at runtime. The -- String is the name of the marker. The name is just used in -- the profiling tools to help you keep clear which marker is which. -- -- This function is suitable for use in pure code. In an IO context use -- traceMarkerIO instead. -- -- Note that when using GHC's SMP runtime, it is possible (but rare) to -- get duplicate events emitted if two CPUs simultaneously evaluate the -- same thunk that uses traceMarker. traceMarker :: () => String -> a -> a -- | The traceMarkerIO function emits a marker to the eventlog, if -- eventlog profiling is available and enabled at runtime. -- -- Compared to traceMarker, traceMarkerIO sequences the -- event with respect to other IO actions. traceMarkerIO :: String -> IO () -- | 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 -- | 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] -- | Get the stack trace attached to an object. whoCreated :: () => a -> IO [String] -- | 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 -- | Return the current CallStack. -- -- Does *not* include the call-site of callStack. callStack :: HasCallStack -> CallStack -- | The empty CallStack. emptyCallStack :: CallStack -- | Freeze a call-stack, preventing any further call-sites from being -- appended. -- --
--   pushCallStack callSite (freezeCallStack callStack) = freezeCallStack callStack
--   
freezeCallStack :: CallStack -> CallStack -- | Convert a list of call-sites to a CallStack. fromCallSiteList :: [([Char], SrcLoc)] -> CallStack -- | Extract a list of call-sites from the CallStack. -- -- The list is ordered by most recent call. getCallStack :: CallStack -> [([Char], SrcLoc)] -- | Pop the most recent call-site off the CallStack. -- -- This function, like pushCallStack, has no effect on a frozen -- CallStack. popCallStack :: CallStack -> CallStack -- | Pretty print a CallStack. prettyCallStack :: CallStack -> String -- | Push a call-site onto the stack. -- -- This function has no effect on a frozen CallStack. pushCallStack :: ([Char], SrcLoc) -> CallStack -> CallStack -- | Perform some computation without adding new entries to the -- CallStack. withFrozenCallStack :: HasCallStack => HasCallStack -> a -> a -- | A single location in the source code. data SrcLoc SrcLoc :: [Char] -> [Char] -> [Char] -> Int -> Int -> Int -> Int -> SrcLoc [srcLocPackage] :: SrcLoc -> [Char] [srcLocModule] :: SrcLoc -> [Char] [srcLocFile] :: SrcLoc -> [Char] [srcLocStartLine] :: SrcLoc -> Int [srcLocStartCol] :: SrcLoc -> Int [srcLocEndLine] :: SrcLoc -> Int [srcLocEndCol] :: SrcLoc -> Int -- | Pretty print a SrcLoc. prettySrcLoc :: SrcLoc -> String data Location Location :: String -> String -> Maybe (String, Int, Int) -> Location [objectName] :: Location -> String [functionName] :: Location -> String [srcLoc] :: Location -> Maybe (String, Int, Int) getStackTrace :: IO (Maybe [Location]) -- | Get a string representation of the current execution stack state. showStackTrace :: IO Maybe String module Decidable -- | A Decidable contravariant functor is the contravariant analogue -- of Alternative. -- -- Noting the superclass constraint that f must also be -- Divisible, a Decidable functor has the ability to "fan -- out" input, under the intuition that contravariant functors consume -- input. -- -- In the dicussion for Divisible, an example was demonstrated -- with Serializers, that turn as into -- ByteStrings. Divisible allowed us to serialize the -- product of multiple values by concatenation. By making our -- Serializer also Decidable- we now have the ability -- to serialize the sum of multiple values - for example different -- constructors in an ADT. -- -- Consider serializing arbitrary identifiers that can be either -- Strings or Ints: -- --
--   data Identifier = StringId String | IntId Int
--   
-- -- We know we have serializers for Strings and Ints, -- but how do we combine them into a Serializer for -- Identifier? Essentially, our Serializer needs to -- scrutinise the incoming value and choose how to serialize it: -- --
--   identifier :: Serializer Identifier
--   identifier = Serializer $ identifier ->
--     case identifier of
--       StringId s -> runSerializer string s
--       IntId i -> runSerializer int i
--   
-- -- It is exactly this notion of choice that Decidable encodes. -- Hence if we add an instance of Decidable for -- Serializer... -- --
--   instance Decidable Serializer where
--     lose f = Serializer $ a -> absurd (f a)
--     choose split l r = Serializer $ a ->
--       either (runSerializer l) (runSerializer r) (split a)
--   
-- -- Then our identifier Serializer is -- --
--   identifier :: Serializer Identifier
--   identifier = choose toEither string int where
--     toEither (StringId s) = Left s
--     toEither (IntId i) = Right i
--   
class Divisible f => Decidable (f :: * -> *) -- | Acts as identity to choose. lose :: Decidable f => a -> Void -> f a choose :: Decidable f => a -> Either b c -> f b -> f c -> f a -- |
--   chosen = choose id
--   
chosen :: Decidable f => f b -> f c -> f Either b c -- |
--   lost = lose id
--   
lost :: Decidable f => f Void contramany :: Decidable f => f a -> f [a] module Distributive -- | This is the categorical dual of Traversable. -- -- Due to the lack of non-trivial comonoids in Haskell, we can restrict -- ourselves to requiring a Functor rather than some Coapplicative -- class. Categorically every Distributive functor is actually a -- right adjoint, and so it must be Representable endofunctor -- and preserve all limits. This is a fancy way of saying it isomorphic -- to (->) x for some x. -- -- To be distributable a container will need to have a way to -- consistently zip a potentially infinite number of copies of itself. -- This effectively means that the holes in all values of that type, must -- have the same cardinality, fixed sized vectors, infinite streams, -- functions, etc. and no extra information to try to merge together. class Functor g => Distributive (g :: * -> *) -- | The dual of sequenceA -- --
--   >>> distribute [(+1),(+2)] 1
--   [2,3]
--   
-- --
--   distribute = collect id
--   distribute . distribute = id
--   
distribute :: (Distributive g, Functor f) => f g a -> g f a -- |
--   collect f = distribute . fmap f
--   fmap f = runIdentity . collect (Identity . f)
--   fmap distribute . collect f = getCompose . collect (Compose . f)
--   
collect :: (Distributive g, Functor f) => a -> g b -> f a -> g f b -- | The dual of sequence -- --
--   distributeM = fmap unwrapMonad . distribute . WrapMonad
--   
distributeM :: (Distributive g, Monad m) => m g a -> g m a -- |
--   collectM = distributeM . liftM f
--   
collectM :: (Distributive g, Monad m) => a -> g b -> m a -> g m b -- | The dual of traverse -- --
--   cotraverse f = fmap f . distribute
--   
cotraverse :: (Distributive g, Functor f) => f a -> b -> f g a -> g b -- | The dual of mapM -- --
--   comapM f = fmap f . distributeM
--   
comapM :: (Distributive g, Monad m) => m a -> b -> m g a -> g b -- | fmapCollect is a viable default definition for fmap -- given a Distributive instance defined in terms of -- collect. fmapCollect :: Distributive f => a -> b -> f a -> f b module Divisible -- | A Divisible contravariant functor is the contravariant analogue -- of Applicative. -- -- Continuing the intuition that Contravariant functors consume -- input, a Divisible contravariant functor also has the ability -- to be composed "beside" another contravariant functor. -- -- Serializers provide a good example of Divisible contravariant -- functors. To begin let's start with the type of serializers for -- specific types: -- --
--   newtype Serializer a = Serializer { runSerializer :: a -> ByteString }
--   
-- -- This is a contravariant functor: -- --
--   instance Contravariant Serializer where
--     contramap f s = Serializer (runSerializer s . f)
--   
-- -- That is, given a serializer for a (s :: Serializer -- a), and a way to turn bs into as (a mapping -- f :: b -> a), we have a serializer for b: -- contramap f s :: Serializer b. -- -- Divisible gives us a way to combine two serializers that focus on -- different parts of a structure. If we postulate the existance of two -- primitive serializers - string :: Serializer String and -- int :: Serializer Int, we would like to be able to combine -- these into a serializer for pairs of Strings and -- Ints. How can we do this? Simply run both serializer and -- combine their output! -- --
--   data StringAndInt = StringAndInt String Int
--   
--   stringAndInt :: Serializer StringAndInt
--   stringAndInt = Serializer $ (StringAndInt s i) ->
--     let sBytes = runSerializer string s
--         iBytes = runSerializer int i
--     in sBytes <> iBytes
--   
-- -- divide is a generalization by also taking a contramap -- like function to split any a into a pair. This conveniently -- allows you to target fields of a record, for instance, by extracting -- the values under two fields and combining them into a tuple. -- -- To complete the example, here is how to write stringAndInt -- using a Divisible instance: -- --
--   instance Divisible Serializer where
--     conquer = Serializer (const mempty)
--   
--     divide toBC bSerializer cSerializer = Serializer $ a ->
--       case toBC a of
--         (b, c) ->
--           let bBytes = runSerializer bSerializer b
--               cBytes = runSerializer cSerializer c
--           in bBytes <> cBytes
--   
--   stringAndInt :: Serializer StringAndInt
--   stringAndInt =
--     divide ((StringAndInt s i) -> (s, i)) string int
--   
class Contravariant f => Divisible (f :: * -> *) divide :: Divisible f => a -> (b, c) -> f b -> f c -> f a -- | Conquer acts as an identity for combining Divisible functors. conquer :: Divisible f => f a -- |
--   divided = divide id
--   
divided :: Divisible f => f a -> f b -> f (a, b) -- | Redundant, but provided for symmetry. -- --
--   conquered = conquer
--   
conquered :: Divisible f => f () contrazip3 :: Divisible f => f a1 -> f a2 -> f a3 -> f (a1, a2, a3) contrazip4 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f (a1, a2, a3, a4) contrazip5 :: Divisible f => f a1 -> f a2 -> f a3 -> f a4 -> f a5 -> f (a1, a2, a3, a4, a5) -- | A combination of a divisible functor with some input for it. Allows to -- use the Monoid API for composition. data Supplied (divisible :: * -> *) [Supplied] :: Supplied divisible module Dynamic -- | A value of type Dynamic is an object encapsulated together with -- its type. -- -- A Dynamic may only represent a monomorphic value; an attempt to -- create a value of type Dynamic from a polymorphically-typed -- expression will result in an ambiguity error (see toDyn). -- -- Showing a value of type Dynamic returns a pretty-printed -- representation of the object's type; useful for debugging. data Dynamic [Dynamic] :: Dynamic -- | Converts an arbitrary value into an object of type Dynamic. -- -- The type of the object must be an instance of Typeable, which -- ensures that only monomorphically-typed objects may be converted to -- Dynamic. To convert a polymorphic object into Dynamic, -- give it a monomorphic type signature. For example: -- --
--   toDyn (id :: Int -> Int)
--   
toDyn :: Typeable a => a -> Dynamic -- | Converts a Dynamic object back into an ordinary Haskell value -- of the correct type. See also fromDyn. fromDynamic :: Typeable a => Dynamic -> Maybe a dynApply :: Dynamic -> Dynamic -> Maybe Dynamic dynTypeRep :: Dynamic -> SomeTypeRep module Either -- | 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 -- | 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 -- | Monadic generalisation of either. eitherM :: Monad m => a -> m c -> b -> m c -> m Either a b -> m c -- | 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] -- | 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] -- | Return True if the given value is a Left-value, -- False otherwise. -- --

Examples

-- -- Basic usage: -- --
--   >>> isLeft (Left "foo")
--   True
--   
--   >>> isLeft (Right 3)
--   False
--   
-- -- Assuming a Left value signifies some sort of error, we can use -- isLeft to write a very simple error-reporting function that -- does absolutely nothing in the case of success, and outputs "ERROR" if -- any error occurred. -- -- This example shows how isLeft might be used to avoid pattern -- matching when one does not care about the value contained in the -- constructor: -- --
--   >>> import Control.Monad ( when )
--   
--   >>> let report e = when (isLeft e) $ putStrLn "ERROR"
--   
--   >>> report (Right 1)
--   
--   >>> report (Left "parse error")
--   ERROR
--   
isLeft :: () => Either a b -> Bool -- | Return 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 the contents of a Left-value or a default value -- otherwise. -- --

Examples

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

Examples

-- -- Basic usage: -- --
--   >>> fromRight 1 (Right 3)
--   3
--   
--   >>> fromRight 1 (Left "foo")
--   1
--   
fromRight :: () => b -> Either a b -> b -- | 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]) -- | This Prism provides a Traversal for tweaking the -- Left half of an Either: -- --
--   >>> over _Left (+1) (Left 2)
--   Left 3
--   
-- --
--   >>> over _Left (+1) (Right 2)
--   Right 2
--   
-- --
--   >>> Right 42 ^._Left :: String
--   ""
--   
-- --
--   >>> Left "hello" ^._Left
--   "hello"
--   
-- -- It also can be turned around to obtain the embedding into the -- Left half of an Either: -- --
--   >>> _Left # 5
--   Left 5
--   
-- --
--   >>> 5^.re _Left
--   Left 5
--   
_Left :: (Choice p, Applicative f) => p a f b -> p Either a c f Either b c -- | This Prism provides a Traversal for tweaking the -- Right half of an Either: -- --
--   >>> over _Right (+1) (Left 2)
--   Left 2
--   
-- --
--   >>> over _Right (+1) (Right 2)
--   Right 3
--   
-- --
--   >>> Right "hello" ^._Right
--   "hello"
--   
-- --
--   >>> Left "hello" ^._Right :: [Double]
--   []
--   
-- -- It also can be turned around to obtain the embedding into the -- Right half of an Either: -- --
--   >>> _Right # 5
--   Right 5
--   
-- --
--   >>> 5^.re _Right
--   Right 5
--   
_Right :: (Choice p, Applicative f) => p a f b -> p Either c a f Either c b module Enum -- | 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..]. enumFrom :: Enum a => a -> [a] -- | Used in Haskell's translation of [n,n'..]. enumFromThen :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n..m]. enumFromTo :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n,n'..m]. enumFromThenTo :: Enum a => a -> a -> a -> [a] module Environment -- | Computation getArgs returns a list of the program's command -- line arguments (not including the program name). getArgs :: IO [String] -- | Computation getFullArgs is the "raw" version of -- getArgs, similar to argv in other languages. It -- returns a list of the program's command line arguments, starting with -- the program name, and including those normally eaten by the RTS (+RTS -- ... -RTS). getFullArgs :: IO [String] -- | withArgs args act - while executing action -- act, have getArgs return args. withArgs :: () => [String] -> IO a -> IO a -- | Computation getProgName returns the name of the program as it -- was invoked. -- -- However, this is hard-to-impossible to implement on some non-Unix -- OSes, so instead, for maximum portability, we just return the leafname -- of the program as invoked. Even then there are some differences -- between platforms: on Windows, for example, a program invoked as foo -- is probably really FOO.EXE, and that is what -- getProgName will return. getProgName :: IO String -- | withProgName name act - while executing action -- act, have getProgName return name. withProgName :: () => String -> IO a -> IO a -- | Returns the absolute pathname of the current executable. -- -- Note that for scripts and interactive sessions, this is the path to -- the interpreter (e.g. ghci.) -- -- Since base 4.11.0.0, getExecutablePath resolves symlinks on -- Windows. If an executable is launched through a symlink, -- getExecutablePath returns the absolute path of the original -- executable. getExecutablePath :: IO FilePath -- | getEnvironment retrieves the entire environment as a list of -- (key,value) pairs. -- -- If an environment entry does not contain an '=' character, -- the key is the whole entry and the value is the -- empty string. getEnvironment :: IO [(String, String)] -- | lookupEnv. getEnv :: String -> IO Maybe String -- | Get an environment value or a default value. getEnvDefault :: String -> String -> IO String -- | Like setEnv, but allows blank environment values and mimics the -- function signature of setEnv from the unix package. setEnv :: String -> String -> Bool -> IO () -- | Like unsetEnv, but allows for the removal of blank environment -- variables. unsetEnv :: String -> IO () module Equality -- | 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. -- -- Minimal complete definition: either == or /=. class Eq a (==) :: Eq a => a -> a -> Bool (/=) :: Eq a => a -> a -> Bool -- | This data type represents an equivalence relation. -- -- Equivalence relations are expected to satisfy three laws: -- -- Reflexivity: -- --
--   getEquivalence f a a = True
--   
-- -- Symmetry: -- --
--   getEquivalence f a b = getEquivalence f b a
--   
-- -- Transitivity: -- -- If getEquivalence f a b and getEquivalence -- f b c are both True then so is getEquivalence f -- a c -- -- The types alone do not enforce these laws, so you'll have to check -- them yourself. newtype Equivalence a Equivalence :: a -> a -> Bool -> Equivalence a [getEquivalence] :: Equivalence a -> a -> a -> Bool -- | Check for equivalence with == -- -- Note: The instances for Double and Float violate -- reflexivity for NaN. defaultEquivalence :: Eq a => Equivalence a comparisonEquivalence :: () => Comparison a -> Equivalence a -- | Lifting of the Eq class to unary type constructors. class Eq1 (f :: * -> *) -- | Lift an equality test through the type constructor. -- -- The function will usually be applied to an equality function, but the -- more general type ensures that the implementation uses it to compare -- elements of the first container with elements of the second. liftEq :: Eq1 f => a -> b -> Bool -> f a -> f b -> Bool -- | Lift the standard (==) function through the type -- constructor. eq1 :: (Eq1 f, Eq a) => f a -> f a -> Bool -- | A sensible default liftEq implementation for Generic1 -- instances. liftEqDefault :: (GEq1 NonV4 Rep1 f, Generic1 f) => a -> b -> Bool -> f a -> f b -> Bool -- | Lifting of the Eq class to binary type constructors. class Eq2 (f :: * -> * -> *) -- | Lift equality tests through the type constructor. -- -- The function will usually be applied to equality functions, but the -- more general type ensures that the implementation uses them to compare -- elements of the first container with elements of the second. liftEq2 :: Eq2 f => a -> b -> Bool -> c -> d -> Bool -> f a c -> f b d -> Bool -- | Lift the standard (==) function through the type -- constructor. eq2 :: (Eq2 f, Eq a, Eq b) => f a b -> f a b -> Bool -- | Propositional equality. If a :~: b is inhabited by some -- terminating value, then the type a is the same as the type -- b. To use this equality in practice, pattern-match on the -- a :~: b to get out the Refl constructor; in the body -- of the pattern-match, the compiler knows that a ~ b. data (:~:) (a :: k) (b :: k) :: forall k. () => k -> k -> * [Refl] :: a :~: a -- | Kind heterogeneous propositional equality. Like :~:, a :~~: -- b is inhabited by a terminating value if and only if a -- is the same type as b. data (:~~:) (a :: k1) (b :: k2) :: forall k1 k2. () => k1 -> k2 -> * [HRefl] :: a :~~: a -- | Symmetry of equality sym :: () => a :~: b -> b :~: a -- | Transitivity of equality trans :: () => a :~: b -> b :~: c -> a :~: c -- | Type-safe cast, using propositional equality castWith :: () => a :~: b -> a -> b -- | Generalized form of type-safe cast using propositional equality gcastWith :: () => a :~: b -> a ~ b -> r -> r -- | Apply one equality to another, respectively apply :: () => f :~: g -> a :~: b -> f a :~: g b -- | Extract equality of the arguments from an equality of applied types inner :: () => f a :~: g b -> a :~: b -- | Extract equality of type constructors from an equality of applied -- types outer :: () => f a :~: g b -> f :~: g -- | This class contains types where you can learn the equality of two -- types from information contained in terms. Typically, only -- singleton types should inhabit this class. class TestEquality (f :: k -> *) -- | Conditionally prove the equality of a and b. testEquality :: TestEquality f => f a -> f b -> Maybe a :~: b -- | A type family to compute Boolean equality. module Error -- | error stops execution and displays an error message. error :: HasCallStack => [Char] -> a -- | A variant of error that does not produce a stack trace. errorWithoutStackTrace :: () => [Char] -> a -- | A special case of error. It is expected that compilers will -- recognize this and insert error messages which are more appropriate to -- the context in which undefined appears. undefined :: HasCallStack => a -- | Throw an exception. Exceptions may be thrown from purely functional -- code, but may only be caught within the IO monad. throw :: Exception e => e -> a -- | If the first argument evaluates to True, then the result is the -- second argument. Otherwise an AssertionFailed exception is -- raised, containing a String with the source file and line -- number of the call to assert. -- -- Assertions can normally be turned on or off with a compiler flag (for -- GHC, assertions are normally on unless optimisation is turned on with -- -O or the -fignore-asserts option is given). When -- assertions are turned off, the first argument to assert is -- ignored, and the second argument is returned as the result. assert :: () => Bool -> a -> a module Eval -- | The value of seq a b is bottom if a is bottom, and -- otherwise equal to b. In other words, it evaluates the first -- argument a to weak head normal form (WHNF). seq is -- usually introduced to improve performance by avoiding unneeded -- laziness. -- -- A note on evaluation order: the expression seq a b does -- not guarantee that a will be evaluated before -- b. The only guarantee given by seq is that the both -- a and b will be evaluated before seq -- returns a value. In particular, this means that b may be -- evaluated before a. If you need to guarantee a specific order -- of evaluation, you must use the function pseq from the -- "parallel" package. seq :: () => a -> b -> b -- | The lazy function restrains strictness analysis a little. The -- call lazy e means the same as e, but lazy has -- a magical property so far as strictness analysis is concerned: it is -- lazy in its first argument, even though its semantics is strict. After -- strictness analysis has run, calls to lazy are inlined to be -- the identity function. -- -- This behaviour is occasionally useful when controlling evaluation -- order. Notably, lazy is used in the library definition of -- par: -- --
--   par :: a -> b -> b
--   par x y = case (par# x) of _ -> lazy y
--   
-- -- If lazy were not lazy, par would look strict in -- y which would defeat the whole purpose of par. -- -- Like seq, the argument of lazy can have an unboxed type. lazy :: () => a -> a -- | Strict (call-by-value) application operator. It takes a function and -- an argument, evaluates the argument to weak head normal form (WHNF), -- then calls the function with that value. ($!) :: () => a -> b -> a -> b infixr 0 $! -- | Evaluate the argument to weak head normal form. -- -- evaluate is typically used to uncover any exceptions that a -- lazy value may contain, and possibly handle them. -- -- evaluate only evaluates to weak head normal form. If -- deeper evaluation is needed, the force function from -- Control.DeepSeq may be handy: -- --
--   evaluate $ force x
--   
-- -- There is a subtle difference between evaluate x and -- return $! x, analogous to the difference -- between throwIO and throw. If the lazy value x -- throws an exception, return $! x will fail to -- return an IO action and will throw an exception instead. -- evaluate x, on the other hand, always produces an -- IO action; that action will throw an exception upon -- execution iff x throws an exception upon -- evaluation. -- -- The practical implication of this difference is that due to the -- imprecise exceptions semantics, -- --
--   (return $! error "foo") >> error "bar"
--   
-- -- may throw either "foo" or "bar", depending on the -- optimizations performed by the compiler. On the other hand, -- --
--   evaluate (error "foo") >> error "bar"
--   
-- -- is guaranteed to throw "foo". -- -- The rule of thumb is to use evaluate to force or handle -- exceptions in lazy values. If, on the other hand, you are forcing a -- lazy value for efficiency reasons only and do not care about -- exceptions, you may use return $! x. evaluate :: () => a -> IO a -- | NF is an abstract data type representing data which has been -- evaluated to normal form. Specifically, if a value of type -- NF a is in weak head normal form, then it is in -- reduced normal form; alternatively, it is only necessary to seq -- an NF a to assure that it is fully evaluated. data NF a -- | Creates a value of type NF. The first time the result is -- evaluated to whnf, the value will be rnfed. To avoid this -- rnf, see UnsafeNF. makeNF :: NFData a => a -> NF a -- | Retrieves a from a value of type NF a; this -- value is guaranteed to be in normal form. getNF :: () => NF 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 -> () -- | 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 -- | 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 $!! -- | Deeply strict version of <$>. (<$!!>) :: (Monad m, NFData b) => a -> b -> m a -> m b infixl 4 <$!!> -- | Reduce to weak head normal form -- -- Equivalent to \x -> seq x (). -- -- Useful for defining NFData for types for which NF=WHNF holds. -- --
--   data T = C1 | C2 | C3
--   instance NFData T where rnf = rwhnf
--   
rwhnf :: () => a -> () -- | A class of functors that can be fully evaluated. class NFData1 (f :: * -> *) -- | liftRnf should reduce its argument to normal form (that is, -- fully evaluate all sub-components), given an argument to reduce -- a arguments, and then return '()'. -- -- See rnf for the generic deriving. liftRnf :: NFData1 f => a -> () -> f a -> () -- | Lift the standard rnf function through the type constructor. rnf1 :: (NFData1 f, NFData a) => f a -> () -- | A class of bifunctors that can be fully evaluated. class NFData2 (p :: * -> * -> *) -- | liftRnf2 should reduce its argument to normal form (that is, -- fully evaluate all sub-components), given functions to reduce -- a and b arguments respectively, and then return -- '()'. -- -- Note: Unlike for the unary liftRnf, there is currently -- no support for generically deriving liftRnf2. liftRnf2 :: NFData2 p => a -> () -> b -> () -> p a b -> () -- | Lift the standard rnf function through the type constructor. rnf2 :: (NFData2 p, NFData a, NFData b) => p a b -> () -- | Eval is a Monad that makes it easier to define parallel -- strategies. It is a strict identity monad: that is, in -- --
--   m >>= f
--   
-- -- m is evaluated before the result is passed to f. -- --
--   instance Monad Eval where
--     return  = Done
--     m >>= k = case m of
--                 Done x -> k x
--   
-- -- If you wanted to construct a Strategy for a pair that sparked -- the first component in parallel and then evaluated the second -- component, you could write -- --
--   myStrat :: Strategy (a,b)
--   myStrat (a,b) = do { a' <- rpar a; b' <- rseq b; return (a',b') }
--   
-- -- Alternatively, you could write this more compactly using the -- Applicative style as -- --
--   myStrat (a,b) = (,) <$> rpar a <*> rseq b
--   
data Eval a -- | Pull the result out of the monad. runEval :: () => Eval a -> a -- | A Strategy is a function that embodies a parallel evaluation -- strategy. The function traverses (parts of) its argument, evaluating -- subexpressions in parallel or in sequence. -- -- A Strategy may do an arbitrary amount of evaluation of its -- argument, but should not return a value different from the one it was -- passed. -- -- Parallel computations may be discarded by the runtime system if the -- program no longer requires their result, which is why a -- Strategy function returns a new value equivalent to the old -- value. The intention is that the program applies the Strategy -- to a structure, and then uses the returned value, discarding the old -- value. This idiom is expressed by the using function. type Strategy a = a -> Eval a -- | Evaluate a value using the given Strategy. -- --
--   x `using` s = runEval (s x)
--   
using :: () => a -> Strategy a -> a infixl 0 `using` -- | evaluate a value using the given Strategy. This is simply -- using with the arguments reversed. withStrategy :: () => Strategy a -> a -> a -- | Compose two strategies sequentially. This is the analogue to function -- composition on strategies. -- -- For any strategies strat1, strat2, and -- strat3, -- --
--   (strat1 `dot` strat2) `dot` strat3 == strat1 `dot` (strat2 `dot` strat3)
--   strat1 `dot` strat1 = strat1
--   strat1 `dot` r0 == strat1
--   
-- --
--   strat2 `dot` strat1 == strat2 . withStrategy strat1
--   
dot :: () => Strategy a -> Strategy a -> Strategy a infixr 9 `dot` -- | rseq evaluates its argument to weak head normal form. -- --
--   rseq == evalSeq Control.Seq.rseq
--   
rseq :: () => Strategy a -- | rdeepseq fully evaluates its argument. -- --
--   rdeepseq == evalSeq Control.Seq.rdeepseq
--   
rdeepseq :: NFData a => Strategy a -- | Evaluate the elements of a traversable data structure according to the -- given strategy. evalTraversable :: Traversable t => Strategy a -> Strategy t a -- | Evaluate each element of a list according to the given strategy. -- Equivalent to evalTraversable at the list type. evalList :: () => Strategy a -> Strategy [a] evalTuple2 :: () => Strategy a -> Strategy b -> Strategy (a, b) evalTuple3 :: () => Strategy a -> Strategy b -> Strategy c -> Strategy (a, b, c) evalTuple4 :: () => Strategy a -> Strategy b -> Strategy c -> Strategy d -> Strategy (a, b, c, d) evalTuple5 :: () => Strategy a -> Strategy b -> Strategy c -> Strategy d -> Strategy e -> Strategy (a, b, c, d, e) evalTuple6 :: () => Strategy a -> Strategy b -> Strategy c -> Strategy d -> Strategy e -> Strategy f -> Strategy (a, b, c, d, e, f) evalTuple7 :: () => Strategy a -> Strategy b -> Strategy c -> Strategy d -> Strategy e -> Strategy f -> Strategy g -> Strategy (a, b, c, d, e, f, g) evalTuple8 :: () => Strategy a -> Strategy b -> Strategy c -> Strategy d -> Strategy e -> Strategy f -> Strategy g -> Strategy h -> Strategy (a, b, c, d, e, f, g, h) evalTuple9 :: () => Strategy a -> Strategy b -> Strategy c -> Strategy d -> Strategy e -> Strategy f -> Strategy g -> Strategy h -> Strategy i -> Strategy (a, b, c, d, e, f, g, h, i) module Except -- | 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 :: * -> *) a ExceptT :: m Either e a -> ExceptT e a -- | The inverse of ExceptT. runExceptT :: () => ExceptT e m a -> m Either e a -- | Map the unwrapped computation using the given function. -- -- mapExceptT :: () => m Either e a -> n Either e' b -> ExceptT e m a -> ExceptT e' n b -- | Transform any exceptions thrown by the computation using the given -- function. withExceptT :: Functor m => e -> e' -> ExceptT e m a -> ExceptT e' m a -- | The strategy of combining computations that can throw exceptions by -- bypassing bound functions from the point an exception is thrown to the -- point that it is handled. -- -- Is parameterized over the type of error information and the monad type -- constructor. It is common to use Either String as the -- monad type constructor for an error monad in which error descriptions -- take the form of strings. In that case and many other common cases the -- resulting monad is already defined as an instance of the -- MonadError class. You can also define your own error type -- and/or use a monad type constructor other than Either -- String or Either IOError. In -- these cases you will have to explicitly define instances of the -- MonadError class. (If you are using the deprecated -- Control.Monad.Error or Control.Monad.Trans.Error, you -- may also have to define an Error instance.) class Monad m => MonadError e (m :: * -> *) | m -> e -- | Is used within a monadic computation to begin exception processing. throwError :: MonadError e m => e -> m a -- | A handler function to handle previous errors and return to normal -- execution. A common idiom is: -- --
--   do { action1; action2; action3 } `catchError` handler
--   
-- -- where the action functions can call throwError. Note -- that handler and the do-block must have the same return type. catchError :: MonadError e m => m a -> e -> m a -> m a -- | Lifts an Either e into any MonadError -- e. -- --
--   do { val <- liftEither =<< action1; action2 }
--   
-- -- where action1 returns an Either to represent errors. liftEither :: MonadError e m => Either e a -> m a module Exception -- | Synchronously throw the given exception. throwIO :: (MonadIO m, Exception e) => e -> m 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 :: * -> *) -- | Throw an exception. Note that this throws when this action is run in -- the monad m, not when it is applied. It is a generalization -- of Control.Exception's throwIO. -- -- Should satisfy the law: -- --
--   throwM e >> f = throwM e
--   
throwM :: (MonadThrow m, Exception e) => e -> m a -- | Raise an IOError in the IO monad. ioError :: () => IOError -> IO a -- | Construct an IOError value with a string describing the error. -- The fail method of the IO instance of the Monad -- class raises a userError, thus: -- --
--   instance Monad IO where
--     ...
--     fail s = ioError (userError s)
--   
userError :: String -> IOError -- | Computation exitWith code throws ExitCode -- code. Normally this terminates the program, returning -- code to the program's caller. -- -- On program termination, the standard Handles stdout and -- stderr are flushed automatically; any other buffered -- Handles need to be flushed manually, otherwise the buffered -- data will be discarded. -- -- A program that fails in any other way is treated as if it had called -- exitFailure. A program that terminates successfully without -- calling exitWith explicitly is treated as if it had called -- exitWith ExitSuccess. -- -- As an ExitCode is not an IOError, exitWith -- bypasses the error handling in the IO monad and cannot be -- intercepted by catch from the Prelude. However it is a -- SomeException, and can be caught using the functions of -- Control.Exception. This means that cleanup computations added -- with bracket (from Control.Exception) are also executed -- properly on exitWith. -- -- Note: in GHC, exitWith should be called from the main program -- thread in order to exit the process. When called from another thread, -- exitWith will throw an ExitException as normal, but -- the exception will not cause the process itself to exit. exitWith :: () => ExitCode -> IO a -- | The computation exitFailure is equivalent to exitWith -- (ExitFailure exitfail), where -- exitfail is implementation-dependent. exitFailure :: () => IO a -- | The computation exitSuccess is equivalent to exitWith -- ExitSuccess, It terminates the program successfully. exitSuccess :: () => IO a -- | Write given error message to stderr and terminate with -- exitFailure. die :: () => String -> IO a -- | Unlifted catch, but will not catch asynchronous exceptions. catch :: (MonadUnliftIO m, Exception e) => m a -> e -> m a -> m a -- | catch specialized to catch all synchronous exception. catchAny :: MonadUnliftIO m => m a -> SomeException -> m a -> m a -- | Same as upstream catches, but will not catch asynchronous -- exceptions. catches :: MonadUnliftIO m => m a -> [Handler m a] -> m a -- | Generalized version of Handler. data Handler (m :: * -> *) a [Handler] :: Handler m a -- | catchJust is like catch but it takes an extra argument -- which is an exception predicate, a function which selects which type -- of exceptions we're interested in. catchJust :: (MonadUnliftIO m, Exception e) => e -> Maybe b -> m a -> b -> m a -> m a -- | Flipped version of catch. handle :: (MonadUnliftIO m, Exception e) => e -> m a -> m a -> m a -- | Flipped catchJust. handleJust :: (MonadUnliftIO m, Exception e) => e -> Maybe b -> b -> m a -> m a -> m a -- | Unlifted try, but will not catch asynchronous exceptions. try :: (MonadUnliftIO m, Exception e) => m a -> m Either e a -- | try specialized to catch all synchronous exceptions. tryAny :: MonadUnliftIO m => m a -> m Either SomeException a -- | A variant of try that takes an exception predicate to select -- which exceptions are caught. tryJust :: (MonadUnliftIO m, Exception e) => e -> Maybe b -> m a -> m Either b a -- | try specialized to only catching IOExceptions. tryIO :: MonadUnliftIO m => m a -> m Either IOException a -- | Async safe version of bracket. bracket :: MonadUnliftIO m => m a -> a -> m b -> a -> m c -> m c -- | Async safe version of bracket_. bracket_ :: MonadUnliftIO m => m a -> m b -> m c -> m c -- | Async safe version of bracketOnError. bracketOnError :: MonadUnliftIO m => m a -> a -> m b -> a -> m c -> m c -- | Async safe version of finally. finally :: MonadUnliftIO m => m a -> m b -> m a -- | Async safe version of onException. onException :: MonadUnliftIO m => m a -> m b -> m a -- | Describes the behaviour of a thread when an asynchronous exception is -- received. data MaskingState -- | asynchronous exceptions are unmasked (the normal state) Unmasked :: MaskingState -- | the state during mask: asynchronous exceptions are masked, but -- blocking operations may still be interrupted MaskedInterruptible :: MaskingState -- | the state during uninterruptibleMask: asynchronous exceptions -- are masked, and blocking operations may not be interrupted MaskedUninterruptible :: MaskingState -- | Unlifted version of mask. mask :: MonadUnliftIO m => forall a. () => m a -> m a -> m b -> m b -- | Unlifted version of mask_. mask_ :: MonadUnliftIO m => m a -> m a -- | Unlifted version of uninterruptibleMask. uninterruptibleMask :: MonadUnliftIO m => forall a. () => m a -> m a -> m b -> m b -- | Unlifted version of uninterruptibleMask_. uninterruptibleMask_ :: MonadUnliftIO m => m a -> m a -- | Returns the MaskingState for the current thread. getMaskingState :: IO MaskingState -- | Allow asynchronous exceptions to be raised even inside mask, -- making the operation interruptible (see the discussion of -- "Interruptible operations" in Exception). -- -- When called outside mask, or inside uninterruptibleMask, -- this function has no effect. interruptible :: () => IO a -> IO a -- | When invoked inside mask, this function allows a masked -- asynchronous exception to be raised, if one exists. It is equivalent -- to performing an interruptible operation (see #interruptible), but -- does not involve any actual blocking. -- -- When called outside mask, or inside uninterruptibleMask, -- this function has no effect. allowInterrupt :: IO () -- | 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] :: SomeException -- | 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 -- | This function maps one exception into another as proposed in the paper -- "A semantics for imprecise exceptions". mapException :: (Exception e1, Exception e2) => e1 -> e2 -> a -> a -- | Defines the exit codes that a program can return. data ExitCode -- | indicates successful termination; ExitSuccess :: ExitCode -- | indicates program failure with an exit code. The exact interpretation -- of the code is operating-system dependent. In particular, some values -- may be prohibited (e.g. 0 on a POSIX-compliant system). ExitFailure :: Int -> ExitCode -- | Exceptions that occur in the IO monad. An -- IOException records a more specific error type, a descriptive -- string and maybe the handle that was used when the error was flagged. data IOException -- | Superclass for asynchronous exceptions. data SomeAsyncException [SomeAsyncException] :: SomeAsyncException -- | Asynchronous exceptions. data AsyncException -- | The current thread's stack exceeded its limit. Since an exception has -- been raised, the thread's stack will certainly be below its limit -- again, but the programmer should take remedial action immediately. StackOverflow :: AsyncException -- | The program's heap is reaching its limit, and the program should take -- action to reduce the amount of live data it has. Notes: -- -- HeapOverflow :: AsyncException -- | This exception is raised by another thread calling killThread, -- or by the system if it needs to terminate the thread for some reason. ThreadKilled :: AsyncException -- | This exception is raised by default in the main thread of the program -- when the user requests to terminate the program via the usual -- mechanism(s) (e.g. Control-C in the console). UserInterrupt :: AsyncException asyncExceptionToException :: Exception e => e -> SomeException asyncExceptionFromException :: Exception e => SomeException -> Maybe e module FRP module Field -- | Constraint representing the fact that the field x belongs to -- the record type r and has field type a. This will be -- solved automatically, but manual instances may be provided as well. class HasField (x :: k) r a | x r -> a -- | Selector function to extract the field from the record. getField :: HasField x r a => r -> a module File -- | 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 -- | 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 handle managing input from the Haskell program's standard input -- channel. stdin :: Handle -- | A handle managing output to the Haskell program's standard output -- channel. stdout :: Handle -- | A handle managing output to the Haskell program's standard error -- channel. stderr :: Handle -- | Lifted version of hFileSize hFileSize :: MonadIO m => Handle -> m Integer -- | Lifted version of hGetEcho hGetEcho :: MonadIO m => Handle -> m Bool -- | Computation hGetPosn hdl returns the current I/O -- position of hdl as a value of the abstract type -- HandlePosn. hGetPosn :: Handle -> IO HandlePosn -- | Lifted version of hIsClosed hIsClosed :: MonadIO m => Handle -> m Bool -- | Lifted version of hIsEOF hIsEOF :: MonadIO m => Handle -> m Bool -- | Lifted version of hIsOpen hIsOpen :: MonadIO m => Handle -> m Bool -- | Lifted version of hIsReadable hIsReadable :: MonadIO m => Handle -> m Bool -- | Lifted version of hIsSeekable hIsSeekable :: MonadIO m => Handle -> m Bool -- | Lifted version of hIsTerminalDevice hIsTerminalDevice :: MonadIO m => Handle -> m Bool -- | Lifted version of hIsWritable hIsWritable :: MonadIO m => Handle -> m Bool -- | Lifted version of hReady hReady :: MonadIO m => Handle -> m Bool -- | hShow is in the IO monad, and gives more comprehensive -- output than the (pure) instance of Show for Handle. hShow :: Handle -> IO String -- | Lifted version of hTell hTell :: MonadIO m => Handle -> m Integer -- | Lifted version of hWaitForInput hWaitForInput :: MonadIO m => Handle -> Int -> m Bool -- | Lifted version of hClose hClose :: MonadIO m => Handle -> m () -- | Lifted version of hFlush hFlush :: MonadIO m => Handle -> m () -- | Lifted version of hSeek hSeek :: MonadIO m => Handle -> SeekMode -> Integer -> m () -- | Select binary mode (True) or text mode (False) on a open -- handle. (See also openBinaryFile.) -- -- This has the same effect as calling hSetEncoding with -- char8, together with hSetNewlineMode with -- noNewlineTranslation. hSetBinaryMode :: Handle -> Bool -> IO () -- | Lifted version of hSetBuffering hSetBuffering :: MonadIO m => Handle -> BufferMode -> m () -- | Lifted version of hSetEcho hSetEcho :: MonadIO m => Handle -> Bool -> m () -- | Lifted version of hSetFileSize hSetFileSize :: MonadIO m => Handle -> Integer -> m () -- | If a call to hGetPosn hdl returns a position -- p, then computation hSetPosn p sets the -- position of hdl to the position it held at the time of the -- call to hGetPosn. -- -- This operation may fail with: -- -- hSetPosn :: HandlePosn -> IO () -- | Three kinds of buffering are supported: line-buffering, -- block-buffering or no-buffering. These modes have the following -- effects. For output, items are written out, or flushed, from -- the internal buffer according to the buffer mode: -- -- -- -- An implementation is free to flush the buffer more frequently, but not -- less frequently, than specified above. The output buffer is emptied as -- soon as it has been written out. -- -- Similarly, input occurs according to the buffer mode for the handle: -- -- -- -- The default buffering mode when a handle is opened is -- implementation-dependent and may depend on the file system object -- which is attached to that handle. For most implementations, physical -- files will normally be block-buffered and terminals will normally be -- line-buffered. data BufferMode -- | buffering is disabled if possible. NoBuffering :: BufferMode -- | line-buffering should be enabled if possible. LineBuffering :: BufferMode -- | block-buffering should be enabled if possible. The size of the buffer -- is n items if the argument is Just n and is -- otherwise implementation-dependent. BlockBuffering :: Maybe Int -> BufferMode data HandlePosn -- | See openFile data IOMode ReadMode :: IOMode WriteMode :: IOMode AppendMode :: IOMode ReadWriteMode :: IOMode -- | A mode that determines the effect of hSeek hdl mode -- i. data SeekMode -- | the position of hdl is set to i. AbsoluteSeek :: SeekMode -- | the position of hdl is set to offset i from the -- current position. RelativeSeek :: SeekMode -- | the position of hdl is set to offset i from the end -- of the file. SeekFromEnd :: SeekMode -- | Combine two paths with a path separator. If the second path starts -- with a path separator or a drive letter, then it returns the second. -- The intention is that readFile (dir </> file) -- will access the same file as setCurrentDirectory dir; readFile -- file. -- --
--   Posix:   "/directory" </> "file.ext" == "/directory/file.ext"
--   Windows: "/directory" </> "file.ext" == "/directory\\file.ext"
--            "directory" </> "/file.ext" == "/file.ext"
--   Valid x => (takeDirectory x </> takeFileName x) `equalFilePath` x
--   
-- -- Combined: -- --
--   Posix:   "/" </> "test" == "/test"
--   Posix:   "home" </> "bob" == "home/bob"
--   Posix:   "x:" </> "foo" == "x:/foo"
--   Windows: "C:\\foo" </> "bar" == "C:\\foo\\bar"
--   Windows: "home" </> "bob" == "home\\bob"
--   
-- -- Not combined: -- --
--   Posix:   "home" </> "/bob" == "/bob"
--   Windows: "home" </> "C:\\bob" == "C:\\bob"
--   
-- -- Not combined (tricky): -- -- On Windows, if a filepath starts with a single slash, it is relative -- to the root of the current drive. In [1], this is (confusingly) -- referred to as an absolute path. The current behavior of -- </> is to never combine these forms. -- --
--   Windows: "home" </> "/bob" == "/bob"
--   Windows: "home" </> "\\bob" == "\\bob"
--   Windows: "C:\\home" </> "\\bob" == "\\bob"
--   
-- -- On Windows, from [1]: "If a file name begins with only a disk -- designator but not the backslash after the colon, it is interpreted as -- a relative path to the current directory on the drive with the -- specified letter." The current behavior of </> is to -- never combine these forms. -- --
--   Windows: "D:\\foo" </> "C:bar" == "C:bar"
--   Windows: "C:\\foo" </> "C:bar" == "C:bar"
--   
() :: FilePath -> FilePath -> FilePath infixr 5 -- | Contract a filename, based on a relative path. Note that the resulting -- path will never introduce .. paths, as the presence of -- symlinks means ../b may not reach a/b if it starts -- from a/c. For a worked example see this blog post. -- -- The corresponding makeAbsolute function can be found in -- System.Directory. -- --
--            makeRelative "/directory" "/directory/file.ext" == "file.ext"
--            Valid x => makeRelative (takeDirectory x) x `equalFilePath` takeFileName x
--            makeRelative x x == "."
--            Valid x y => equalFilePath x y || (isRelative x && makeRelative y x == x) || equalFilePath (y </> makeRelative y x) x
--   Windows: makeRelative "C:\\Home" "c:\\home\\bob" == "bob"
--   Windows: makeRelative "C:\\Home" "c:/home/bob" == "bob"
--   Windows: makeRelative "C:\\Home" "D:\\Home\\Bob" == "D:\\Home\\Bob"
--   Windows: makeRelative "C:\\Home" "C:Home\\Bob" == "C:Home\\Bob"
--   Windows: makeRelative "/Home" "/home/bob" == "bob"
--   Windows: makeRelative "/" "//" == "//"
--   Posix:   makeRelative "/Home" "/home/bob" == "/home/bob"
--   Posix:   makeRelative "/home/" "/home/bob/foo/bar" == "bob/foo/bar"
--   Posix:   makeRelative "/fred" "bob" == "bob"
--   Posix:   makeRelative "/file/test" "/file/test/fred" == "fred"
--   Posix:   makeRelative "/file/test" "/file/test/fred/" == "fred/"
--   Posix:   makeRelative "some/path" "some/path/a/b/c" == "a/b/c"
--   
makeRelative :: FilePath -> FilePath -> FilePath -- | Remove any trailing path separators -- --
--   dropTrailingPathSeparator "file/test/" == "file/test"
--             dropTrailingPathSeparator "/" == "/"
--   Windows:  dropTrailingPathSeparator "\\" == "\\"
--   Posix:    not (hasTrailingPathSeparator (dropTrailingPathSeparator x)) || isDrive x
--   
dropTrailingPathSeparator :: FilePath -> FilePath -- | Normalise a file -- -- -- --
--   Posix:   normalise "/file/\\test////" == "/file/\\test/"
--   Posix:   normalise "/file/./test" == "/file/test"
--   Posix:   normalise "/test/file/../bob/fred/" == "/test/file/../bob/fred/"
--   Posix:   normalise "../bob/fred/" == "../bob/fred/"
--   Posix:   normalise "./bob/fred/" == "bob/fred/"
--   Windows: normalise "c:\\file/bob\\" == "C:\\file\\bob\\"
--   Windows: normalise "c:\\" == "C:\\"
--   Windows: normalise "C:.\\" == "C:"
--   Windows: normalise "\\\\server\\test" == "\\\\server\\test"
--   Windows: normalise "//server/test" == "\\\\server\\test"
--   Windows: normalise "c:/file" == "C:\\file"
--   Windows: normalise "/file" == "\\file"
--   Windows: normalise "\\" == "\\"
--   Windows: normalise "/./" == "\\"
--            normalise "." == "."
--   Posix:   normalise "./" == "./"
--   Posix:   normalise "./." == "./"
--   Posix:   normalise "/./" == "/"
--   Posix:   normalise "/" == "/"
--   Posix:   normalise "bob/fred/." == "bob/fred/"
--   Posix:   normalise "//home" == "/home"
--   
normalise :: FilePath -> FilePath -- |
--   not . isRelative
--   
-- --
--   isAbsolute x == not (isRelative x)
--   
isAbsolute :: FilePath -> Bool -- | Is a path relative, or is it fixed to the root? -- --
--   Windows: isRelative "path\\test" == True
--   Windows: isRelative "c:\\test" == False
--   Windows: isRelative "c:test" == True
--   Windows: isRelative "c:\\" == False
--   Windows: isRelative "c:/" == False
--   Windows: isRelative "c:" == True
--   Windows: isRelative "\\\\foo" == False
--   Windows: isRelative "\\\\?\\foo" == False
--   Windows: isRelative "\\\\?\\UNC\\foo" == False
--   Windows: isRelative "/foo" == True
--   Windows: isRelative "\\foo" == True
--   Posix:   isRelative "test/path" == True
--   Posix:   isRelative "/test" == False
--   Posix:   isRelative "/" == False
--   
-- -- According to [1]: -- -- isRelative :: FilePath -> Bool -- | Take a FilePath and make it valid; does not change already valid -- FilePaths. -- --
--   isValid (makeValid x)
--   isValid x ==> makeValid x == x
--   makeValid "" == "_"
--   makeValid "file\0name" == "file_name"
--   Windows: makeValid "c:\\already\\/valid" == "c:\\already\\/valid"
--   Windows: makeValid "c:\\test:of_test" == "c:\\test_of_test"
--   Windows: makeValid "test*" == "test_"
--   Windows: makeValid "c:\\test\\nul" == "c:\\test\\nul_"
--   Windows: makeValid "c:\\test\\prn.txt" == "c:\\test\\prn_.txt"
--   Windows: makeValid "c:\\test/prn.txt" == "c:\\test/prn_.txt"
--   Windows: makeValid "c:\\nul\\file" == "c:\\nul_\\file"
--   Windows: makeValid "\\\\\\foo" == "\\\\drive"
--   Windows: makeValid "\\\\?\\D:file" == "\\\\?\\D:\\file"
--   Windows: makeValid "nul .txt" == "nul _.txt"
--   
makeValid :: FilePath -> FilePath -- | Is a FilePath valid, i.e. could you create a file like it? This -- function checks for invalid names, and invalid characters, but does -- not check if length limits are exceeded, as these are typically -- filesystem dependent. -- --
--            isValid "" == False
--            isValid "\0" == False
--   Posix:   isValid "/random_ path:*" == True
--   Posix:   isValid x == not (null x)
--   Windows: isValid "c:\\test" == True
--   Windows: isValid "c:\\test:of_test" == False
--   Windows: isValid "test*" == False
--   Windows: isValid "c:\\test\\nul" == False
--   Windows: isValid "c:\\test\\prn.txt" == False
--   Windows: isValid "c:\\nul\\file" == False
--   Windows: isValid "\\\\" == False
--   Windows: isValid "\\\\\\foo" == False
--   Windows: isValid "\\\\?\\D:file" == False
--   Windows: isValid "foo\tbar" == False
--   Windows: isValid "nul .txt" == False
--   Windows: isValid " nul.txt" == True
--   
isValid :: FilePath -> Bool -- | Equality of two FilePaths. If you call -- System.Directory.canonicalizePath first this has a much -- better chance of working. Note that this doesn't follow symlinks or -- DOSNAM~1s. -- --
--            x == y ==> equalFilePath x y
--            normalise x == normalise y ==> equalFilePath x y
--            equalFilePath "foo" "foo/"
--            not (equalFilePath "foo" "/foo")
--   Posix:   not (equalFilePath "foo" "FOO")
--   Windows: equalFilePath "foo" "FOO"
--   Windows: not (equalFilePath "C:" "C:/")
--   
equalFilePath :: FilePath -> FilePath -> Bool -- | Join path elements back together. -- --
--   joinPath ["/","directory/","file.ext"] == "/directory/file.ext"
--   Valid x => joinPath (splitPath x) == x
--   joinPath [] == ""
--   Posix: joinPath ["test","file","path"] == "test/file/path"
--   
joinPath :: [FilePath] -> FilePath -- | Just as splitPath, but don't add the trailing slashes to each -- element. -- --
--            splitDirectories "/directory/file.ext" == ["/","directory","file.ext"]
--            splitDirectories "test/file" == ["test","file"]
--            splitDirectories "/test/file" == ["/","test","file"]
--   Windows: splitDirectories "C:\\test\\file" == ["C:\\", "test", "file"]
--            Valid x => joinPath (splitDirectories x) `equalFilePath` x
--            splitDirectories "" == []
--   Windows: splitDirectories "C:\\test\\\\\\file" == ["C:\\", "test", "file"]
--            splitDirectories "/test///file" == ["/","test","file"]
--   
splitDirectories :: FilePath -> [FilePath] -- | Split a path by the directory separator. -- --
--   splitPath "/directory/file.ext" == ["/","directory/","file.ext"]
--   concat (splitPath x) == x
--   splitPath "test//item/" == ["test//","item/"]
--   splitPath "test/item/file" == ["test/","item/","file"]
--   splitPath "" == []
--   Windows: splitPath "c:\\test\\path" == ["c:\\","test\\","path"]
--   Posix:   splitPath "/file/test" == ["/","file/","test"]
--   
splitPath :: FilePath -> [FilePath] -- | An alias for </>. combine :: FilePath -> FilePath -> FilePath -- | Set the directory, keeping the filename the same. -- --
--   replaceDirectory "root/file.ext" "/directory/" == "/directory/file.ext"
--   Valid x => replaceDirectory x (takeDirectory x) `equalFilePath` x
--   
replaceDirectory :: FilePath -> String -> FilePath -- | Get the directory name, move up one level. -- --
--             takeDirectory "/directory/other.ext" == "/directory"
--             takeDirectory x `isPrefixOf` x || takeDirectory x == "."
--             takeDirectory "foo" == "."
--             takeDirectory "/" == "/"
--             takeDirectory "/foo" == "/"
--             takeDirectory "/foo/bar/baz" == "/foo/bar"
--             takeDirectory "/foo/bar/baz/" == "/foo/bar/baz"
--             takeDirectory "foo/bar/baz" == "foo/bar"
--   Windows:  takeDirectory "foo\\bar" == "foo"
--   Windows:  takeDirectory "foo\\bar\\\\" == "foo\\bar"
--   Windows:  takeDirectory "C:\\" == "C:\\"
--   
takeDirectory :: FilePath -> FilePath -- | Add a trailing file path separator if one is not already present. -- --
--   hasTrailingPathSeparator (addTrailingPathSeparator x)
--   hasTrailingPathSeparator x ==> addTrailingPathSeparator x == x
--   Posix:    addTrailingPathSeparator "test/rest" == "test/rest/"
--   
addTrailingPathSeparator :: FilePath -> FilePath -- | Is an item either a directory or the last character a path separator? -- --
--   hasTrailingPathSeparator "test" == False
--   hasTrailingPathSeparator "test/" == True
--   
hasTrailingPathSeparator :: FilePath -> Bool -- | Set the base name. -- --
--   replaceBaseName "/directory/other.ext" "file" == "/directory/file.ext"
--   replaceBaseName "file/test.txt" "bob" == "file/bob.txt"
--   replaceBaseName "fred" "bill" == "bill"
--   replaceBaseName "/dave/fred/bob.gz.tar" "new" == "/dave/fred/new.tar"
--   Valid x => replaceBaseName x (takeBaseName x) == x
--   
replaceBaseName :: FilePath -> String -> FilePath -- | Get the base name, without an extension or path. -- --
--   takeBaseName "/directory/file.ext" == "file"
--   takeBaseName "file/test.txt" == "test"
--   takeBaseName "dave.ext" == "dave"
--   takeBaseName "" == ""
--   takeBaseName "test" == "test"
--   takeBaseName (addTrailingPathSeparator x) == ""
--   takeBaseName "file/file.tar.gz" == "file.tar"
--   
takeBaseName :: FilePath -> String -- | Get the file name. -- --
--   takeFileName "/directory/file.ext" == "file.ext"
--   takeFileName "test/" == ""
--   takeFileName x `isSuffixOf` x
--   takeFileName x == snd (splitFileName x)
--   Valid x => takeFileName (replaceFileName x "fred") == "fred"
--   Valid x => takeFileName (x </> "fred") == "fred"
--   Valid x => isRelative (takeFileName x)
--   
takeFileName :: FilePath -> FilePath -- | Drop the filename. Unlike takeDirectory, this function will -- leave a trailing path separator on the directory. -- --
--   dropFileName "/directory/file.ext" == "/directory/"
--   dropFileName x == fst (splitFileName x)
--   
dropFileName :: FilePath -> FilePath -- | Set the filename. -- --
--   replaceFileName "/directory/other.txt" "file.ext" == "/directory/file.ext"
--   Valid x => replaceFileName x (takeFileName x) == x
--   
replaceFileName :: FilePath -> String -> FilePath -- | Split a filename into directory and file. </> is the -- inverse. The first component will often end with a trailing slash. -- --
--   splitFileName "/directory/file.ext" == ("/directory/","file.ext")
--   Valid x => uncurry (</>) (splitFileName x) == x || fst (splitFileName x) == "./"
--   Valid x => isValid (fst (splitFileName x))
--   splitFileName "file/bob.txt" == ("file/", "bob.txt")
--   splitFileName "file/" == ("file/", "")
--   splitFileName "bob" == ("./", "bob")
--   Posix:   splitFileName "/" == ("/","")
--   Windows: splitFileName "c:" == ("c:","")
--   
splitFileName :: FilePath -> (String, String) -- | Is an element a drive -- --
--   Posix:   isDrive "/" == True
--   Posix:   isDrive "/foo" == False
--   Windows: isDrive "C:\\" == True
--   Windows: isDrive "C:\\foo" == False
--            isDrive "" == False
--   
isDrive :: FilePath -> Bool -- | Does a path have a drive. -- --
--   not (hasDrive x) == null (takeDrive x)
--   Posix:   hasDrive "/foo" == True
--   Windows: hasDrive "C:\\foo" == True
--   Windows: hasDrive "C:foo" == True
--            hasDrive "foo" == False
--            hasDrive "" == False
--   
hasDrive :: FilePath -> Bool -- | Delete the drive, if it exists. -- --
--   dropDrive x == snd (splitDrive x)
--   
dropDrive :: FilePath -> FilePath -- | Get the drive from a filepath. -- --
--   takeDrive x == fst (splitDrive x)
--   
takeDrive :: FilePath -> FilePath -- | Join a drive and the rest of the path. -- --
--   Valid x => uncurry joinDrive (splitDrive x) == x
--   Windows: joinDrive "C:" "foo" == "C:foo"
--   Windows: joinDrive "C:\\" "bar" == "C:\\bar"
--   Windows: joinDrive "\\\\share" "foo" == "\\\\share\\foo"
--   Windows: joinDrive "/:" "foo" == "/:\\foo"
--   
joinDrive :: FilePath -> FilePath -> FilePath -- | Split a path into a drive and a path. On Posix, / is a Drive. -- --
--   uncurry (++) (splitDrive x) == x
--   Windows: splitDrive "file" == ("","file")
--   Windows: splitDrive "c:/file" == ("c:/","file")
--   Windows: splitDrive "c:\\file" == ("c:\\","file")
--   Windows: splitDrive "\\\\shared\\test" == ("\\\\shared\\","test")
--   Windows: splitDrive "\\\\shared" == ("\\\\shared","")
--   Windows: splitDrive "\\\\?\\UNC\\shared\\file" == ("\\\\?\\UNC\\shared\\","file")
--   Windows: splitDrive "\\\\?\\UNCshared\\file" == ("\\\\?\\","UNCshared\\file")
--   Windows: splitDrive "\\\\?\\d:\\file" == ("\\\\?\\d:\\","file")
--   Windows: splitDrive "/d" == ("","/d")
--   Posix:   splitDrive "/test" == ("/","test")
--   Posix:   splitDrive "//test" == ("//","test")
--   Posix:   splitDrive "test/file" == ("","test/file")
--   Posix:   splitDrive "file" == ("","file")
--   
splitDrive :: FilePath -> (FilePath, FilePath) -- | Replace all extensions of a file with a new extension. Note that -- replaceExtension and addExtension both work for adding -- multiple extensions, so only required when you need to drop all -- extensions first. -- --
--   replaceExtensions "file.fred.bob" "txt" == "file.txt"
--   replaceExtensions "file.fred.bob" "tar.gz" == "file.tar.gz"
--   
replaceExtensions :: FilePath -> String -> FilePath -- | Get all extensions. -- --
--   takeExtensions "/directory/path.ext" == ".ext"
--   takeExtensions "file.tar.gz" == ".tar.gz"
--   
takeExtensions :: FilePath -> String -- | Drop all extensions. -- --
--   dropExtensions "/directory/path.ext" == "/directory/path"
--   dropExtensions "file.tar.gz" == "file"
--   not $ hasExtension $ dropExtensions x
--   not $ any isExtSeparator $ takeFileName $ dropExtensions x
--   
dropExtensions :: FilePath -> FilePath -- | Split on all extensions. -- --
--   splitExtensions "/directory/path.ext" == ("/directory/path",".ext")
--   splitExtensions "file.tar.gz" == ("file",".tar.gz")
--   uncurry (++) (splitExtensions x) == x
--   Valid x => uncurry addExtension (splitExtensions x) == x
--   splitExtensions "file.tar.gz" == ("file",".tar.gz")
--   
splitExtensions :: FilePath -> (FilePath, String) -- | Drop the given extension from a FilePath, and the "." -- preceding it. Returns Nothing if the FilePath does not have the -- given extension, or Just and the part before the extension if -- it does. -- -- This function can be more predictable than dropExtensions, -- especially if the filename might itself contain . characters. -- --
--   stripExtension "hs.o" "foo.x.hs.o" == Just "foo.x"
--   stripExtension "hi.o" "foo.x.hs.o" == Nothing
--   dropExtension x == fromJust (stripExtension (takeExtension x) x)
--   dropExtensions x == fromJust (stripExtension (takeExtensions x) x)
--   stripExtension ".c.d" "a.b.c.d"  == Just "a.b"
--   stripExtension ".c.d" "a.b..c.d" == Just "a.b."
--   stripExtension "baz"  "foo.bar"  == Nothing
--   stripExtension "bar"  "foobar"   == Nothing
--   stripExtension ""     x          == Just x
--   
stripExtension :: String -> FilePath -> Maybe FilePath -- | Does the given filename have the specified extension? -- --
--   "png" `isExtensionOf` "/directory/file.png" == True
--   ".png" `isExtensionOf` "/directory/file.png" == True
--   ".tar.gz" `isExtensionOf` "bar/foo.tar.gz" == True
--   "ar.gz" `isExtensionOf` "bar/foo.tar.gz" == False
--   "png" `isExtensionOf` "/directory/file.png.jpg" == False
--   "csv/table.csv" `isExtensionOf` "/data/csv/table.csv" == False
--   
isExtensionOf :: String -> FilePath -> Bool -- | Does the given filename have an extension? -- --
--   hasExtension "/directory/path.ext" == True
--   hasExtension "/directory/path" == False
--   null (takeExtension x) == not (hasExtension x)
--   
hasExtension :: FilePath -> Bool -- | Add an extension, even if there is already one there, equivalent to -- <.>. -- --
--   addExtension "/directory/path" "ext" == "/directory/path.ext"
--   addExtension "file.txt" "bib" == "file.txt.bib"
--   addExtension "file." ".bib" == "file..bib"
--   addExtension "file" ".bib" == "file.bib"
--   addExtension "/" "x" == "/.x"
--   addExtension x "" == x
--   Valid x => takeFileName (addExtension (addTrailingPathSeparator x) "ext") == ".ext"
--   Windows: addExtension "\\\\share" ".txt" == "\\\\share\\.txt"
--   
addExtension :: FilePath -> String -> FilePath -- | Remove last extension, and the "." preceding it. -- --
--   dropExtension "/directory/path.ext" == "/directory/path"
--   dropExtension x == fst (splitExtension x)
--   
dropExtension :: FilePath -> FilePath -- | Add an extension, even if there is already one there, equivalent to -- addExtension. -- --
--   "/directory/path" <.> "ext" == "/directory/path.ext"
--   "/directory/path" <.> ".ext" == "/directory/path.ext"
--   
(<.>) :: FilePath -> String -> FilePath infixr 7 <.> -- | Set the extension of a file, overwriting one if already present, -- equivalent to -<.>. -- --
--   replaceExtension "/directory/path.txt" "ext" == "/directory/path.ext"
--   replaceExtension "/directory/path.txt" ".ext" == "/directory/path.ext"
--   replaceExtension "file.txt" ".bob" == "file.bob"
--   replaceExtension "file.txt" "bob" == "file.bob"
--   replaceExtension "file" ".bob" == "file.bob"
--   replaceExtension "file.txt" "" == "file"
--   replaceExtension "file.fred.bob" "txt" == "file.fred.txt"
--   replaceExtension x y == addExtension (dropExtension x) y
--   
replaceExtension :: FilePath -> String -> FilePath -- | Remove the current extension and add another, equivalent to -- replaceExtension. -- --
--   "/directory/path.txt" -<.> "ext" == "/directory/path.ext"
--   "/directory/path.txt" -<.> ".ext" == "/directory/path.ext"
--   "foo.o" -<.> "c" == "foo.c"
--   
(-<.>) :: FilePath -> String -> FilePath infixr 7 -<.> -- | Get the extension of a file, returns "" for no extension, -- .ext otherwise. -- --
--   takeExtension "/directory/path.ext" == ".ext"
--   takeExtension x == snd (splitExtension x)
--   Valid x => takeExtension (addExtension x "ext") == ".ext"
--   Valid x => takeExtension (replaceExtension x "ext") == ".ext"
--   
takeExtension :: FilePath -> String -- | Split on the extension. addExtension is the inverse. -- --
--   splitExtension "/directory/path.ext" == ("/directory/path",".ext")
--   uncurry (++) (splitExtension x) == x
--   Valid x => uncurry addExtension (splitExtension x) == x
--   splitExtension "file.txt" == ("file",".txt")
--   splitExtension "file" == ("file","")
--   splitExtension "file/file.txt" == ("file/file",".txt")
--   splitExtension "file.txt/boris" == ("file.txt/boris","")
--   splitExtension "file.txt/boris.ext" == ("file.txt/boris",".ext")
--   splitExtension "file/path.txt.bob.fred" == ("file/path.txt.bob",".fred")
--   splitExtension "file/path.txt/" == ("file/path.txt/","")
--   
splitExtension :: FilePath -> (String, String) -- | Get a list of FilePaths in the $PATH variable. getSearchPath :: IO [FilePath] -- | Take a string, split it on the searchPathSeparator character. -- Blank items are ignored on Windows, and converted to . on -- Posix. On Windows path elements are stripped of quotes. -- -- Follows the recommendations in -- http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html -- --
--   Posix:   splitSearchPath "File1:File2:File3"  == ["File1","File2","File3"]
--   Posix:   splitSearchPath "File1::File2:File3" == ["File1",".","File2","File3"]
--   Windows: splitSearchPath "File1;File2;File3"  == ["File1","File2","File3"]
--   Windows: splitSearchPath "File1;;File2;File3" == ["File1","File2","File3"]
--   Windows: splitSearchPath "File1;\"File2\";File3" == ["File1","File2","File3"]
--   
splitSearchPath :: String -> [FilePath] -- | Is the character an extension character? -- --
--   isExtSeparator a == (a == extSeparator)
--   
isExtSeparator :: Char -> Bool -- | File extension character -- --
--   extSeparator == '.'
--   
extSeparator :: Char -- | Is the character a file separator? -- --
--   isSearchPathSeparator a == (a == searchPathSeparator)
--   
isSearchPathSeparator :: Char -> Bool -- | The character that is used to separate the entries in the $PATH -- environment variable. -- --
--   Windows: searchPathSeparator == ';'
--   Posix:   searchPathSeparator == ':'
--   
searchPathSeparator :: Char -- | Rather than using (== pathSeparator), use this. Test -- if something is a path separator. -- --
--   isPathSeparator a == (a `elem` pathSeparators)
--   
isPathSeparator :: Char -> Bool -- | The list of all possible separators. -- --
--   Windows: pathSeparators == ['\\', '/']
--   Posix:   pathSeparators == ['/']
--   pathSeparator `elem` pathSeparators
--   
pathSeparators :: [Char] -- | The character that separates directories. In the case where more than -- one character is possible, pathSeparator is the 'ideal' one. -- --
--   Windows: pathSeparator == '\\'
--   Posix:   pathSeparator ==  '/'
--   isPathSeparator pathSeparator
--   
pathSeparator :: Char -- | Binary file handling. module File.Binary -- | Unlifted version of withBinaryFile. withBinaryFile :: MonadUnliftIO m => FilePath -> IOMode -> Handle -> m a -> m a -- | Read an entire file strictly into a ByteString. readFile :: FilePath -> IO ByteString -- | Read the specified file (internally, by reading a -- ByteString) and attempt to decode it into a Haskell -- value using deserialise (the type of which is -- determined by the choice of the result type). -- -- Throws: DeserialiseFailure if the file fails to -- deserialise properly. readFileDeserialise :: Serialise a => FilePath -> IO a -- | Write a ByteString to a file. writeFile :: FilePath -> ByteString -> IO () -- | Serialise a ByteString and write it directly to the -- specified file. writeFileSerialise :: Serialise a => FilePath -> a -> IO () -- | Append a ByteString to a file. appendFile :: FilePath -> ByteString -> IO () -- | getContents. Read stdin strictly. Equivalent to hGetContents stdin The -- Handle is closed after the contents have been read. getContents :: IO ByteString -- | Read a handle's entire contents strictly into a ByteString. -- -- This function reads chunks at a time, increasing the chunk size on -- each read. The final string is then realloced to the appropriate size. -- For files > half of available memory, this may lead to memory -- exhaustion. Consider using readFile in this case. -- -- The Handle is closed once the contents have been read, or if an -- exception is thrown. hGetContents :: Handle -> IO ByteString -- | Read a ByteString directly from the specified Handle. -- This is far more efficient than reading the characters into a -- String and then using pack. First argument is the Handle -- to read from, and the second is the number of bytes to read. It -- returns the bytes read, up to n, or empty if EOF has been -- reached. -- -- hGet is implemented in terms of hGetBuf. -- -- If the handle is a pipe or socket, and the writing end is closed, -- hGet will behave as if EOF was reached. hGet :: Handle -> Int -> IO ByteString -- | Like hGet, except that a shorter ByteString may be -- returned if there are not enough bytes immediately available to -- satisfy the whole request. hGetSome only blocks if there is no -- data available, and EOF has not yet been reached. hGetSome :: Handle -> Int -> IO ByteString -- | hGetNonBlocking is similar to hGet, except that it will never -- block waiting for data to become available, instead it returns only -- whatever data is available. If there is no data available to be read, -- hGetNonBlocking returns empty. -- -- Note: on Windows and with Haskell implementation other than GHC, this -- function does not work correctly; it behaves identically to -- hGet. hGetNonBlocking :: Handle -> Int -> IO ByteString -- | Write a ByteString to stdout putStr :: ByteString -> IO () -- | A synonym for hPut, for compatibility hPutStr :: Handle -> ByteString -> IO () -- | Similar to hPut except that it will never block. Instead it -- returns any tail that did not get written. This tail may be -- empty in the case that the whole string was written, or the -- whole original string if nothing was written. Partial writes are also -- possible. -- -- Note: on Windows and with Haskell implementation other than GHC, this -- function does not work correctly; it behaves identically to -- hPut. hPutNonBlocking :: Handle -> ByteString -> IO ByteString -- | Textual file handling. module File.Text -- | Unlifted version of withFile. withFile :: MonadUnliftIO m => FilePath -> IOMode -> Handle -> m a -> m a -- | Like openFile, but opens the file in ordinary blocking mode. -- This can be useful for opening a FIFO for writing: if we open in -- non-blocking mode then the open will fail if there are no readers, -- whereas a blocking open will block until a reader appear. openFileBlocking :: FilePath -> IOMode -> IO Handle -- | The readFile function reads a file and returns the contents of -- the file as a string. The entire file is read strictly, as with -- getContents. readFile :: FilePath -> IO Text -- | Write a string to a file. The file is truncated to zero length before -- writing begins. writeFile :: FilePath -> Text -> IO () -- | Write a string the end of a file. appendFile :: FilePath -> Text -> IO () -- | Read a character from the standard input device (same as -- hGetChar stdin). getChar :: IO Char -- | Read a single line of user input from stdin. getLine :: IO Text -- | Read all user input on stdin as a single string. getContents :: IO Text -- | Computation hGetChar hdl reads a character from the -- file or channel managed by hdl, blocking until a character is -- available. -- -- This operation may fail with: -- -- hGetChar :: Handle -> IO Char -- | Read a single line from a handle. hGetLine :: Handle -> IO Text -- | Experimental. Read a single chunk of strict text from a -- Handle. The size of the chunk depends on the amount of input -- currently buffered. -- -- This function blocks only if there is no data available, and EOF has -- not yet been reached. Once EOF is reached, this function returns an -- empty string instead of throwing an exception. hGetChunk :: Handle -> IO Text -- | Read the remaining contents of a Handle as a string. The -- Handle is closed once the contents have been read, or if an -- exception is thrown. -- -- Internally, this function reads a chunk at a time from the lower-level -- buffering abstraction, and concatenates the chunks into a single -- string once the entire file has been read. -- -- As a result, it requires approximately twice as much memory as its -- result to construct its result. For files more than a half of -- available RAM in size, this may result in memory exhaustion. hGetContents :: Handle -> IO Text -- | Write a string to stdout. putStr :: Text -> IO () -- | Write a string to stdout, followed by a newline. putStrLn :: Text -> IO () -- | The print function outputs a value of any printable type to the -- standard output device. Printable types are those that are instances -- of class Show; print converts values to strings for -- output using the show operation and adds a newline. -- -- For example, a program to print the first 20 integers and their powers -- of 2 could be written as: -- --
--   main = print ([(n, 2^n) | n <- [0..19]])
--   
print :: Show a => a -> IO () -- | Write a string to a handle. hPutStr :: Handle -> Text -> IO () -- | Write a string to a handle, followed by a newline. hPutStrLn :: Handle -> Text -> IO () -- | Computation hPrint hdl t writes the string -- representation of t given by the shows function to the -- file or channel managed by hdl and appends a newline. -- -- This operation may fail with: -- -- hPrint :: Show a => Handle -> a -> IO () -- | A TextEncoding is a specification of a conversion scheme -- between sequences of bytes and sequences of Unicode characters. -- -- For example, UTF-8 is an encoding of Unicode characters into a -- sequence of bytes. The TextEncoding for UTF-8 is utf8. data TextEncoding -- | The action hSetEncoding hdl encoding changes -- the text encoding for the handle hdl to encoding. -- The default encoding when a Handle is created is -- localeEncoding, namely the default encoding for the current -- locale. -- -- To create a Handle with no encoding at all, use -- openBinaryFile. To stop further encoding or decoding on an -- existing Handle, use hSetBinaryMode. -- -- hSetEncoding may need to flush buffered data in order to change -- the encoding. hSetEncoding :: Handle -> TextEncoding -> IO () -- | Return the current TextEncoding for the specified -- Handle, or Nothing if the Handle is in binary -- mode. -- -- Note that the TextEncoding remembers nothing about the state of -- the encoder/decoder in use on this Handle. For example, if the -- encoding in use is UTF-16, then using hGetEncoding and -- hSetEncoding to save and restore the encoding may result in an -- extra byte-order-mark being written to the file. hGetEncoding :: Handle -> IO Maybe TextEncoding -- | The Latin1 (ISO8859-1) encoding. This encoding maps bytes directly to -- the first 256 Unicode code points, and is thus not a complete Unicode -- encoding. An attempt to write a character greater than '\255' to a -- Handle using the latin1 encoding will result in an -- error. latin1 :: TextEncoding -- | The UTF-8 Unicode encoding utf8 :: TextEncoding -- | The UTF-8 Unicode encoding, with a byte-order-mark (BOM; the byte -- sequence 0xEF 0xBB 0xBF). This encoding behaves like utf8, -- except that on input, the BOM sequence is ignored at the beginning of -- the stream, and on output, the BOM sequence is prepended. -- -- The byte-order-mark is strictly unnecessary in UTF-8, but is sometimes -- used to identify the encoding of a file. utf8_bom :: TextEncoding -- | The UTF-16 Unicode encoding (a byte-order-mark should be used to -- indicate endianness). utf16 :: TextEncoding -- | The UTF-16 Unicode encoding (litte-endian) utf16le :: TextEncoding -- | The UTF-16 Unicode encoding (big-endian) utf16be :: TextEncoding -- | The UTF-32 Unicode encoding (a byte-order-mark should be used to -- indicate endianness). utf32 :: TextEncoding -- | The UTF-32 Unicode encoding (litte-endian) utf32le :: TextEncoding -- | The UTF-32 Unicode encoding (big-endian) utf32be :: TextEncoding module Foldable -- | Data structures that can be folded. -- -- For example, given a data type -- --
--   data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
--   
-- -- a suitable instance would be -- --
--   instance Foldable Tree where
--      foldMap f Empty = mempty
--      foldMap f (Leaf x) = f x
--      foldMap f (Node l k r) = foldMap f l `mappend` f k `mappend` foldMap f r
--   
-- -- This is suitable even for abstract types, as the monoid is assumed to -- satisfy the monoid laws. Alternatively, one could define -- foldr: -- --
--   instance Foldable Tree where
--      foldr f z Empty = z
--      foldr f z (Leaf x) = f x z
--      foldr f z (Node l k r) = foldr f (f k (foldr f z r)) l
--   
-- -- Foldable instances are expected to satisfy the following -- laws: -- --
--   foldr f z t = appEndo (foldMap (Endo . f) t ) z
--   
-- --
--   foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z
--   
-- --
--   fold = foldMap id
--   
-- --
--   length = getSum . foldMap (Sum . const  1)
--   
-- -- sum, product, maximum, and minimum -- should all be essentially equivalent to foldMap forms, such -- as -- --
--   sum = getSum . foldMap Sum
--   
-- -- but may be less defined. -- -- If the type is also a Functor instance, it should satisfy -- --
--   foldMap f = fold . fmap f
--   
-- -- which implies that -- --
--   foldMap f . fmap g = foldMap (f . g)
--   
class Foldable (t :: * -> *) -- | Combine the elements of a structure using a monoid. fold :: (Foldable t, Monoid m) => t m -> m -- | Map each element of the structure to a monoid, and combine the -- results. foldMap :: (Foldable t, Monoid m) => a -> m -> t a -> m -- | Right-associative fold of a structure. -- -- In the case of lists, foldr, when applied to a binary operator, -- a starting value (typically the right-identity of the operator), and a -- list, reduces the list using the binary operator, from right to left: -- --
--   foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)
--   
-- -- Note that, since the head of the resulting expression is produced by -- an application of the operator to the first element of the list, -- foldr can produce a terminating expression from an infinite -- list. -- -- For a general Foldable structure this should be semantically -- identical to, -- --
--   foldr f z = foldr f z . toList
--   
foldr :: Foldable t => a -> b -> b -> b -> t a -> b -- | Right-associative fold of a structure, but with strict application of -- the operator. foldr' :: Foldable t => a -> b -> b -> b -> t a -> b -- | Left-associative fold of a structure but with strict application of -- the operator. -- -- This ensures that each step of the fold is forced to weak head normal -- form before being applied, avoiding the collection of thunks that -- would otherwise occur. This is often what you want to strictly reduce -- a finite list to a single, monolithic result (e.g. length). -- -- For a general Foldable structure this should be semantically -- identical to, -- --
--   foldl f z = foldl' f z . toList
--   
foldl' :: Foldable t => b -> a -> b -> b -> t a -> b -- | List of elements of a structure, from left to right. toList :: Foldable t => t a -> [a] -- | Test whether the structure is empty. The default implementation is -- optimized for structures that are similar to cons-lists, because there -- is no general way to do better. null :: Foldable t => t a -> Bool -- | Returns the size/length of a finite structure as an Int. The -- default implementation is optimized for structures that are similar to -- cons-lists, because there is no general way to do better. length :: Foldable t => t a -> Int -- | Does the element occur in the structure? elem :: (Foldable t, Eq a) => a -> t a -> Bool -- | The sum function computes the sum of the numbers of a -- structure. sum :: (Foldable t, Num a) => t a -> a -- | The product function computes the product of the numbers of a -- structure. product :: (Foldable t, Num a) => t a -> a -- | Monadic fold over the elements of a structure, associating to the -- right, i.e. from right to left. foldrM :: (Foldable t, Monad m) => a -> b -> m b -> b -> t a -> m b -- | Monadic fold over the elements of a structure, associating to the -- left, i.e. from left to right. foldlM :: (Foldable t, Monad m) => b -> a -> m b -> b -> t a -> m b -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and ignore the results. For a version that doesn't -- ignore the results see traverse. traverse_ :: (Foldable t, Applicative f) => a -> f b -> t a -> f () -- | for_ is traverse_ with its arguments flipped. For a -- version that doesn't ignore the results see for. -- --
--   >>> for_ [1..4] print
--   1
--   2
--   3
--   4
--   
for_ :: (Foldable t, Applicative f) => t a -> a -> f b -> f () -- | Evaluate each action in the structure from left to right, and ignore -- the results. For a version that doesn't ignore the results see -- sequenceA. sequenceA_ :: (Foldable t, Applicative f) => t f a -> f () -- | The sum of a collection of actions, generalizing concat. -- -- asum [Just Hello, Nothing, Just World] Just Hello asum :: (Foldable t, Alternative f) => t f a -> f a -- | The sum of a collection of actions, generalizing concat. As of -- base 4.8.0.0, msum is just asum, specialized to -- MonadPlus. msum :: (Foldable t, MonadPlus m) => t m a -> m a -- | Map a function over all the elements of a container and concatenate -- the resulting lists. concatMap :: Foldable t => a -> [b] -> t a -> [b] -- | and returns the conjunction of a container of Bools. For the -- result to be True, the container must be finite; False, -- however, results from a False value finitely far from the left -- end. and :: Foldable t => t Bool -> Bool -- | or returns the disjunction of a container of Bools. For the -- result to be False, the container must be finite; True, -- however, results from a True value finitely far from the left -- end. or :: Foldable t => t Bool -> Bool -- | Determines whether all elements of the structure satisfy the -- predicate. all :: Foldable t => a -> Bool -> t a -> Bool -- | notElem is the negation of elem. notElem :: (Foldable t, Eq a) => a -> t a -> Bool infix 4 `notElem` -- | The find function takes a predicate and a structure and returns -- the leftmost element of the structure matching the predicate, or -- Nothing if there is no such element. find :: Foldable t => a -> Bool -> t a -> Maybe a -- | 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 -- | Like foldM, but discards the result. foldM_ :: (Foldable t, Monad m) => b -> a -> m b -> b -> t a -> m () -- | Fold a value using its Foldable instance using explicitly -- provided Monoid operations. This is like foldMap where -- the Monoid instance can be manually specified. -- --
--   foldMapBy mappend memptyfoldMap
--   
-- --
--   >>> foldMapBy (+) 0 length ["hello","world"]
--   10
--   
foldMapBy :: Foldable t => r -> r -> r -> r -> a -> r -> t a -> r -- | Fold a value using its Foldable instance using explicitly -- provided Monoid operations. This is like fold where -- the Monoid instance can be manually specified. -- --
--   foldBy mappend memptyfold
--   
-- --
--   >>> foldBy (++) [] ["hello","world"]
--   "helloworld"
--   
foldBy :: Foldable t => a -> a -> a -> a -> t a -> a -- | The inits function takes a stream xs and returns all -- the finite prefixes of xs. inits :: Foldable f => f a -> NonEmpty [a] -- | The tails function takes a stream xs and returns all -- the suffixes of xs. tails :: Foldable f => f a -> NonEmpty [a] -- | insert x xs inserts x into the last position -- in xs where it is still less than or equal to the next -- element. In particular, if the list is sorted beforehand, the result -- will also be sorted. insert :: (Foldable f, Ord a) => a -> f a -> NonEmpty a -- | The group function takes a stream and returns a list of streams -- such that flattening the resulting list is equal to the argument. -- Moreover, each stream in the resulting list contains only equal -- elements. For example, in list notation: -- --
--   'group' $ 'cycle' "Mississippi"
--     = "M" : "i" : "ss" : "i" : "ss" : "i" : "pp" : "i" : "M" : "i" : ...
--   
group :: (Foldable f, Eq a) => f a -> [NonEmpty a] -- | groupBy operates like group, but uses the provided -- equality predicate instead of ==. groupBy :: Foldable f => a -> a -> Bool -> f a -> [NonEmpty a] -- | groupWith operates like group, but uses the provided -- projection when comparing for equality groupWith :: (Foldable f, Eq b) => a -> b -> f a -> [NonEmpty a] -- | groupAllWith operates like groupWith, but sorts the list -- first so that each equivalence class has, at most, one list in the -- output groupAllWith :: Ord b => a -> b -> [a] -> [NonEmpty a] class Foldable t => Foldable1 (t :: * -> *) fold1 :: (Foldable1 t, Semigroup m) => t m -> m foldMap1 :: (Foldable1 t, Semigroup m) => a -> m -> t a -> m toNonEmpty :: Foldable1 t => t a -> NonEmpty a asum1 :: (Foldable1 t, Alt m) => t m a -> m a -- | Monadic fold over the elements of a non-empty structure, associating -- to the left, i.e. from left to right. -- --
--   let g = flip $ (=<<) . f
--   in foldlM1 f (x1 :| [x2, ..., xn]) == (...((x1 `f` x2) `g` x2) `g`...) `g` xn
--   
foldlM1 :: (Foldable1 t, Monad m) => a -> a -> m a -> t a -> m a -- | Monadic fold over the elements of a non-empty structure, associating -- to the right, i.e. from right to left. -- --
--   let g = (=<<) . f
--   in foldrM1 f (x1 :| [x2, ..., xn]) == x1 `g` (x2 `g` ... (xn-1 `f` xn)...)
--   
foldrM1 :: (Foldable1 t, Monad m) => a -> a -> m a -> t a -> m a for1_ :: (Foldable1 t, Apply f) => t a -> a -> f b -> f () -- | Insert an m between each pair of 't m'. Equivalent to -- intercalateMap1 with id as the second argument. -- --
--   >>> intercalate1 ", " $ "hello" :| ["how", "are", "you"]
--   "hello, how, are, you"
--   
-- --
--   >>> intercalate1 ", " $ "hello" :| []
--   "hello"
--   
-- --
--   >>> intercalate1 mempty $ "I" :| ["Am", "Fine", "You?"]
--   "IAmFineYou?"
--   
intercalate1 :: (Foldable1 t, Semigroup m) => m -> t m -> m -- | Insert m between each pair of m derived from -- a. -- --
--   >>> intercalateMap1 " " show $ True :| [False, True]
--   "True False True"
--   
-- --
--   >>> intercalateMap1 " " show $ True :| []
--   "True"
--   
intercalateMap1 :: (Foldable1 t, Semigroup m) => m -> a -> m -> t a -> m sequenceA1_ :: (Foldable1 t, Apply f) => t f a -> f () traverse1_ :: (Foldable1 t, Apply f) => a -> f b -> t a -> f () module Foldable.Partial -- | A variant of foldr that has no base case, and thus may only be -- applied to non-empty structures. -- --
--   foldr1 f = foldr1 f . toList
--   
foldr1 :: Foldable t => a -> a -> a -> t a -> a -- | The largest element of a non-empty structure. maximum :: (Foldable t, Ord a) => t a -> a -- | The largest element of a non-empty structure with respect to the given -- comparison function. maximumBy :: Foldable t => a -> a -> Ordering -> t a -> a -- | The least element of a non-empty structure. minimum :: (Foldable t, Ord a) => t a -> a -- | The least element of a non-empty structure with respect to the given -- comparison function. minimumBy :: Foldable t => a -> a -> Ordering -> t a -> a module Foldl module Function -- | 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. ($) :: () => a -> b -> a -> b infixr 0 $ -- | Strict (call-by-value) application operator. It takes a function and -- an argument, evaluates the argument to weak head normal form (WHNF), -- then calls the function with that value. ($!) :: () => a -> b -> a -> b infixr 0 $! -- | & 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 & -- | 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 -- | fix f is the least fixed point of the function -- f, i.e. the least defined x such that f x = -- x. -- -- For example, we can write the factorial function using direct -- recursion as -- --
--   >>> let fac n = if n <= 1 then 1 else n * fac (n-1) in fac 5
--   120
--   
-- -- This uses the fact that Haskell’s let introduces recursive -- bindings. We can rewrite this definition using fix, -- --
--   >>> fix (\rec n -> if n <= 1 then 1 else n * rec (n-1)) 5
--   120
--   
-- -- Instead of making a recursive call, we introduce a dummy parameter -- rec; when used within fix, this parameter then refers -- to fix' argument, hence the recursion is reintroduced. fix :: () => a -> a -> a -- | flip f takes its (first) two arguments in the reverse -- order of f. -- --
--   >>> flip (++) "hello" "world"
--   "worldhello"
--   
flip :: () => a -> b -> c -> b -> a -> c -- | A looping operation, where the predicate returns Left as a seed -- for the next loop or Right to abort the loop. -- --
--   loop (\x -> if x < 10 then Left $ x * 2 else Right $ show x) 1 == "16"
--   
loop :: () => a -> Either a b -> a -> b on :: () => b -> b -> c -> a -> b -> a -> a -> c infixl 0 `on` -- | until p f yields the result of applying f -- until p holds. until :: () => a -> Bool -> a -> a -> 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 -- | Dual function arrows. newtype Op a b Op :: b -> a -> Op a b [getOp] :: Op a b -> b -> a module Functor -- | The Functor class is used for types that can be mapped over. -- Instances of Functor should satisfy the following laws: -- --
--   fmap id  ==  id
--   fmap (f . g)  ==  fmap f . fmap g
--   
-- -- The instances of Functor for lists, Maybe and IO -- satisfy these laws. class Functor (f :: * -> *) 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 -- | An infix synonym for fmap. -- -- The name of this operator is an allusion to $. Note the -- similarities between their types: -- --
--    ($)  ::              (a -> b) ->   a ->   b
--   (<$>) :: Functor f => (a -> b) -> f a -> f b
--   
-- -- Whereas $ is function application, <$> is -- function application lifted over a Functor. -- --

Examples

-- -- Convert from a Maybe Int to a -- Maybe String using show: -- --
--   >>> show <$> Nothing
--   Nothing
--   
--   >>> show <$> Just 3
--   Just "3"
--   
-- -- Convert from an Either Int Int to -- an Either Int String using -- show: -- --
--   >>> show <$> Left 17
--   Left 17
--   
--   >>> show <$> Right 17
--   Right "17"
--   
-- -- Double each element of a list: -- --
--   >>> (*2) <$> [1,2,3]
--   [2,4,6]
--   
-- -- Apply even to the second element of a pair: -- --
--   >>> even <$> (2,2)
--   (2,True)
--   
(<$>) :: Functor f => a -> b -> f a -> f b infixl 4 <$> -- | Flipped version of <$. -- --

Examples

-- -- Replace the contents of a Maybe Int with a -- constant String: -- --
--   >>> Nothing $> "foo"
--   Nothing
--   
--   >>> Just 90210 $> "foo"
--   Just "foo"
--   
-- -- Replace the contents of an Either Int -- Int with a constant String, resulting in an -- Either Int String: -- --
--   >>> Left 8675309 $> "foo"
--   Left 8675309
--   
--   >>> Right 8675309 $> "foo"
--   Right "foo"
--   
-- -- Replace each element of a list with a constant String: -- --
--   >>> [1,2,3] $> "foo"
--   ["foo","foo","foo"]
--   
-- -- Replace the second element of a pair with a constant String: -- --
--   >>> (1,2) $> "foo"
--   (1,"foo")
--   
($>) :: Functor f => f a -> b -> f b infixl 4 $> -- | 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 <&> -- | 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 () -- | The unzip function is the inverse of the zip function. unzip :: Functor f => f (a, b) -> (f a, f b) -- | This Setter can be used to map over all of the values in a -- Functor. -- --
--   fmapover mapped
--   fmapDefaultover traverse
--   (<$) ≡ set mapped
--   
-- --
--   >>> over mapped f [a,b,c]
--   [f a,f b,f c]
--   
-- --
--   >>> over mapped (+1) [1,2,3]
--   [2,3,4]
--   
-- --
--   >>> set mapped x [a,b,c]
--   [x,x,x]
--   
-- --
--   >>> [[a,b],[c]] & mapped.mapped +~ x
--   [[a + x,b + x],[c + x]]
--   
-- --
--   >>> over (mapped._2) length [("hello","world"),("leaders","!!!")]
--   [("hello",5),("leaders",3)]
--   
-- --
--   mapped :: Functor f => Setter (f a) (f b) a b
--   
-- -- If you want an IndexPreservingSetter use setting -- fmap. mapped :: Functor f => Setter f a f b a b -- | A strong lax semi-monoidal endofunctor. This is equivalent to an -- Applicative without pure. -- -- Laws: -- --
--   (.) <$> u <.> v <.> w = u <.> (v <.> w)
--   x <.> (f <$> y) = (. f) <$> x <.> y
--   f <$> (x <.> y) = (f .) <$> x <.> y
--   
-- -- The laws imply that .> and <. really ignore their -- left and right results, respectively, and really return their right -- and left results, respectively. Specifically, -- --
--   (mf <$> m) .> (nf <$> n) = nf <$> (m .> n)
--   (mf <$> m) <. (nf <$> n) = mf <$> (m <. n)
--   
class Functor f => Apply (f :: * -> *) (<.>) :: Apply f => f a -> b -> f a -> f b -- |
--   a .> b = const id <$> a <.> b
--   
(.>) :: Apply f => f a -> f b -> f b -- |
--   a <. b = const <$> a <.> b
--   
(<.) :: Apply f => f a -> f b -> f a -- | Lift a binary function into a comonad with zipping liftF2 :: Apply f => a -> b -> c -> f a -> f b -> f c -- | Lift a ternary function into a comonad with zipping liftF3 :: Apply w => a -> b -> c -> d -> w a -> w b -> w c -> w d -- | Transform a Apply into an Applicative by adding a unit. newtype MaybeApply (f :: * -> *) a MaybeApply :: Either f a a -> MaybeApply a [runMaybeApply] :: MaybeApply a -> Either f a a newtype Static (f :: * -> *) a b Static :: f a -> b -> Static a b [runStatic] :: Static a b -> f a -> b -- | Laws: -- --
--   <!> is associative:             (a <!> b) <!> c = a <!> (b <!> c)
--   <$> left-distributes over <!>:  f <$> (a <!> b) = (f <$> a) <!> (f <$> b)
--   
-- -- If extended to an Alternative then <!> should -- equal <|>. -- -- Ideally, an instance of Alt also satisfies the "left -- distributon" law of MonadPlus with respect to <.>: -- --
--   <.> right-distributes over <!>: (a <!> b) <.> c = (a <.> c) <!> (b <.> c)
--   
-- -- But Maybe, IO, Either a, -- ErrorT e m, and STM satisfy the alternative -- "left catch" law instead: -- --
--   pure a <!> b = pure a
--   
-- -- However, this variation cannot be stated purely in terms of the -- dependencies of Alt. -- -- When and if MonadPlus is successfully refactored, this class should -- also be refactored to remove these instances. -- -- The right distributive law should extend in the cases where the a -- Bind or Monad is provided to yield variations of the -- right distributive law: -- --
--   (m <!> n) >>- f = (m >>- f) <!> (m >>- f)
--   (m <!> n) >>= f = (m >>= f) <!> (m >>= f)
--   
class Functor f => Alt (f :: * -> *) -- | <|> without a required empty () :: Alt f => f a -> f a -> f a -- | Laws: -- --
--   zero <!> m = m
--   m <!> zero = m
--   
-- -- If extended to an Alternative then zero should equal -- empty. class Alt f => Plus (f :: * -> *) zero :: Plus f => f a -- | A Monad sans return. -- -- Minimal definition: Either join or >>- -- -- If defining both, then the following laws (the default definitions) -- must hold: -- --
--   join = (>>- id)
--   m >>- f = join (fmap f m)
--   
-- -- Laws: -- --
--   induced definition of <.>: f <.> x = f >>- (<$> x)
--   
-- -- Finally, there are two associativity conditions: -- --
--   associativity of (>>-):    (m >>- f) >>- g == m >>- (\x -> f x >>- g)
--   associativity of join:     join . join = join . fmap join
--   
-- -- These can both be seen as special cases of the constraint that -- --
--   associativity of (->-): (f ->- g) ->- h = f ->- (g ->- h)
--   
class Apply m => Bind (m :: * -> *) (>>-) :: Bind m => m a -> a -> m b -> m b join :: Bind m => m m a -> m a (-<<) :: Bind m => a -> m b -> m a -> m b infixr 1 -<< class Functor w => Extend (w :: * -> *) -- |
--   duplicated = extended id
--   fmap (fmap f) . duplicated = duplicated . fmap f
--   
duplicated :: Extend w => w a -> w w a -- |
--   extended f  = fmap f . duplicated
--   
extended :: Extend w => w a -> b -> w a -> w b -- | A functor in the category of monads, using hoist as the analog -- of fmap: -- --
--   hoist (f . g) = hoist f . hoist g
--   
--   hoist id = id
--   
class MFunctor (t :: * -> * -> k -> *) -- | Lift a monad morphism from m to n into a monad -- morphism from (t m) to (t n) -- -- The first argument to hoist must be a monad morphism, even -- though the type system does not enforce this hoist :: (MFunctor t, Monad m) => forall a. () => m a -> n a -> t m b -> t n b module Generic module Graph.Adjacency module Graph.Inductive data Gr a b type UGr = Gr () () -- | Minimum implementation: empty, isEmpty, match, -- mkGraph, labNodes class Graph (gr :: * -> * -> *) -- | An empty Graph. empty :: Graph gr => gr a b -- | True if the given Graph is empty. isEmpty :: Graph gr => gr a b -> Bool -- | Decompose a Graph into the MContext found for the given -- node and the remaining Graph. match :: Graph gr => Node -> gr a b -> Decomp gr a b -- | Create a Graph from the list of LNodes and -- LEdges. -- -- For graphs that are also instances of DynGraph, mkGraph ns -- es should be equivalent to (insEdges es . -- insNodes ns) empty. mkGraph :: Graph gr => [LNode a] -> [LEdge b] -> gr a b -- | A list of all LNodes in the Graph. labNodes :: Graph gr => gr a b -> [LNode a] -- | Decompose a graph into the Context for an arbitrarily-chosen -- Node and the remaining Graph. matchAny :: Graph gr => gr a b -> GDecomp gr a b -- | The number of Nodes in a Graph. noNodes :: Graph gr => gr a b -> Int -- | The minimum and maximum Node in a Graph. nodeRange :: Graph gr => gr a b -> (Node, Node) -- | A list of all LEdges in the Graph. labEdges :: Graph gr => gr a b -> [LEdge b] -- | Build a quasi-unlabeled Graph. mkUGraph :: Graph gr => [Node] -> [Edge] -> gr () () -- | The number of nodes in the graph. An alias for noNodes. order :: Graph gr => gr a b -> Int -- | The number of edges in the graph. -- -- Note that this counts every edge found, so if you are representing an -- unordered graph by having each edge mirrored this will be incorrect. -- -- If you created an unordered graph by either mirroring every edge -- (including loops!) or using the undir function in -- Data.Graph.Inductive.Basic then you can safely halve the value -- returned by this. size :: Graph gr => gr a b -> Int -- | List all Nodes in the Graph. nodes :: Graph gr => gr a b -> [Node] -- | List all Edges in the Graph. edges :: Graph gr => gr a b -> [Edge] -- | Find the context for the given Node. Causes an error if the -- Node is not present in the Graph. context :: Graph gr => gr a b -> Node -> Context a b -- | Find the label for a Node. lab :: Graph gr => gr a b -> Node -> Maybe a -- | Find the neighbors for a Node. neighbors :: Graph gr => gr a b -> Node -> [Node] -- | Find the labelled links coming into or going from a Context. lneighbors :: Graph gr => gr a b -> Node -> Adj b -- | Find all Nodes that have a link from the given Node. suc :: Graph gr => gr a b -> Node -> [Node] -- | Find all Nodes that link to to the given Node. pre :: Graph gr => gr a b -> Node -> [Node] -- | Find all Nodes that are linked from the given Node and -- the label of each link. lsuc :: Graph gr => gr a b -> Node -> [(Node, b)] -- | Find all Nodes that link to the given Node and the label -- of each link. lpre :: Graph gr => gr a b -> Node -> [(Node, b)] -- | Find all outward-bound LEdges for the given Node. out :: Graph gr => gr a b -> Node -> [LEdge b] -- | Find all inward-bound LEdges for the given Node. inn :: Graph gr => gr a b -> Node -> [LEdge b] -- | The outward-bound degree of the Node. outdeg :: Graph gr => gr a b -> Node -> Int -- | The inward-bound degree of the Node. indeg :: Graph gr => gr a b -> Node -> Int -- | The degree of the Node. deg :: Graph gr => gr a b -> Node -> Int -- | Checks if there is an undirected edge between two nodes. hasNeighbor :: Graph gr => gr a b -> Node -> Node -> Bool -- | Checks if there is an undirected labelled edge between two nodes. hasNeighborAdj :: (Graph gr, Eq b) => gr a b -> Node -> (b, Node) -> Bool -- | Checks if there is a directed edge between two nodes. hasEdge :: Graph gr => gr a b -> Edge -> Bool -- | Checks if there is a labelled edge between two nodes. hasLEdge :: (Graph gr, Eq b) => gr a b -> LEdge b -> Bool equal :: (Eq a, Eq b, Graph gr) => gr a b -> gr a b -> Bool -- | True if the Node is present in the Graph. gelem :: Graph gr => Node -> gr a b -> Bool -- | Return all Contexts for which the given function returns -- True. gsel :: Graph gr => Context a b -> Bool -> gr a b -> [Context a b] -- | Directed graph fold. gfold :: Graph gr => Context a b -> [Node] -> Context a b -> c -> d -> (Maybe d -> c -> c, c) -> [Node] -> gr a b -> c -- | Fold a function over the graph by recursively calling match. ufold :: Graph gr => Context a b -> c -> c -> c -> gr a b -> c -- | True if the graph has any edges of the form (A, A). hasLoop :: Graph gr => gr a b -> Bool -- | The inverse of hasLoop. isSimple :: Graph gr => gr a b -> Bool -- | List N available Nodes, i.e. Nodes that are not used in -- the Graph. newNodes :: Graph gr => Int -> gr a b -> [Node] -- | Finds the articulation points for a connected undirected graph, by -- using the low numbers criteria: -- -- a) The root node is an articulation point iff it has two or more -- children. -- -- b) An non-root node v is an articulation point iff there exists at -- least one child w of v such that lowNumber(w) >= dfsNumber(v). ap :: Graph gr => gr a b -> [Node] bfs :: Graph gr => Node -> gr a b -> [Node] bfsn :: Graph gr => [Node] -> gr a b -> [Node] bfsWith :: Graph gr => Context a b -> c -> Node -> gr a b -> [c] bfsnWith :: Graph gr => Context a b -> c -> [Node] -> gr a b -> [c] level :: Graph gr => Node -> gr a b -> [(Node, Int)] leveln :: Graph gr => [(Node, Int)] -> gr a b -> [(Node, Int)] bfe :: Graph gr => Node -> gr a b -> [Edge] bfen :: Graph gr => [Edge] -> gr a b -> [Edge] bft :: Graph gr => Node -> gr a b -> RTree lbft :: Graph gr => Node -> gr a b -> LRTree b esp :: Graph gr => Node -> Node -> gr a b -> Path lesp :: Graph gr => Node -> Node -> gr a b -> LPath b type CFun a b c = Context a b -> c -- | Depth-first search. dfs :: Graph gr => [Node] -> gr a b -> [Node] dfs' :: Graph gr => gr a b -> [Node] dfsWith :: Graph gr => CFun a b c -> [Node] -> gr a b -> [c] dfsWith' :: Graph gr => CFun a b c -> gr a b -> [c] -- | Directed depth-first forest. dff :: Graph gr => [Node] -> gr a b -> [Tree Node] dff' :: Graph gr => gr a b -> [Tree Node] dffWith :: Graph gr => CFun a b c -> [Node] -> gr a b -> [Tree c] dffWith' :: Graph gr => CFun a b c -> gr a b -> [Tree c] -- | Most general DFS algorithm to create a list of results. The other -- list-returning functions such as dfs are all defined in terms -- of this one. -- --
--   xdfsWith d f vs = preorderF . xdffWith d f vs
--   
xdfsWith :: Graph gr => CFun a b [Node] -> CFun a b c -> [Node] -> gr a b -> [c] -- | Most general DFS algorithm to create a forest of results, otherwise -- very similar to xdfsWith. The other forest-returning functions -- such as dff are all defined in terms of this one. xdfWith :: Graph gr => CFun a b [Node] -> CFun a b c -> [Node] -> gr a b -> ([Tree c], gr a b) -- | Discard the graph part of the result of xdfWith. -- --
--   xdffWith d f vs g = fst (xdfWith d f vs g)
--   
xdffWith :: Graph gr => CFun a b [Node] -> CFun a b c -> [Node] -> gr a b -> [Tree c] -- | Undirected depth-first search, obtained by following edges regardless -- of their direction. udfs :: Graph gr => [Node] -> gr a b -> [Node] udfs' :: Graph gr => gr a b -> [Node] -- | Undirected depth-first forest, obtained by following edges regardless -- of their direction. udff :: Graph gr => [Node] -> gr a b -> [Tree Node] udff' :: Graph gr => gr a b -> [Tree Node] udffWith :: Graph gr => CFun a b c -> [Node] -> gr a b -> [Tree c] udffWith' :: Graph gr => CFun a b c -> gr a b -> [Tree c] -- | Reverse depth-first forest, obtained by following predecessors. rdff :: Graph gr => [Node] -> gr a b -> [Tree Node] rdff' :: Graph gr => gr a b -> [Tree Node] rdfs' :: Graph gr => gr a b -> [Node] rdffWith :: Graph gr => CFun a b c -> [Node] -> gr a b -> [Tree c] rdffWith' :: Graph gr => CFun a b c -> gr a b -> [Tree c] -- | Topological sorting, i.e. a list of Nodes so that if -- there's an edge between a source and a target node, the source appears -- earlier in the result. topsort :: Graph gr => gr a b -> [Node] -- | topsort, returning only the labels of the nodes. topsort' :: Graph gr => gr a b -> [a] -- | Collection of strongly connected components scc :: Graph gr => gr a b -> [[Node]] -- | Collection of nodes reachable from a starting point. reachable :: Graph gr => Node -> gr a b -> [Node] -- | Collection of connected components components :: Graph gr => gr a b -> [[Node]] -- | Number of connected components noComponents :: Graph gr => gr a b -> Int -- | Is the graph connected? isConnected :: Graph gr => gr a b -> Bool -- | The condensation of the given graph, i.e., the graph of its strongly -- connected components. condensation :: Graph gr => gr a b -> gr [Node] () -- | return the set of dominators of the nodes of a graph, given a root dom :: Graph gr => gr a b -> Node -> [(Node, [Node])] -- | return immediate dominators for each node of a graph, given a root iDom :: Graph gr => gr a b -> Node -> [(Node, Node)] -- | Representation of a shortest path forest. type Voronoi a = LRTree a -- | Produce a shortest path forest (the roots of which are those nodes -- specified) from nodes in the graph to one of the root nodes (if -- possible). gvdIn :: (DynGraph gr, Real b) => [Node] -> gr a b -> Voronoi b -- | Produce a shortest path forest (the roots of which are those nodes -- specified) from nodes in the graph from one of the root nodes -- (if possible). gvdOut :: (Graph gr, Real b) => [Node] -> gr a b -> Voronoi b -- | Return the nodes reachable to/from (depending on how the -- Voronoi was constructed) from the specified root node (if the -- specified node is not one of the root nodes of the shortest path -- forest, an empty list will be returned). voronoiSet :: () => Node -> Voronoi b -> [Node] -- | Try to determine the nearest root node to the one specified in the -- shortest path forest. nearestNode :: () => Node -> Voronoi b -> Maybe Node -- | The distance to the nearestNode (if there is one) in the -- shortest path forest. nearestDist :: () => Node -> Voronoi b -> Maybe b -- | Try to construct a path to/from a specified node to one of the root -- nodes of the shortest path forest. nearestPath :: () => Node -> Voronoi b -> Maybe Path -- | Calculate the maximum independent node set of the specified graph. indep :: DynGraph gr => gr a b -> [Node] -- | The maximum independent node set along with its size. indepSize :: DynGraph gr => gr a b -> ([Node], Int) msTreeAt :: (Graph gr, Real b) => Node -> gr a b -> LRTree b msTree :: (Graph gr, Real b) => gr a b -> LRTree b msPath :: () => LRTree b -> Node -> Node -> Path -- |
--                   i                                 0
--   For each edge a--->b this function returns edge b--->a .
--            i
--   Edges a<--->b are ignored
--            j
--   
getRevEdges :: Num b => [Edge] -> [LEdge b] -- |
--                   i                                  0
--   For each edge a--->b insert into graph the edge a<---b . Then change the
--                              i         (i,0,i)
--   label of every edge from a---->b to a------->b
--   
-- -- where label (x,y,z)=(Max Capacity, Current flow, Residual capacity) augmentGraph :: (DynGraph gr, Num b) => gr a b -> gr a (b, b, b) -- | Given a successor or predecessor list for node u and given -- node v, find the label corresponding to edge (u,v) -- and update the flow and residual capacity of that edge's label. Then -- return the updated list. updAdjList :: Num b => Adj (b, b, b) -> Node -> b -> Bool -> Adj (b, b, b) -- | Update flow and residual capacity along augmenting path from -- s to t in graph @G. For a path -- [u,v,w,...] find the node u in G and its -- successor and predecessor list, then update the corresponding edges -- (u,v) and (v,u)@ on those lists by using the minimum -- residual capacity of the path. updateFlow :: (DynGraph gr, Num b) => Path -> b -> gr a (b, b, b) -> gr a (b, b, b) -- | Compute the flow from s to t on a graph whose edges -- are labeled with (x,y,z)=(max capacity,current flow,residual -- capacity) and all edges are of the form a<---->b. -- First compute the residual graph, that is, delete those edges whose -- residual capacity is zero. Then compute the shortest augmenting path -- from s to t, and finally update the flow and -- residual capacity along that path by using the minimum capacity of -- that path. Repeat this process until no shortest path from s -- to t exist. mfmg :: (DynGraph gr, Num b, Ord b) => gr a (b, b, b) -> Node -> Node -> gr a (b, b, b) -- | Compute the flow from s to t on a graph whose edges are labeled with -- x, which is the max capacity and where not all edges need to -- be of the form a<---->b. Return the flow as a grap whose edges -- are labeled with (x,y,z)=(max capacity,current flow,residual capacity) -- and all edges are of the form a<---->b mf :: (DynGraph gr, Num b, Ord b) => gr a b -> Node -> Node -> gr a (b, b, b) -- | Compute the maximum flow from s to t on a graph whose edges are -- labeled with x, which is the max capacity and where not all edges need -- to be of the form a<---->b. Return the flow as a graph whose -- edges are labeled with (y,x) = (current flow, max capacity). maxFlowgraph :: (DynGraph gr, Num b, Ord b) => gr a b -> Node -> Node -> gr a (b, b) -- | Compute the value of a maximumflow maxFlow :: (DynGraph gr, Num b, Ord b) => gr a b -> Node -> Node -> b type Network = Gr () (Double, Double) ekSimple :: Network -> Node -> Node -> (Network, Double) ekFused :: Network -> Node -> Node -> (Network, Double) ekList :: Network -> Node -> Node -> (Network, Double) data Heap a b -- | Tree of shortest paths from a certain node to the rest of the -- (reachable) nodes. -- -- Corresponds to dijkstra applied to a heap in which the only -- known node is the starting node, with a path of length 0 leading to -- it. -- -- The edge labels of type b are the edge weights; negative edge -- weights are not supported. spTree :: (Graph gr, Real b) => Node -> gr a b -> LRTree b -- | Shortest path between two nodes, if any. -- -- Returns Nothing if the destination is not reachable from the -- start node, and Just path otherwise. -- -- The edge labels of type b are the edge weights; negative edge -- weights are not supported. sp :: (Graph gr, Real b) => Node -> Node -> gr a b -> Maybe Path -- | Length of the shortest path between two nodes, if any. -- -- Returns Nothing if there is no path, and Just -- length otherwise. -- -- The edge labels of type b are the edge weights; negative edge -- weights are not supported. spLength :: (Graph gr, Real b) => Node -> Node -> gr a b -> Maybe b -- | Dijkstra's shortest path algorithm. -- -- The edge labels of type b are the edge weights; negative edge -- weights are not supported. dijkstra :: (Graph gr, Real b) => Heap b LPath b -> gr a b -> LRTree b class Graph gr => DynGraph (gr :: * -> * -> *) -- | Merge the Context into the DynGraph. -- -- Context adjacencies should only refer to either a Node already in a -- graph or the node in the Context itself (for loops). -- -- Behaviour is undefined if the specified Node already exists in -- the graph. (&) :: DynGraph gr => Context a b -> gr a b -> gr a b -- | Build a Graph from a list of Contexts. -- -- The list should be in the order such that earlier Contexts -- depend upon later ones (i.e. as produced by ufold (:) -- []). buildGr :: DynGraph gr => [Context a b] -> gr a b -- | Insert a LNode into the Graph. insNode :: DynGraph gr => LNode a -> gr a b -> gr a b -- | Insert multiple LNodes into the Graph. insNodes :: DynGraph gr => [LNode a] -> gr a b -> gr a b -- | Insert a LEdge into the Graph. insEdge :: DynGraph gr => LEdge b -> gr a b -> gr a b -- | Insert multiple LEdges into the Graph. insEdges :: DynGraph gr => [LEdge b] -> gr a b -> gr a b -- | Remove a Node from the Graph. delNode :: Graph gr => Node -> gr a b -> gr a b -- | Remove multiple Nodes from the Graph. delNodes :: Graph gr => [Node] -> gr a b -> gr a b -- | Remove an Edge from the Graph. -- -- NOTE: in the case of multiple edges, this will delete all such -- edges from the graph as there is no way to distinguish between them. -- If you need to delete only a single such edge, please use -- delLEdge. delEdge :: DynGraph gr => Edge -> gr a b -> gr a b -- | Remove multiple Edges from the Graph. delEdges :: DynGraph gr => [Edge] -> gr a b -> gr a b -- | Remove an LEdge from the Graph. -- -- NOTE: in the case of multiple edges with the same label, this will -- only delete the first such edge. To delete all such edges, -- please use delAllLedge. delLEdge :: (DynGraph gr, Eq b) => LEdge b -> gr a b -> gr a b -- | Remove all edges equal to the one specified. delAllLEdge :: (DynGraph gr, Eq b) => LEdge b -> gr a b -> gr a b -- | Map a function over the graph by recursively calling match. gmap :: DynGraph gr => Context a b -> Context c d -> gr a b -> gr c d -- | Map a function over the Node labels in a graph. nmap :: DynGraph gr => a -> c -> gr a b -> gr c b -- | Map a function over the Edge labels in a graph. emap :: DynGraph gr => b -> c -> gr a b -> gr a c -- | Map functions over both the Node and Edge labels in a -- graph. nemap :: DynGraph gr => a -> c -> b -> d -> gr a b -> gr c d -- | Build a graph out of the contexts for which the predicate is satisfied -- by recursively calling match. gfiltermap :: DynGraph gr => Context a b -> MContext c d -> gr a b -> gr c d -- | Returns the subgraph only containing the nodes which satisfy the given -- predicate. nfilter :: DynGraph gr => Node -> Bool -> gr a b -> gr a b -- | Returns the subgraph only containing the labelled nodes which satisfy -- the given predicate. labnfilter :: Graph gr => LNode a -> Bool -> gr a b -> gr a b -- | Returns the subgraph only containing the nodes whose labels satisfy -- the given predicate. labfilter :: DynGraph gr => a -> Bool -> gr a b -> gr a b -- | Returns the subgraph induced by the supplied nodes. subgraph :: DynGraph gr => [Node] -> gr a b -> gr a b -- | Reverse the direction of all edges. grev :: DynGraph gr => gr a b -> gr a b -- | Make the graph undirected, i.e. for every edge from A to B, there -- exists an edge from B to A. undir :: (Eq b, DynGraph gr) => gr a b -> gr a b -- | Remove all labels. unlab :: DynGraph gr => gr a b -> gr () () -- | Filter based on edge property. efilter :: DynGraph gr => LEdge b -> Bool -> gr a b -> gr a b -- | Filter based on edge label property. elfilter :: DynGraph gr => b -> Bool -> gr a b -> gr a b -- | Finds the bi-connected components of an undirected connected graph. It -- first finds the articulation points of the graph. Then it disconnects -- the graph on each articulation point and computes the connected -- components. bcc :: DynGraph gr => gr a b -> [gr a b] -- | Pretty-print the graph. Note that this loses a lot of information, -- such as edge inverses, etc. prettify :: (DynGraph gr, Show a, Show b) => gr a b -> String -- | Pretty-print the graph to stdout. prettyPrint :: (DynGraph gr, Show a, Show b) => gr a b -> IO () -- | Finds the transitive, reflexive closure of a directed graph. Given a -- graph G=(V,E), its transitive closure is the graph: G* = (V,E*) where -- E*={(i,j): i,j in V and either i = j or there is a path from i to j in -- G} trc :: DynGraph gr => gr a b -> gr a () -- | Finds the reflexive closure of a directed graph. Given a graph -- G=(V,E), its transitive closure is the graph: G* = (V,Er union E) -- where Er = {(i,i): i in V} rc :: DynGraph gr => gr a b -> gr a () -- | Finds the transitive closure of a directed graph. Given a graph -- G=(V,E), its transitive closure is the graph: G* = (V,E*) where -- E*={(i,j): i,j in V and there is a path from i to j in G} tc :: DynGraph gr => gr a b -> gr a () -- | Unlabeled node type Node = Int -- | Labeled node type LNode a = (Node, a) -- | Quasi-unlabeled node type UNode = LNode () -- | Unlabeled edge type Edge = (Node, Node) -- | Labeled edge type LEdge b = (Node, Node, b) -- | Quasi-unlabeled edge type UEdge = LEdge () -- | Drop the label component of an edge. toEdge :: () => LEdge b -> Edge -- | The label in an edge. edgeLabel :: () => LEdge b -> b -- | Add a label to an edge. toLEdge :: () => Edge -> b -> LEdge b -- | Links to the Node, the Node itself, a label, links from -- the Node. -- -- In other words, this captures all information regarding the specified -- Node within a graph. type Context a b = (Adj b, Node, a, Adj b) type MContext a b = Maybe Context a b -- | Unlabeled context. type UContext = ([Node], Node, [Node]) -- | The Node in a Context. node' :: () => Context a b -> Node -- | The label in a Context. lab' :: () => Context a b -> a -- | The LNode from a Context. labNode' :: () => Context a b -> LNode a -- | All Nodes linked to or from in a Context. neighbors' :: () => Context a b -> [Node] -- | All labelled links coming into or going from a Context. lneighbors' :: () => Context a b -> Adj b -- | All Nodes linked to in a Context. suc' :: () => Context a b -> [Node] -- | All Nodes linked from in a Context. pre' :: () => Context a b -> [Node] -- | All Nodes linked from in a Context, and the label of the -- links. lpre' :: () => Context a b -> [(Node, b)] -- | All Nodes linked from in a Context, and the label of the -- links. lsuc' :: () => Context a b -> [(Node, b)] -- | All outward-directed LEdges in a Context. out' :: () => Context a b -> [LEdge b] -- | All inward-directed LEdges in a Context. inn' :: () => Context a b -> [LEdge b] -- | The outward degree of a Context. outdeg' :: () => Context a b -> Int -- | The inward degree of a Context. indeg' :: () => Context a b -> Int -- | The degree of a Context. deg' :: () => Context a b -> Int -- | Graph decomposition - the context removed from a Graph, -- and the rest of the Graph. type Decomp (g :: * -> * -> *) a b = (MContext a b, g a b) -- | The same as Decomp, only more sure of itself. type GDecomp (g :: * -> * -> *) a b = (Context a b, g a b) -- | Unlabeled decomposition. type UDecomp g = (Maybe UContext, g) -- | Unlabeled path type Path = [Node] -- | Labeled path newtype LPath a LP :: [LNode a] -> LPath a [unLPath] :: LPath a -> [LNode a] -- | Quasi-unlabeled path type UPath = [UNode] type RTree = [Path] type LRTree a = [LPath a] -- | Labeled links to or from a Node. type Adj b = [(b, Node)] -- | OrdGr comes equipped with an Ord instance, so that graphs can be used -- as e.g. Map keys. newtype OrdGr (gr :: * -> * -> *) a b OrdGr :: gr a b -> OrdGr a b [unOrdGr] :: OrdGr a b -> gr a b module Groupoid -- | semigroupoid with inverses. This technically should be a category with -- inverses, except we need to use Ob to define the valid objects for the -- category class Semigroupoid k1 => Groupoid (k1 :: k -> k -> *) inv :: Groupoid k1 => k1 a b -> k1 b a module Hashable -- | The class of types that can be converted to a hash value. -- -- Minimal implementation: hashWithSalt. class Hashable a -- | Return a hash value for the argument, using the given salt. -- -- The general contract of hashWithSalt is: -- -- hashWithSalt :: Hashable a => Int -> a -> Int -- | Like hashWithSalt, but no salt is used. The default -- implementation uses hashWithSalt with some default salt. -- Instances might want to implement this method to provide a more -- efficient implementation than the default implementation. hash :: Hashable a => a -> Int -- | Transform a value into a Hashable value, then hash the -- transformed value using the given salt. -- -- This is a useful shorthand in cases where a type can easily be mapped -- to another type that is already an instance of Hashable. -- Example: -- --
--   data Foo = Foo | Bar
--            deriving (Enum)
--   
--   instance Hashable Foo where
--       hashWithSalt = hashUsing fromEnum
--   
hashUsing :: Hashable b => a -> b -> Int -> a -> Int -- | Compute a hash value for the content of this pointer. hashPtr :: () => Ptr a -> Int -> IO Int -- | Compute a hash value for the content of this pointer, using an initial -- salt. -- -- This function can for example be used to hash non-contiguous segments -- of memory as if they were one contiguous segment, by using the output -- of one hash as the salt for the next. hashPtrWithSalt :: () => Ptr a -> Int -> Int -> IO Int -- | Compute a hash value for the content of this ByteArray#, -- beginning at the specified offset, using specified number of bytes. hashByteArray :: ByteArray# -> Int -> Int -> Int -- | Compute a hash value for the content of this ByteArray#, using -- an initial salt. -- -- This function can for example be used to hash non-contiguous segments -- of memory as if they were one contiguous segment, by using the output -- of one hash as the salt for the next. hashByteArrayWithSalt :: ByteArray# -> Int -> Int -> Int -> Int -- | A hashable value along with the result of the hash function. data Hashed a -- | Wrap a hashable value, caching the hash function result. hashed :: Hashable a => a -> Hashed a -- | Unwrap hashed value. unhashed :: () => Hashed a -> a -- | Hashed cannot be Functor mapHashed :: Hashable b => a -> b -> Hashed a -> Hashed b -- | Hashed cannot be Traversable traverseHashed :: (Hashable b, Functor f) => a -> f b -> Hashed a -> f Hashed b module Heap module IO -- | 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 -- | 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 :: * -> *) -- | Lift a computation from the IO monad. liftIO :: MonadIO m => IO a -> m a -- | The implementation of mfix for IO. If the function -- passed to fixIO inspects its argument, the resulting action -- will throw FixIOException. fixIO :: () => a -> IO a -> IO a -- | Unlifted timeout. timeout :: MonadUnliftIO m => Int -> m a -> m Maybe a -- | Given an action, produce a wrapped action that runs at most once. If -- the function raises an exception, the same exception will be reraised -- each time. -- --
--   let x ||| y = do t1 <- onceFork x; t2 <- onceFork y; t1; t2
--   \(x :: IO Int) -> void (once x) == return ()
--   \(x :: IO Int) -> join (once x) == x
--   \(x :: IO Int) -> (do y <- once x; y; y) == x
--   \(x :: IO Int) -> (do y <- once x; y ||| y) == x
--   
once :: () => IO a -> IO IO a -- | Like once, but immediately starts running the computation on a -- background thread. -- --
--   \(x :: IO Int) -> join (onceFork x) == x
--   \(x :: IO Int) -> (do a <- onceFork x; a; a) == x
--   
onceFork :: () => IO a -> IO IO a module IO.Unsafe -- | This is the "back door" into the IO monad, allowing IO -- computation to be performed at any time. For this to be safe, the -- IO computation should be free of side effects and independent -- of its environment. -- -- If the I/O computation wrapped in unsafePerformIO performs side -- effects, then the relative order in which those side effects take -- place (relative to the main I/O trunk, or other calls to -- unsafePerformIO) is indeterminate. Furthermore, when using -- unsafePerformIO to cause side-effects, you should take the -- following precautions to ensure the side effects are performed as many -- times as you expect them to be. Note that these precautions are -- necessary for GHC, but may not be sufficient, and other compilers may -- require different precautions: -- -- -- -- It is less well known that unsafePerformIO is not type safe. -- For example: -- --
--   test :: IORef [a]
--   test = unsafePerformIO $ newIORef []
--   
--   main = do
--           writeIORef test [42]
--           bang <- readIORef test
--           print (bang :: [Char])
--   
-- -- This program will core dump. This problem with polymorphic references -- is well known in the ML community, and does not arise with normal -- monadic use of references. There is no easy way to make it impossible -- once you use unsafePerformIO. Indeed, it is possible to write -- coerce :: a -> b with the help of unsafePerformIO. -- So be careful! unsafePerformIO :: () => IO a -> a -- | This version of unsafePerformIO is more efficient because it -- omits the check that the IO is only being performed by a single -- thread. Hence, when you use unsafeDupablePerformIO, there is a -- possibility that the IO action may be performed multiple times (on a -- multiprocessor), and you should therefore ensure that it gives the -- same results each time. It may even happen that one of the duplicated -- IO actions is only run partially, and then interrupted in the middle -- without an exception being raised. Therefore, functions like -- bracket cannot be used safely within -- unsafeDupablePerformIO. unsafeDupablePerformIO :: () => IO a -> a -- | unsafeInterleaveIO allows an IO computation to be -- deferred lazily. When passed a value of type IO a, the -- IO will only be performed when the value of the a is -- demanded. This is used to implement lazy file reading, see -- hGetContents. unsafeInterleaveIO :: () => IO a -> IO a -- | A slightly faster version of fixIO that may not be safe to use -- with multiple threads. The unsafety arises when used like this: -- --
--   unsafeFixIO $ \r -> do
--      forkIO (print r)
--      return (...)
--   
-- -- In this case, the child thread will receive a NonTermination -- exception instead of waiting for the value of r to be -- computed. unsafeFixIO :: () => a -> IO a -> IO a module Ix -- | The Ix class is used to map a contiguous subrange of values in -- a type onto integers. It is used primarily for array indexing (see the -- array package). -- -- The first argument (l,u) of each of these operations is a -- pair specifying the lower and upper bounds of a contiguous subrange of -- values. -- -- An implementation is entitled to assume the following laws about these -- operations: -- -- class Ord a => Ix a -- | The list of values in the subrange defined by a bounding pair. range :: Ix a => (a, a) -> [a] -- | The position of a subscript in the subrange. index :: Ix a => (a, a) -> a -> Int -- | Returns True the given subscript lies in the range defined the -- bounding pair. inRange :: Ix a => (a, a) -> a -> Bool -- | The size of the subrange defined by a bounding pair. rangeSize :: Ix a => (a, a) -> Int -- | JSON functionality common to both encoding and decoding. Re-exported -- by both Json.Encode and Json.Decode for convenience. module Json -- | A JSON value represented as a Haskell value. data Value Object :: !Object -> Value Array :: !Array -> Value String :: !Text -> Value Number :: !Scientific -> Value Bool :: !Bool -> Value Null :: Value -- | Primitives of Value data Primitive StringPrim :: !Text -> Primitive NumberPrim :: !Scientific -> Primitive BoolPrim :: !Bool -> Primitive NullPrim :: Primitive class AsNumber t -- |
--   >>> "[1, \"x\"]" ^? nth 0 . _Number
--   Just 1.0
--   
-- --
--   >>> "[1, \"x\"]" ^? nth 1 . _Number
--   Nothing
--   
_Number :: AsNumber t => Prism' t Scientific -- | Prism into an Double over a Value, Primitive or -- Scientific -- --
--   >>> "[10.2]" ^? nth 0 . _Double
--   Just 10.2
--   
_Double :: AsNumber t => Prism' t Double -- | Prism into an Integer over a Value, Primitive or -- Scientific -- --
--   >>> "[10]" ^? nth 0 . _Integer
--   Just 10
--   
-- --
--   >>> "[10.5]" ^? nth 0 . _Integer
--   Just 10
--   
-- --
--   >>> "42" ^? _Integer
--   Just 42
--   
_Integer :: AsNumber t => Prism' t Integer -- | Access Integer Values as Integrals. -- --
--   >>> "[10]" ^? nth 0 . _Integral
--   Just 10
--   
-- --
--   >>> "[10.5]" ^? nth 0 . _Integral
--   Just 10
--   
_Integral :: (AsNumber t, Integral a) => Prism' t a -- | Prism into non-Null values -- --
--   >>> "{\"a\": \"xyz\", \"b\": null}" ^? key "a" . nonNull
--   Just (String "xyz")
--   
-- --
--   >>> "{\"a\": {}, \"b\": null}" ^? key "a" . nonNull
--   Just (Object (fromList []))
--   
-- --
--   >>> "{\"a\": \"xyz\", \"b\": null}" ^? key "b" . nonNull
--   Nothing
--   
nonNull :: Prism' Value Value class AsNumber t => AsPrimitive t -- |
--   >>> "[1, \"x\", null, true, false]" ^? nth 0 . _Primitive
--   Just (NumberPrim 1.0)
--   
-- --
--   >>> "[1, \"x\", null, true, false]" ^? nth 1 . _Primitive
--   Just (StringPrim "x")
--   
-- --
--   >>> "[1, \"x\", null, true, false]" ^? nth 2 . _Primitive
--   Just NullPrim
--   
-- --
--   >>> "[1, \"x\", null, true, false]" ^? nth 3 . _Primitive
--   Just (BoolPrim True)
--   
-- --
--   >>> "[1, \"x\", null, true, false]" ^? nth 4 . _Primitive
--   Just (BoolPrim False)
--   
_Primitive :: AsPrimitive t => Prism' t Primitive -- |
--   >>> "{\"a\": \"xyz\", \"b\": true}" ^? key "a" . _String
--   Just "xyz"
--   
-- --
--   >>> "{\"a\": \"xyz\", \"b\": true}" ^? key "b" . _String
--   Nothing
--   
-- --
--   >>> _Object._Wrapped # [("key" :: Text, _String # "value")] :: String
--   "{\"key\":\"value\"}"
--   
_String :: AsPrimitive t => Prism' t Text -- |
--   >>> "{\"a\": \"xyz\", \"b\": true}" ^? key "b" . _Bool
--   Just True
--   
-- --
--   >>> "{\"a\": \"xyz\", \"b\": true}" ^? key "a" . _Bool
--   Nothing
--   
-- --
--   >>> _Bool # True :: String
--   "true"
--   
-- --
--   >>> _Bool # False :: String
--   "false"
--   
_Bool :: AsPrimitive t => Prism' t Bool -- |
--   >>> "{\"a\": \"xyz\", \"b\": null}" ^? key "b" . _Null
--   Just ()
--   
-- --
--   >>> "{\"a\": \"xyz\", \"b\": null}" ^? key "a" . _Null
--   Nothing
--   
-- --
--   >>> _Null # () :: String
--   "null"
--   
_Null :: AsPrimitive t => Prism' t () class AsPrimitive t => AsValue t -- |
--   >>> preview _Value "[1,2,3]" == Just (Array (Vector.fromList [Number 1.0,Number 2.0,Number 3.0]))
--   True
--   
_Value :: AsValue t => Prism' t Value -- |
--   >>> "{\"a\": {}, \"b\": null}" ^? key "a" . _Object
--   Just (fromList [])
--   
-- --
--   >>> "{\"a\": {}, \"b\": null}" ^? key "b" . _Object
--   Nothing
--   
-- --
--   >>> _Object._Wrapped # [("key" :: Text, _String # "value")] :: String
--   "{\"key\":\"value\"}"
--   
_Object :: AsValue t => Prism' t HashMap Text Value -- |
--   >>> preview _Array "[1,2,3]" == Just (Vector.fromList [Number 1.0,Number 2.0,Number 3.0])
--   True
--   
_Array :: AsValue t => Prism' t Vector Value class AsJSON t -- | _JSON is a Prism from something containing JSON to -- something encoded in that structure _JSON :: (AsJSON t, FromJSON a, ToJSON a) => Prism' t a -- | Like ix, but for Object with Text indices. This often -- has better inference than ix when used with OverloadedStrings. -- --
--   >>> "{\"a\": 100, \"b\": 200}" ^? key "a"
--   Just (Number 100.0)
--   
-- --
--   >>> "[1,2,3]" ^? key "a"
--   Nothing
--   
key :: AsValue t => Text -> Traversal' t Value -- | An indexed Traversal into Object properties -- --
--   >>> "{\"a\": 4, \"b\": 7}" ^@.. members
--   [("a",Number 4.0),("b",Number 7.0)]
--   
-- --
--   >>> "{\"a\": 4, \"b\": 7}" & members . _Number *~ 10
--   "{\"a\":40,\"b\":70}"
--   
members :: AsValue t => IndexedTraversal' Text t Value -- | Like ix, but for Arrays with Int indexes -- --
--   >>> "[1,2,3]" ^? nth 1
--   Just (Number 2.0)
--   
-- --
--   >>> "\"a\": 100, \"b\": 200}" ^? nth 1
--   Nothing
--   
-- --
--   >>> "[1,2,3]" & nth 1 .~ Number 20
--   "[1,20,3]"
--   
nth :: AsValue t => Int -> Traversal' t Value -- | An indexed Traversal into Array elements -- --
--   >>> "[1,2,3]" ^.. values
--   [Number 1.0,Number 2.0,Number 3.0]
--   
-- --
--   >>> "[1,2,3]" & values . _Number *~ 10
--   "[10,20,30]"
--   
values :: AsValue t => IndexedTraversal' Int t Value module Json.Decode -- | A type that can be converted from JSON, with the possibility of -- failure. -- -- In many cases, you can get the compiler to generate parsing code for -- you (see below). To begin, let's cover writing an instance by hand. -- -- There are various reasons a conversion could fail. For example, an -- Object could be missing a required key, an Array could -- be of the wrong size, or a value could be of an incompatible type. -- -- The basic ways to signal a failed conversion are as follows: -- -- -- -- An example type and instance using typeMismatch: -- --
--   -- Allow ourselves to write Text literals.
--   {-# LANGUAGE OverloadedStrings #-}
--   
--   data Coord = Coord { x :: Double, y :: Double }
--   
--   instance FromJSON Coord where
--       parseJSON (Object v) = Coord
--           <$> v .: "x"
--           <*> v .: "y"
--   
--       -- We do not expect a non-Object value here.
--       -- We could use mzero to fail, but typeMismatch
--       -- gives a much more informative error message.
--       parseJSON invalid    = typeMismatch "Coord" invalid
--   
-- -- For this common case of only being concerned with a single type of -- JSON value, the functions withObject, withNumber, etc. -- are provided. Their use is to be preferred when possible, since they -- are more terse. Using withObject, we can rewrite the above -- instance (assuming the same language extension and data type) as: -- --
--   instance FromJSON Coord where
--       parseJSON = withObject "Coord" $ \v -> Coord
--           <$> v .: "x"
--           <*> v .: "y"
--   
-- -- Instead of manually writing your FromJSON instance, there are -- two options to do it automatically: -- -- -- -- To use the second, simply add a deriving Generic -- clause to your datatype and declare a FromJSON instance for -- your datatype without giving a definition for parseJSON. -- -- For example, the previous example can be simplified to just: -- --
--   {-# LANGUAGE DeriveGeneric #-}
--   
--   import GHC.Generics
--   
--   data Coord = Coord { x :: Double, y :: Double } deriving Generic
--   
--   instance FromJSON Coord
--   
-- -- The default implementation will be equivalent to parseJSON = -- genericParseJSON defaultOptions; If you need -- different options, you can customize the generic decoding by defining: -- --
--   customOptions = defaultOptions
--                   { fieldLabelModifier = map toUpper
--                   }
--   
--   instance FromJSON Coord where
--       parseJSON = genericParseJSON customOptions
--   
class FromJSON a parseJSON :: FromJSON a => Value -> Parser a parseJSONList :: FromJSON a => Value -> Parser [a] -- | Parse any datatype with a Generic instance from a JSON -- Value. gparseJson :: (Generic a, GfromJson Rep a, ConNames Rep a, GIsEnum Rep a) => Value -> Parser a -- | Read the docs for ToJSONKey first. This class is a conversion -- in the opposite direction. If you have a newtype wrapper around -- Text, the recommended way to define instances is with -- generalized newtype deriving: -- --
--   newtype SomeId = SomeId { getSomeId :: Text }
--     deriving (Eq,Ord,Hashable,FromJSONKey)
--   
class FromJSONKey a -- | Strategy for parsing the key of a map-like container. fromJSONKey :: FromJSONKey a => FromJSONKeyFunction a -- | This is similar in spirit to the readList method of -- Read. It makes it possible to give String keys special -- treatment without using OverlappingInstances. End users -- should always be able to use the default implementation of this -- method. fromJSONKeyList :: FromJSONKey a => FromJSONKeyFunction [a] -- | This type is related to ToJSONKeyFunction. If -- FromJSONKeyValue is used in the FromJSONKey instance, -- then ToJSONKeyValue should be used in the ToJSONKey -- instance. The other three data constructors for this type all -- correspond to ToJSONKeyText. Strictly speaking, -- FromJSONKeyTextParser is more powerful than -- FromJSONKeyText, which is in turn more powerful than -- FromJSONKeyCoerce. For performance reasons, these exist as -- three options instead of one. data FromJSONKeyFunction a -- | uses coerce (unsafeCoerce in older GHCs) FromJSONKeyCoerce :: !CoerceText a -> FromJSONKeyFunction a -- | conversion from Text that always succeeds FromJSONKeyText :: !Text -> a -> FromJSONKeyFunction a -- | conversion from Text that may fail FromJSONKeyTextParser :: !Text -> Parser a -> FromJSONKeyFunction a -- | conversion for non-textual keys FromJSONKeyValue :: !Value -> Parser a -> FromJSONKeyFunction a -- | Convert a value from JSON, failing if the types do not match. fromJSON :: FromJSON a => Value -> Result a -- | Efficiently deserialize a JSON value from a lazy ByteString. If -- this fails due to incomplete or invalid input, Nothing is -- returned. -- -- The input must consist solely of a JSON document, with no trailing -- data except for whitespace. -- -- This function parses immediately, but defers conversion. See -- json for details. decode :: FromJSON a => ByteString -> Maybe a -- | Efficiently deserialize a JSON value from a lazy ByteString. If -- this fails due to incomplete or invalid input, Nothing is -- returned. -- -- The input must consist solely of a JSON document, with no trailing -- data except for whitespace. -- -- This function parses and performs conversion immediately. See -- json' for details. decode' :: FromJSON a => ByteString -> Maybe a -- | Efficiently deserialize a JSON value from a strict ByteString. -- If this fails due to incomplete or invalid input, Nothing is -- returned. -- -- The input must consist solely of a JSON document, with no trailing -- data except for whitespace. -- -- This function parses immediately, but defers conversion. See -- json for details. decodeStrict :: FromJSON a => ByteString -> Maybe a -- | Efficiently deserialize a JSON value from a strict ByteString. -- If this fails due to incomplete or invalid input, Nothing is -- returned. -- -- The input must consist solely of a JSON document, with no trailing -- data except for whitespace. -- -- This function parses and performs conversion immediately. See -- json' for details. decodeStrict' :: FromJSON a => ByteString -> Maybe a -- | Like decode but returns an error message when decoding fails. eitherDecode :: FromJSON a => ByteString -> Either String a -- | Like decode' but returns an error message when decoding fails. eitherDecode' :: FromJSON a => ByteString -> Either String a -- | Like decodeStrict but returns an error message when decoding -- fails. eitherDecodeStrict :: FromJSON a => ByteString -> Either String a -- | Like decodeStrict' but returns an error message when decoding -- fails. eitherDecodeStrict' :: FromJSON a => ByteString -> Either String a decodeWith :: () => Parser Value -> Value -> Result a -> ByteString -> Maybe a decodeStrictWith :: () => Parser Value -> Value -> Result a -> ByteString -> Maybe a eitherDecodeWith :: () => Parser Value -> Value -> IResult a -> ByteString -> Either (JSONPath, String) a eitherDecodeStrictWith :: () => Parser Value -> Value -> IResult a -> ByteString -> Either (JSONPath, String) a -- | withObject expected f value applies f to the -- Object when value is an Object and fails using -- typeMismatch expected otherwise. withObject :: () => String -> Object -> Parser a -> Value -> Parser a -- | withText expected f value applies f to the -- Text when value is a String and fails using -- typeMismatch expected otherwise. withText :: () => String -> Text -> Parser a -> Value -> Parser a -- | withArray expected f value applies f to the -- Array when value is an Array and fails using -- typeMismatch expected otherwise. withArray :: () => String -> Array -> Parser a -> Value -> Parser a -- | withScientific expected f value applies f to -- the Scientific number when value is a Number -- and fails using typeMismatch expected otherwise. . -- Warning: If you are converting from a scientific to an -- unbounded type such as Integer you may want to add a -- restriction on the size of the exponent (see -- withBoundedScientific) to prevent malicious input from filling -- up the memory of the target system. withScientific :: () => String -> Scientific -> Parser a -> Value -> Parser a -- | withBool expected f value applies f to the -- Bool when value is a Bool and fails using -- typeMismatch expected otherwise. withBool :: () => String -> Bool -> Parser a -> Value -> Parser a -- | Decode a nested JSON-encoded string. withEmbeddedJSON :: () => String -> Value -> Parser a -> Value -> Parser a -- | Retrieve the value associated with the given key of an Object. -- The result is empty if the key is not present or the value -- cannot be converted to the desired type. -- -- This accessor is appropriate if the key and value must be -- present in an object for it to be valid. If the key and value are -- optional, use .:? instead. (.:) :: FromJSON a => Object -> Text -> Parser a -- | Retrieve the value associated with the given key of an Object. -- The result is Nothing if the key is not present or if its value -- is Null, or empty if the value cannot be converted to -- the desired type. -- -- This accessor is most useful if the key and value can be absent from -- an object without affecting its validity. If the key and value are -- mandatory, use .: instead. (.:?) :: FromJSON a => Object -> Text -> Parser Maybe a -- | Retrieve the value associated with the given key of an Object. -- The result is Nothing if the key is not present or -- empty if the value cannot be converted to the desired type. -- -- This differs from .:? by attempting to parse Null the -- same as any other JSON value, instead of interpreting it as -- Nothing. (.:!) :: FromJSON a => Object -> Text -> Parser Maybe a -- | Helper for use in combination with .:? to provide default -- values for optional JSON object fields. -- -- This combinator is most useful if the key and value can be absent from -- an object without affecting its validity and we know a default value -- to assign in that case. If the key and value are mandatory, use -- .: instead. -- -- Example usage: -- --
--   v1 <- o .:? "opt_field_with_dfl" .!= "default_val"
--   v2 <- o .:  "mandatory_field"
--   v3 <- o .:? "opt_field2"
--   
(.!=) :: () => Parser Maybe a -> a -> Parser a -- | Function variant of .:. parseField :: FromJSON a => Object -> Text -> Parser a -- | Function variant of .:?. parseFieldMaybe :: FromJSON a => Object -> Text -> Parser Maybe a -- | Function variant of .:!. parseFieldMaybe' :: FromJSON a => Object -> Text -> Parser Maybe a -- | Variant of .: with explicit parser function. -- -- E.g. explicitParseField parseJSON1 :: -- (FromJSON1 f, FromJSON a) -> Object -> -- Text -> Parser (f a) explicitParseField :: () => Value -> Parser a -> Object -> Text -> Parser a -- | Variant of .:? with explicit parser function. explicitParseFieldMaybe :: () => Value -> Parser a -> Object -> Text -> Parser Maybe a -- | Variant of .:! with explicit parser function. explicitParseFieldMaybe' :: () => Value -> Parser a -> Object -> Text -> Parser Maybe a -- | A JSON parser. N.B. This might not fit your usual understanding of -- "parser". Instead you might like to think of Parser as a "parse -- result", i.e. a parser to which the input has already been applied. data Parser a -- | The result of running a Parser. data Result a Error :: String -> Result a Success :: a -> Result a -- | Run a Parser. parse :: () => a -> Parser b -> a -> Result b -- | Run a Parser with a Maybe result type. parseMaybe :: () => a -> Parser b -> a -> Maybe b -- | Run a Parser with an Either result type. If the parse -- fails, the Left payload will contain an error message. parseEither :: () => a -> Parser b -> a -> Either String b -- | Run a Parser. iparse :: () => a -> Parser b -> a -> IResult b -- | Parse a top-level JSON value. -- -- The conversion of a parsed value to a Haskell value is deferred until -- the Haskell value is needed. This may improve performance if only a -- subset of the results of conversions are needed, but at a cost in -- thunk allocation. -- -- This function is an alias for value. In aeson 0.8 and earlier, -- it parsed only object or array types, in conformance with the -- now-obsolete RFC 4627. json :: Parser Value -- | Parse a top-level JSON value. -- -- This is a strict version of json which avoids building up -- thunks during parsing; it performs all conversions immediately. Prefer -- this version if most of the JSON data needs to be accessed. -- -- This function is an alias for value'. In aeson 0.8 and earlier, -- it parsed only object or array types, in conformance with the -- now-obsolete RFC 4627. json' :: Parser Value -- | Parse any JSON value. You should usually json in preference to -- this function, as this function relaxes the object-or-array -- requirement of RFC 4627. -- -- In particular, be careful in using this function if you think your -- code might interoperate with Javascript. A naïve Javascript library -- that parses JSON data using eval is vulnerable to attack -- unless the encoded data represents an object or an array. JSON -- implementations in other languages conform to that same restriction to -- preserve interoperability and security. value :: Parser Value -- | Strict version of value. See also json'. value' :: Parser Value -- | Parse a quoted JSON string. jstring :: Parser Text -- | Parse a JSON number. scientific :: Parser Scientific module Json.Encode -- | A JSON "array" (sequence). type Array = Vector Value -- | The empty array. emptyArray :: Value -- | A JSON "object" (key/value map). type Object = HashMap Text Value -- | The empty object. emptyObject :: Value -- | A type that can be converted to JSON. -- -- Instances in general must specify toJSON and -- should (but don't need to) specify toEncoding. -- -- An example type and instance: -- --
--   -- Allow ourselves to write Text literals.
--   {-# LANGUAGE OverloadedStrings #-}
--   
--   data Coord = Coord { x :: Double, y :: Double }
--   
--   instance ToJSON Coord where
--     toJSON (Coord x y) = object ["x" .= x, "y" .= y]
--   
--     toEncoding (Coord x y) = pairs ("x" .= x <> "y" .= y)
--   
-- -- Instead of manually writing your ToJSON instance, there are two -- options to do it automatically: -- -- -- -- To use the second, simply add a deriving Generic -- clause to your datatype and declare a ToJSON instance. If you -- require nothing other than defaultOptions, it is sufficient to -- write (and this is the only alternative where the default -- toJSON implementation is sufficient): -- --
--   {-# LANGUAGE DeriveGeneric #-}
--   
--   import GHC.Generics
--   
--   data Coord = Coord { x :: Double, y :: Double } deriving Generic
--   
--   instance ToJSON Coord where
--       toEncoding = genericToEncoding defaultOptions
--   
-- -- If on the other hand you wish to customize the generic decoding, you -- have to implement both methods: -- --
--   customOptions = defaultOptions
--                   { fieldLabelModifier = map toUpper
--                   }
--   
--   instance ToJSON Coord where
--       toJSON     = genericToJSON customOptions
--       toEncoding = genericToEncoding customOptions
--   
-- -- Previous versions of this library only had the toJSON method. -- Adding toEncoding had to reasons: -- --
    --
  1. toEncoding is more efficient for the common case that the output -- of toJSON is directly serialized to a ByteString. -- Further, expressing either method in terms of the other would be -- non-optimal.
  2. --
  3. The choice of defaults allows a smooth transition for existing -- users: Existing instances that do not define toEncoding still -- compile and have the correct semantics. This is ensured by making the -- default implementation of toEncoding use toJSON. This -- produces correct results, but since it performs an intermediate -- conversion to a Value, it will be less efficient than directly -- emitting an Encoding. (this also means that specifying nothing -- more than instance ToJSON Coord would be sufficient as a -- generically decoding instance, but there probably exists no good -- reason to not specify toEncoding in new instances.)
  4. --
class ToJSON a -- | Convert a Haskell value to a JSON-friendly intermediate type. toJSON :: ToJSON a => a -> Value -- | Encode a Haskell value as JSON. -- -- The default implementation of this method creates an intermediate -- Value using toJSON. This provides source-level -- compatibility for people upgrading from older versions of this -- library, but obviously offers no performance advantage. -- -- To benefit from direct encoding, you must provide an -- implementation for this method. The easiest way to do so is by having -- your types implement Generic using the DeriveGeneric -- extension, and then have GHC generate a method body as follows. -- --
--   instance ToJSON Coord where
--       toEncoding = genericToEncoding defaultOptions
--   
toEncoding :: ToJSON a => a -> Encoding toJSONList :: ToJSON a => [a] -> Value toEncodingList :: ToJSON a => [a] -> Encoding -- | Convert any datatype with a Generic instance to a JSON -- Value. gtoJson :: (Generic a, GtoJson Rep a, ConNames Rep a, GIsEnum Rep a) => a -> Value -- | Typeclass for types that can be used as the key of a map-like -- container (like Map or HashMap). For example, since -- Text has a ToJSONKey instance and Char has a -- ToJSON instance, we can encode a value of type Map -- Text Char: -- --
--   >>> LBC8.putStrLn $ encode $ Map.fromList [("foo" :: Text, 'a')]
--   {"foo":"a"}
--   
-- -- Since Int also has a ToJSONKey instance, we can -- similarly write: -- --
--   >>> LBC8.putStrLn $ encode $ Map.fromList [(5 :: Int, 'a')]
--   {"5":"a"}
--   
-- -- JSON documents only accept strings as object keys. For any type from -- base that has a natural textual representation, it can be -- expected that its ToJSONKey instance will choose that -- representation. -- -- For data types that lack a natural textual representation, an -- alternative is provided. The map-like container is represented as a -- JSON array instead of a JSON object. Each value in the array is an -- array with exactly two values. The first is the key and the second is -- the value. -- -- For example, values of type '[Text]' cannot be encoded to a string, so -- a Map with keys of type '[Text]' is encoded as follows: -- --
--   >>> LBC8.putStrLn $ encode $ Map.fromList [(["foo","bar","baz" :: Text], 'a')]
--   [[["foo","bar","baz"],"a"]]
--   
-- -- The default implementation of ToJSONKey chooses this method of -- encoding a key, using the ToJSON instance of the type. -- -- To use your own data type as the key in a map, all that is needed is -- to write a ToJSONKey (and possibly a FromJSONKey) -- instance for it. If the type cannot be trivially converted to and from -- Text, it is recommended that ToJSONKeyValue is used. -- Since the default implementations of the typeclass methods can build -- this from a ToJSON instance, there is nothing that needs to be -- written: -- --
--   data Foo = Foo { fooAge :: Int, fooName :: Text }
--     deriving (Eq,Ord,Generic)
--   instance ToJSON Foo
--   instance ToJSONKey Foo
--   
-- -- That's it. We can now write: -- --
--   >>> let m = Map.fromList [(Foo 4 "bar",'a'),(Foo 6 "arg",'b')]
--   
--   >>> LBC8.putStrLn $ encode m
--   [[{"fooName":"bar","fooAge":4},"a"],[{"fooName":"arg","fooAge":6},"b"]]
--   
-- -- The next case to consider is if we have a type that is a newtype -- wrapper around Text. The recommended approach is to use -- generalized newtype deriving: -- --
--   newtype RecordId = RecordId { getRecordId :: Text}
--     deriving (Eq,Ord,ToJSONKey)
--   
-- -- Then we may write: -- --
--   >>> LBC8.putStrLn $ encode $ Map.fromList [(RecordId "abc",'a')]
--   {"abc":"a"}
--   
-- -- Simple sum types are a final case worth considering. Suppose we have: -- --
--   data Color = Red | Green | Blue
--     deriving (Show,Read,Eq,Ord)
--   
-- -- It is possible to get the ToJSONKey instance for free as we did -- with Foo. However, in this case, we have a natural way to go -- to and from Text that does not require any escape sequences. -- So, in this example, ToJSONKeyText will be used instead of -- ToJSONKeyValue. The Show instance can be used to help -- write ToJSONKey: -- --
--   instance ToJSONKey Color where
--     toJSONKey = ToJSONKeyText f g
--       where f = Text.pack . show
--             g = text . Text.pack . show
--             -- text function is from Data.Aeson.Encoding
--   
-- -- The situation of needing to turning function a -> Text -- into a ToJSONKeyFunction is common enough that a special -- combinator is provided for it. The above instance can be rewritten as: -- --
--   instance ToJSONKey Color where
--     toJSONKey = toJSONKeyText (Text.pack . show)
--   
-- -- The performance of the above instance can be improved by not using -- String as an intermediate step when converting to Text. -- One option for improving performance would be to use template haskell -- machinery from the text-show package. However, even with the -- approach, the Encoding (a wrapper around a bytestring builder) -- is generated by encoding the Text to a ByteString, an -- intermediate step that could be avoided. The fastest possible -- implementation would be: -- --
--   -- Assuming that OverloadedStrings is enabled
--   instance ToJSONKey Color where
--     toJSONKey = ToJSONKeyText f g
--       where f x = case x of {Red -> "Red";Green ->"Green";Blue -> "Blue"}
--             g x = case x of {Red -> text "Red";Green -> text "Green";Blue -> text "Blue"}
--             -- text function is from Data.Aeson.Encoding
--   
-- -- This works because GHC can lift the encoded values out of the case -- statements, which means that they are only evaluated once. This -- approach should only be used when there is a serious need to maximize -- performance. class ToJSONKey a -- | Strategy for rendering the key for a map-like container. toJSONKey :: ToJSONKey a => ToJSONKeyFunction a -- | This is similar in spirit to the showsList method of -- Show. It makes it possible to give String keys special -- treatment without using OverlappingInstances. End users -- should always be able to use the default implementation of this -- method. toJSONKeyList :: ToJSONKey a => ToJSONKeyFunction [a] data ToJSONKeyFunction a -- | key is encoded to string, produces object ToJSONKeyText :: !a -> Text -> !a -> Encoding' Text -> ToJSONKeyFunction a -- | key is encoded to value, produces array ToJSONKeyValue :: !a -> Value -> !a -> Encoding -> ToJSONKeyFunction a -- | Efficiently serialize a JSON value as a lazy ByteString. -- -- This is implemented in terms of the ToJSON class's -- toEncoding method. encode :: ToJSON a => a -> ByteString -- | Encode a JSON Value to a Data.Text.Lazy -- -- Note: uses toEncoding encodeToLazyText :: ToJSON a => a -> Text -- | A drop-in replacement for aeson's encode function, producing -- JSON-ByteStrings for human readers. -- -- Follows the default configuration in defConfig. encodePretty :: ToJSON a => a -> ByteString -- | A key-value pair for encoding a JSON object. class KeyValue kv (.=) :: (KeyValue kv, ToJSON v) => Text -> v -> kv infixr 8 .= -- | Create a Value from a list of name/value Pairs. If -- duplicate keys arise, earlier keys and their associated values win. object :: [Pair] -> Value -- | Often used synonym for Encoding'. type Encoding = Encoding' Value -- | An encoding of a JSON value. -- -- tag represents which kind of JSON the Encoding is encoding -- to, we reuse Text and Value as tags here. data Encoding' tag encodingToLazyByteString :: () => Encoding' a -> ByteString -- | A series of values that, when encoded, should be separated by commas. -- Since 0.11.0.0, the .= operator is overloaded to create -- either (Text, Value) or Series. You can use Series -- when encoding directly to a bytestring builder as in the following -- example: -- --
--   toEncoding (Person name age) = pairs ("name" .= name <> "age" .= age)
--   
data Series -- | Encode a series of key/value pairs, separated by commas. pairs :: Series -> Encoding pair :: Text -> Encoding -> Series pair' :: Encoding' Text -> Encoding -> Series -- | Encode a Foldable as a JSON array. foldable :: (Foldable t, ToJSON a) => t a -> Encoding emptyArray_ :: Encoding emptyObject_ :: Encoding text :: () => Text -> Encoding' a lazyText :: () => Text -> Encoding' a string :: () => String -> Encoding' a list :: () => a -> Encoding -> [a] -> Encoding -- | Encode as JSON object dict :: () => k -> Encoding' Text -> v -> Encoding -> forall a. () => k -> v -> a -> a -> a -> m -> a -> m -> Encoding null_ :: Encoding bool :: Bool -> Encoding int8 :: Int8 -> Encoding int16 :: Int16 -> Encoding int32 :: Int32 -> Encoding int64 :: Int64 -> Encoding int :: Int -> Encoding word8 :: Word8 -> Encoding word16 :: Word16 -> Encoding word32 :: Word32 -> Encoding word64 :: Word64 -> Encoding word :: Word -> Encoding integer :: Integer -> Encoding float :: Float -> Encoding double :: Double -> Encoding scientific :: Scientific -> Encoding int8Text :: () => Int8 -> Encoding' a int16Text :: () => Int16 -> Encoding' a int32Text :: () => Int32 -> Encoding' a int64Text :: () => Int64 -> Encoding' a intText :: () => Int -> Encoding' a word8Text :: () => Word8 -> Encoding' a word16Text :: () => Word16 -> Encoding' a word32Text :: () => Word32 -> Encoding' a word64Text :: () => Word64 -> Encoding' a wordText :: () => Word -> Encoding' a integerText :: () => Integer -> Encoding' a floatText :: () => Float -> Encoding' a doubleText :: () => Double -> Encoding' a scientificText :: () => Scientific -> Encoding' a day :: () => Day -> Encoding' a localTime :: () => LocalTime -> Encoding' a utcTime :: () => UTCTime -> Encoding' a timeOfDay :: () => TimeOfDay -> Encoding' a zonedTime :: () => ZonedTime -> Encoding' a value :: Value -> Encoding aesonQQ :: QuasiQuoter -- | A newtype wrapper for UTCTime that uses the same non-standard -- serialization format as Microsoft .NET, whose System.DateTime -- type is by default serialized to JSON as in the following example: -- --
--   /Date(1302547608878)/
--   
-- -- The number represents milliseconds since the Unix epoch. newtype DotNetTime DotNetTime :: UTCTime -> DotNetTime -- | Acquire the underlying value. [fromDotNetTime] :: DotNetTime -> UTCTime module Label class IsLabel (x :: Symbol) a fromLabel :: IsLabel x a => a module List -- | 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 \\ function is list difference (non-associative). In the -- result of xs \\ ys, the first occurrence of -- each element of ys in turn (if any) has been removed from -- xs. Thus -- --
--   (xs ++ ys) \\ xs == ys.
--   
-- --
--   >>> "Hello World!" \\ "ell W"
--   "Hoorld!"
--   
-- -- It is a special case of deleteFirstsBy, which allows the -- programmer to supply their own equality test. (\\) :: Eq a => [a] -> [a] -> [a] infix 5 \\ -- | Are all elements the same. -- --
--   allSame [1,1,2] == False
--   allSame [1,1,1] == True
--   allSame [1]     == True
--   allSame []      == True
--   allSame (1:1:2:undefined) == False
--   \xs -> allSame xs == (length (nub xs) <= 1)
--   
allSame :: Eq a => [a] -> Bool -- | Is there any element which occurs more than once. -- --
--   anySame [1,1,2] == True
--   anySame [1,2,3] == False
--   anySame (1:2:1:undefined) == True
--   anySame [] == False
--   \xs -> anySame xs == (length (nub xs) < length xs)
--   
anySame :: Eq a => [a] -> Bool -- | 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]) -- | Find the first instance of needle in haystack. The -- first element of the returned tuple is the prefix of haystack -- before needle is matched. The second is the remainder of -- haystack, starting with the match. If you want the remainder -- without the match, use stripInfix. -- --
--   breakOn "::" "a::b::c" == ("a", "::b::c")
--   breakOn "/" "foobar"   == ("foobar", "")
--   \needle haystack -> let (prefix,match) = breakOn needle haystack in prefix ++ match == haystack
--   
breakOn :: Eq a => [a] -> [a] -> ([a], [a]) -- | Similar to breakOn, but searches from the end of the string. -- -- The first element of the returned tuple is the prefix of -- haystack up to and including the last match of -- needle. The second is the remainder of haystack, -- following the match. -- --
--   breakOnEnd "::" "a::b::c" == ("a::b::", "c")
--   
breakOnEnd :: Eq a => [a] -> [a] -> ([a], [a]) -- | Break, but from the end. -- --
--   breakEnd isLower "youRE" == ("you","RE")
--   breakEnd isLower "youre" == ("youre","")
--   breakEnd isLower "YOURE" == ("","YOURE")
--   \f xs -> breakEnd (not . f) xs == spanEnd f  xs
--   
breakEnd :: () => a -> Bool -> [a] -> ([a], [a]) -- | A useful recursion pattern for processing a list to produce a new -- list, often used for "chopping" up the input list. Typically chop is -- called with some function that will consume an initial prefix of the -- list and produce a value and the rest of the list. -- -- For example, many common Prelude functions can be implemented in terms -- of chop: -- --
--   group :: (Eq a) => [a] -> [[a]]
--   group = chop (\ xs@(x:_) -> span (==x) xs)
--   
--   words :: String -> [String]
--   words = filter (not . null) . chop (span (not . isSpace) . dropWhile isSpace)
--   
chop :: () => [a] -> (b, [a]) -> [a] -> [b] -- | Append an element to the start of a list, an alias for '(:)'. -- --
--   cons 't' "est" == "test"
--   \x xs -> uncons (cons x xs) == Just (x,xs)
--   
cons :: () => 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 :: () => [a] -> [a] -- | delete x removes the first occurrence of x -- from its list argument. For example, -- --
--   >>> delete 'a' "banana"
--   "bnana"
--   
-- -- It is a special case of deleteBy, which allows the programmer -- to supply their own equality test. delete :: Eq a => a -> [a] -> [a] -- | The deleteBy function behaves like delete, but takes a -- user-supplied equality predicate. -- --
--   >>> deleteBy (<=) 4 [1..10]
--   [1,2,3,5,6,7,8,9,10]
--   
deleteBy :: () => a -> a -> Bool -> a -> [a] -> [a] -- | The deleteFirstsBy function takes a predicate and two lists and -- returns the first list with the first occurrence of each element of -- the second list removed. deleteFirstsBy :: () => a -> a -> Bool -> [a] -> [a] -> [a] -- | Are two lists disjoint, with no elements in common. -- --
--   disjoint [1,2,3] [4,5] == True
--   disjoint [1,2,3] [4,1] == False
--   
disjoint :: Eq a => [a] -> [a] -> Bool -- | Divides up an input list into a set of sublists, according to -- n and m input specifications you provide. Each -- sublist will have n items, and the start of each sublist will -- be offset by m items from the previous one. -- --
--   divvy 5 5 [1..20] == [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]
--   
-- -- In the case where a source list's trailing elements do no fill an -- entire sublist, those trailing elements will be dropped. -- --
--   divvy 5 2 [1..10] == [[1,2,3,4,5],[3,4,5,6,7],[5,6,7,8,9]]
--   
-- -- As an example, you can generate a moving average over a list of -- prices: -- --
--   type Prices = [Float]
--   type AveragePrices = [Float]
--   
--   average :: [Float] -> Float
--   average xs = sum xs / (fromIntegral $ length xs)
--   
--   simpleMovingAverage :: Prices -> AveragePrices
--   simpleMovingAverage priceList =
--     map average divvyedPrices
--       where divvyedPrices = divvy 20 1 priceList
--   
divvy :: () => Int -> Int -> [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] -- | Drop a number of elements from the end of the list. -- --
--   dropEnd 3 "hello"  == "he"
--   dropEnd 5 "bye"    == ""
--   dropEnd (-1) "bye" == "bye"
--   \i xs -> dropEnd i xs `isPrefixOf` xs
--   \i xs -> length (dropEnd i xs) == max 0 (length xs - max 0 i)
--   \i -> take 3 (dropEnd 5 [i..]) == take 3 [i..]
--   
dropEnd :: () => Int -> [a] -> [a] -- | Drops the given prefix from a list. It returns the original sequence -- if the sequence doesn't start with the given prefix. -- --
--   dropPrefix "Mr. " "Mr. Men" == "Men"
--   dropPrefix "Mr. " "Dr. Men" == "Dr. Men"
--   
dropPrefix :: Eq a => [a] -> [a] -> [a] -- | Drops the given suffix from a list. It returns the original sequence -- if the sequence doesn't end with the given suffix. -- --
--   dropSuffix "!" "Hello World!"  == "Hello World"
--   dropSuffix "!" "Hello World!!" == "Hello World!"
--   dropSuffix "!" "Hello World."  == "Hello World."
--   
dropSuffix :: Eq a => [a] -> [a] -> [a] -- | dropWhile p xs returns the suffix remaining after -- takeWhile p xs: -- --
--   dropWhile (< 3) [1,2,3,4,5,1,2,3] == [3,4,5,1,2,3]
--   dropWhile (< 9) [1,2,3] == []
--   dropWhile (< 0) [1,2,3] == [1,2,3]
--   
dropWhile :: () => a -> Bool -> [a] -> [a] -- | The dropWhileEnd function drops the largest suffix of a list in -- which the given predicate holds for all elements. For example: -- --
--   >>> dropWhileEnd isSpace "foo\n"
--   "foo"
--   
-- --
--   >>> dropWhileEnd isSpace "foo bar"
--   "foo bar"
--   
-- --
--   dropWhileEnd isSpace ("foo\n" ++ undefined) == "foo" ++ undefined
--   
dropWhileEnd :: () => a -> Bool -> [a] -> [a] -- | The elemIndex function returns the index of the first element -- in the given list which is equal (by ==) to the query element, -- or Nothing if there is no such element. -- --
--   >>> elemIndex 4 [0..]
--   Just 4
--   
elemIndex :: Eq a => a -> [a] -> Maybe Int -- | The elemIndices function extends elemIndex, by returning -- the indices of all elements equal to the query element, in ascending -- order. -- --
--   >>> elemIndices 'o' "Hello World"
--   [4,7]
--   
elemIndices :: Eq a => a -> [a] -> [Int] -- | Split into chunks terminated by the given subsequence. Equivalent to -- split . dropFinalBlank . dropDelims . -- onSublist. For example: -- --
--   endBy ";" "foo;bar;baz;" == ["foo","bar","baz"]
--   
-- -- Note also that the lines function from Data.List is -- equivalent to endBy "\n". endBy :: Eq a => [a] -> [a] -> [[a]] -- | filter, applied to a predicate and a list, returns the list of -- those elements that satisfy the predicate; i.e., -- --
--   filter p xs = [ x | x <- xs, p x]
--   
filter :: () => a -> Bool -> [a] -> [a] -- | The findIndex function takes a predicate and a list and returns -- the index of the first element in the list satisfying the predicate, -- or Nothing if there is no such element. -- --
--   >>> findIndex isSpace "Hello World!"
--   Just 5
--   
findIndex :: () => a -> Bool -> [a] -> Maybe Int -- | The findIndices function extends findIndex, by returning -- the indices of all elements satisfying the predicate, in ascending -- order. -- --
--   >>> findIndices (`elem` "aeiou") "Hello World!"
--   [1,4,7]
--   
findIndices :: () => a -> Bool -> [a] -> [Int] -- | The genericDrop function is an overloaded version of -- drop, which accepts any Integral value as the number of -- elements to drop. genericDrop :: Integral i => i -> [a] -> [a] -- | The genericIndex function is an overloaded version of -- !!, which accepts any Integral value as the index. genericIndex :: Integral i => [a] -> i -> a -- | The genericLength function is an overloaded version of -- length. In particular, instead of returning an Int, it -- returns any type which is an instance of Num. It is, however, -- less efficient than length. genericLength :: Num i => [a] -> i -- | The genericReplicate function is an overloaded version of -- replicate, which accepts any Integral value as the -- number of repetitions to make. genericReplicate :: Integral i => i -> a -> [a] -- | The genericSplitAt function is an overloaded version of -- splitAt, which accepts any Integral value as the -- position at which to split. genericSplitAt :: Integral i => i -> [a] -> ([a], [a]) -- | The 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 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 groupBy function is the non-overloaded version of -- group. groupBy :: () => a -> a -> Bool -> [a] -> [[a]] -- | A version of group where the equality is done on some extracted -- value. groupOn :: Eq b => a -> b -> [a] -> [[a]] -- | A combination of group and sort. -- --
--   groupSort [(1,'t'),(3,'t'),(2,'e'),(2,'s')] == [(1,"t"),(2,"es"),(3,"t")]
--   \xs -> map fst (groupSort xs) == sort (nub (map fst xs))
--   \xs -> concatMap snd (groupSort xs) == map snd (sortOn fst xs)
--   
groupSort :: Ord k => [(k, v)] -> [(k, [v])] -- | A combination of group and sort, using a predicate to -- compare on. -- --
--   groupSortBy (compare `on` length) ["test","of","sized","item"] == [["of"],["test","item"],["sized"]]
--   
groupSortBy :: () => a -> a -> Ordering -> [a] -> [[a]] -- | A combination of group and sort, using a part of the -- value to compare on. -- --
--   groupSortOn length ["test","of","sized","item"] == [["of"],["test","item"],["sized"]]
--   
groupSortOn :: Ord b => a -> b -> [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 insert function takes an element and a list and inserts the -- element into the list at the first position where it is less than or -- equal to the next element. In particular, if the list is sorted before -- the call, the result will also be sorted. It is a special case of -- insertBy, which allows the programmer to supply their own -- comparison function. -- --
--   >>> insert 4 [1,2,3,5,6,7]
--   [1,2,3,4,5,6,7]
--   
insert :: Ord a => a -> [a] -> [a] -- | The non-overloaded version of insert. insertBy :: () => a -> a -> Ordering -> a -> [a] -> [a] -- | intercalate xs xss is equivalent to (concat -- (intersperse xs xss)). It inserts the list xs in -- between the lists in xss and concatenates the result. -- --
--   >>> intercalate ", " ["Lorem", "ipsum", "dolor"]
--   "Lorem, ipsum, dolor"
--   
intercalate :: () => [a] -> [[a]] -> [a] -- | The intersect function takes the list intersection of two -- lists. For example, -- --
--   >>> [1,2,3,4] `intersect` [2,4,6,8]
--   [2,4]
--   
-- -- If the first list contains duplicates, so will the result. -- --
--   >>> [1,2,2,3,4] `intersect` [6,4,4,2]
--   [2,2,4]
--   
-- -- It is a special case of intersectBy, which allows the -- programmer to supply their own equality test. If the element is found -- in both the first and the second list, the element from the first list -- will be used. intersect :: Eq a => [a] -> [a] -> [a] -- | The intersectBy function is the non-overloaded version of -- intersect. intersectBy :: () => a -> a -> Bool -> [a] -> [a] -> [a] -- | The intersperse function takes an element and a list and -- `intersperses' that element between the elements of the list. For -- example, -- --
--   >>> intersperse ',' "abcde"
--   "a,b,c,d,e"
--   
intersperse :: () => a -> [a] -> [a] -- | The isInfixOf function takes two lists and returns True -- iff the first list is contained, wholly and intact, anywhere within -- the second. -- --
--   >>> isInfixOf "Haskell" "I really like Haskell."
--   True
--   
-- --
--   >>> isInfixOf "Ial" "I really like Haskell."
--   False
--   
isInfixOf :: Eq a => [a] -> [a] -> Bool -- | The 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 isSubsequenceOf function takes two lists and returns -- True if all the elements of the first list occur, in order, in -- the second. The elements do not have to occur consecutively. -- -- isSubsequenceOf x y is equivalent to elem x -- (subsequences y). -- --

Examples

-- --
--   >>> isSubsequenceOf "GHC" "The Glorious Haskell Compiler"
--   True
--   
--   >>> isSubsequenceOf ['a','d'..'z'] ['a'..'z']
--   True
--   
--   >>> isSubsequenceOf [1..10] [10,9..0]
--   False
--   
isSubsequenceOf :: Eq a => [a] -> [a] -> Bool -- | The isSuffixOf function takes two lists and returns True -- iff the first list is a suffix of the second. The second list must be -- finite. -- --
--   >>> "ld!" `isSuffixOf` "Hello World!"
--   True
--   
-- --
--   >>> "World" `isSuffixOf` "Hello World!"
--   False
--   
isSuffixOf :: Eq a => [a] -> [a] -> Bool -- | iterate f x returns an infinite list of repeated -- applications of f to x: -- --
--   iterate f x == [x, f x, f (f x), ...]
--   
-- -- Note that iterate is lazy, potentially leading to thunk -- build-up if the consumer doesn't force each iterate. See 'iterate\'' -- for a strict variant of this function. iterate :: () => a -> a -> a -> [a] -- | 'iterate\'' is the strict version of iterate. -- -- It ensures that the result of each application of force to weak head -- normal form before proceeding. iterate' :: () => a -> a -> a -> [a] -- | lookup key assocs looks up a key in an association -- list. lookup :: Eq a => a -> [(a, b)] -> Maybe b -- | map f xs is the list obtained by applying f -- to each element of xs, i.e., -- --
--   map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn]
--   map f [x1, x2, ...] == [f x1, f x2, ...]
--   
map :: () => a -> b -> [a] -> [b] -- | O(n^2). The nub function removes duplicate elements from -- a list. In particular, it keeps only the first occurrence of each -- element. (The name nub means `essence'.) It is a special case -- of nubBy, which allows the programmer to supply their own -- equality test. -- --
--   >>> nub [1,2,3,4,3,2,1,2,4,3,5]
--   [1,2,3,4,5]
--   
nub :: Eq a => [a] -> [a] -- | The nubBy function behaves just like nub, except it uses -- a user-supplied equality predicate instead of the overloaded == -- function. -- --
--   >>> nubBy (\x y -> mod x 3 == mod y 3) [1,2,4,5,6]
--   [1,2,6]
--   
nubBy :: () => a -> a -> Bool -> [a] -> [a] -- | A version of nub where the equality is done on some extracted -- value. nubOn f is equivalent to nubBy ((==) on -- f), but has the performance advantage of only evaluating -- f once for each element in the input list. nubOn :: Eq b => a -> b -> [a] -> [a] -- | O(n log n). The nubOrd function removes duplicate -- elements from a list. In particular, it keeps only the first -- occurrence of each element. Unlike the standard nub operator, -- this version requires an Ord instance and consequently runs -- asymptotically faster. -- --
--   nubOrd "this is a test" == "this ae"
--   nubOrd (take 4 ("this" ++ undefined)) == "this"
--   \xs -> nubOrd xs == nub xs
--   
nubOrd :: Ord a => [a] -> [a] -- | A version of nubOrd with a custom predicate. -- --
--   nubOrdBy (compare `on` length) ["a","test","of","this"] == ["a","test","of"]
--   
nubOrdBy :: () => a -> a -> Ordering -> [a] -> [a] -- | A version of nubOrd which operates on a portion of the value. -- --
--   nubOrdOn length ["a","test","of","this"] == ["a","test","of"]
--   
nubOrdOn :: Ord b => a -> b -> [a] -> [a] -- | O(n log n). The nubSort function sorts and removes -- duplicate elements from a list. In particular, it keeps only the first -- occurrence of each element. -- --
--   nubSort "this is a test" == " aehist"
--   \xs -> nubSort xs == nub (sort xs)
--   
nubSort :: Ord a => [a] -> [a] -- | A version of nubSort with a custom predicate. -- --
--   nubSortBy (compare `on` length) ["a","test","of","this"] == ["a","of","test"]
--   
nubSortBy :: () => a -> a -> Ordering -> [a] -> [a] -- | A version of nubSort which operates on a portion of the value. -- --
--   nubSortOn length ["a","test","of","this"] == ["a","of","test"]
--   
nubSortOn :: Ord b => a -> b -> [a] -> [a] -- | The partition function takes a predicate a list and returns the -- pair of lists of elements which do and do not satisfy the predicate, -- respectively; i.e., -- --
--   partition p xs == (filter p xs, filter (not . p) xs)
--   
-- --
--   >>> partition (`elem` "aeiou") "Hello World!"
--   ("eoo","Hll Wrld!")
--   
partition :: () => a -> Bool -> [a] -> ([a], [a]) -- | The permutations function returns the list of all permutations -- of the argument. -- --
--   >>> permutations "abc"
--   ["abc","bac","cba","bca","cab","acb"]
--   
permutations :: () => [a] -> [[a]] -- | repeat x is an infinite list, with x the -- value of every element. 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 :: () => Int -> a -> [a] -- | reverse xs returns the elements of xs in -- reverse order. xs must be finite. reverse :: () => [a] -> [a] -- | scanl is similar to foldl, but returns a list of -- successive reduced values from the left: -- --
--   scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
--   
-- -- Note that -- --
--   last (scanl f z xs) == foldl f z xs.
--   
scanl :: () => b -> a -> b -> b -> [a] -> [b] -- | A strictly accumulating version of scanl scanl' :: () => b -> a -> b -> b -> [a] -> [b] -- | scanl1 is a variant of scanl that has no starting value -- argument: -- --
--   scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
--   
scanl1 :: () => a -> a -> a -> [a] -> [a] -- | scanr is the right-to-left dual of scanl. Note that -- --
--   head (scanr f z xs) == foldr f z xs.
--   
scanr :: () => a -> b -> b -> b -> [a] -> [b] -- | scanr1 is a variant of scanr that has no starting value -- argument. scanr1 :: () => a -> a -> a -> [a] -> [a] -- | The sort function implements a stable sorting algorithm. It is -- a special case of sortBy, which allows the programmer to supply -- their own comparison function. -- -- Elements are arranged from from lowest to highest, keeping duplicates -- in the order they appeared in the input. -- --
--   >>> sort [1,6,4,3,2,5]
--   [1,2,3,4,5,6]
--   
sort :: Ord a => [a] -> [a] -- | The 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] -- | Sort a list by comparing the results of a key function applied to each -- element. sortOn f is equivalent to sortBy (comparing -- f), but has the performance advantage of only evaluating -- f once for each element in the input list. This is called the -- decorate-sort-undecorate paradigm, or Schwartzian transform. -- -- Elements are arranged from from lowest to highest, keeping duplicates -- in the order they appeared in the input. -- --
--   >>> sortOn fst [(2, "world"), (4, "!"), (1, "Hello")]
--   [(1,"Hello"),(2,"world"),(4,"!")]
--   
sortOn :: Ord b => a -> b -> [a] -> [a] -- | span, applied to a predicate p and a list xs, -- returns a tuple where first element is longest prefix (possibly empty) -- of xs of elements that satisfy p and second element -- is the remainder of the list: -- --
--   span (< 3) [1,2,3,4,1,2,3,4] == ([1,2],[3,4,1,2,3,4])
--   span (< 9) [1,2,3] == ([1,2,3],[])
--   span (< 0) [1,2,3] == ([],[1,2,3])
--   
-- -- span p xs is equivalent to (takeWhile p xs, -- dropWhile p xs) span :: () => a -> Bool -> [a] -> ([a], [a]) -- | Span, but from the end. -- --
--   spanEnd isUpper "youRE" == ("you","RE")
--   spanEnd (not . isSpace) "x y z" == ("x y ","z")
--   \f xs -> uncurry (++) (spanEnd f xs) == xs
--   \f xs -> spanEnd f xs == swap (both reverse (span f (reverse xs)))
--   
spanEnd :: () => a -> Bool -> [a] -> ([a], [a]) -- | Splits a list into components delimited by separators, where the -- predicate returns True for a separator element. The resulting -- components do not contain the separators. Two adjacent separators -- result in an empty component in the output. -- --
--   split (== 'a') "aabbaca" == ["","","bb","c",""]
--   split (== 'a') ""        == [""]
--   split (== ':') "::xyz:abc::123::" == ["","","xyz","abc","","123","",""]
--   split (== ',') "my,list,here" == ["my","list","here"]
--   
split :: () => a -> Bool -> [a] -> [[a]] -- | splitAt n xs returns a tuple where first element is -- xs prefix of length n and second element is the -- remainder of the list: -- --
--   splitAt 6 "Hello World!" == ("Hello ","World!")
--   splitAt 3 [1,2,3,4,5] == ([1,2,3],[4,5])
--   splitAt 1 [1,2,3] == ([1],[2,3])
--   splitAt 3 [1,2,3] == ([1,2,3],[])
--   splitAt 4 [1,2,3] == ([1,2,3],[])
--   splitAt 0 [1,2,3] == ([],[1,2,3])
--   splitAt (-1) [1,2,3] == ([],[1,2,3])
--   
-- -- It is equivalent to (take n xs, drop n xs) when -- n is not _|_ (splitAt _|_ xs = _|_). -- splitAt is an instance of the more general -- genericSplitAt, in which n may be of any integral -- type. splitAt :: () => Int -> [a] -> ([a], [a]) -- | splitAtEnd n xs returns a split where the second -- element tries to contain n elements. -- --
--   splitAtEnd 3 "hello" == ("he","llo")
--   splitAtEnd 3 "he"    == ("", "he")
--   \i xs -> uncurry (++) (splitAt i xs) == xs
--   \i xs -> splitAtEnd i xs == (dropEnd i xs, takeEnd i xs)
--   
splitAtEnd :: () => Int -> [a] -> ([a], [a]) -- | Split on the given sublist. Equivalent to split . -- dropDelims . onSublist. For example: -- --
--   splitOn ".." "a..b...c....d.." == ["a","b",".c","","d",""]
--   
-- -- In some parsing combinator frameworks this is also known as -- sepBy. -- -- Note that this is the right inverse of the intercalate function -- from Data.List, that is, -- --
--   intercalate x . splitOn x === id
--   
-- -- splitOn x . intercalate x is the identity on -- certain lists, but it is tricky to state the precise conditions under -- which this holds. (For example, it is not enough to say that -- x does not occur in any elements of the input list. Working -- out why is left as an exercise for the reader.) splitOn :: Eq a => [a] -> [a] -> [[a]] -- | Append an element to the end of a list, takes O(n) time. -- --
--   snoc "tes" 't' == "test"
--   \xs x -> unsnoc (snoc xs x) == Just (xs,x)
--   
snoc :: () => [a] -> a -> [a] -- | Return the the string before and after the search string, or -- Nothing if the search string is not present. -- -- Examples: -- --
--   stripInfix "::" "a::b::c" == Just ("a", "b::c")
--   stripInfix "/" "foobar"   == Nothing
--   
stripInfix :: Eq a => [a] -> [a] -> Maybe ([a], [a]) -- | Similar to stripInfix, but searches from the end of the string. -- --
--   stripInfixEnd "::" "a::b::c" == Just ("a::b", "c")
--   
stripInfixEnd :: Eq a => [a] -> [a] -> Maybe ([a], [a]) -- | The stripPrefix function drops the given prefix from a list. It -- returns Nothing if the list did not start with the prefix -- given, or Just the list after the prefix, if it does. -- --
--   >>> stripPrefix "foo" "foobar"
--   Just "bar"
--   
-- --
--   >>> stripPrefix "foo" "foo"
--   Just ""
--   
-- --
--   >>> stripPrefix "foo" "barfoo"
--   Nothing
--   
-- --
--   >>> stripPrefix "foo" "barfoobaz"
--   Nothing
--   
stripPrefix :: Eq a => [a] -> [a] -> Maybe [a] -- | Return the prefix of the second list if its suffix matches the entire -- first list. -- -- Examples: -- --
--   stripSuffix "bar" "foobar" == Just "foo"
--   stripSuffix ""    "baz"    == Just "baz"
--   stripSuffix "foo" "quux"   == Nothing
--   
stripSuffix :: Eq a => [a] -> [a] -> Maybe [a] -- | The subsequences function returns the list of all subsequences -- of the argument. -- --
--   >>> subsequences "abc"
--   ["","a","b","ab","c","ac","bc","abc"]
--   
subsequences :: () => [a] -> [[a]] -- | The tails function returns all final segments of the argument, -- longest first. For example, -- --
--   >>> tails "abc"
--   ["abc","bc","c",""]
--   
-- -- Note that tails has the following strictness property: -- tails _|_ = _|_ : _|_ tails :: () => [a] -> [[a]] -- | 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] -- | Take a number of elements from the end of the list. -- --
--   takeEnd 3 "hello"  == "llo"
--   takeEnd 5 "bye"    == "bye"
--   takeEnd (-1) "bye" == ""
--   \i xs -> takeEnd i xs `isSuffixOf` xs
--   \i xs -> length (takeEnd i xs) == min (max 0 i) (length xs)
--   
takeEnd :: () => 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] -- | A version of takeWhile operating from the end. -- --
--   takeWhileEnd even [2,3,4,6] == [4,6]
--   
takeWhileEnd :: () => a -> Bool -> [a] -> [a] -- | The transpose function transposes the rows and columns of its -- argument. For example, -- --
--   >>> transpose [[1,2,3],[4,5,6]]
--   [[1,4],[2,5],[3,6]]
--   
-- -- If some of the rows are shorter than the following rows, their -- elements are skipped: -- --
--   >>> transpose [[10,11],[20],[],[30,31,32]]
--   [[10,20,30],[11,31],[32]]
--   
transpose :: () => [[a]] -> [[a]] -- | Decompose a list into its head and tail. If the list is empty, returns -- Nothing. If the list is non-empty, returns Just (x, -- xs), where x is the head of the list and xs its -- tail. uncons :: () => [a] -> Maybe (a, [a]) -- | 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 union function returns the list union of the two lists. For -- example, -- --
--   >>> "dog" `union` "cow"
--   "dogcw"
--   
-- -- Duplicates, and elements of the first list, are removed from the the -- second list, but if the first list contains duplicates, so will the -- result. It is a special case of unionBy, which allows the -- programmer to supply their own equality test. union :: Eq a => [a] -> [a] -> [a] -- | The unionBy function is the non-overloaded version of -- union. unionBy :: () => a -> a -> Bool -> [a] -> [a] -> [a] -- | If the list is empty returns Nothing, otherwise returns the -- init and the last. -- --
--   unsnoc "test" == Just ("tes",'t')
--   unsnoc ""     == Nothing
--   \xs -> unsnoc xs == if null xs then Nothing else Just (init xs, last xs)
--   
unsnoc :: () => [a] -> Maybe ([a], a) -- | unzip transforms a list of pairs into a list of first -- components and a list of second components. unzip :: () => [(a, b)] -> ([a], [b]) -- | The unzip3 function takes a list of triples and returns three -- lists, analogous to unzip. unzip3 :: () => [(a, b, c)] -> ([a], [b], [c]) -- | The unzip4 function takes a list of quadruples and returns four -- lists, analogous to unzip. unzip4 :: () => [(a, b, c, d)] -> ([a], [b], [c], [d]) -- | The unzip5 function takes a list of five-tuples and returns -- five lists, analogous to unzip. unzip5 :: () => [(a, b, c, d, e)] -> ([a], [b], [c], [d], [e]) -- | The unzip6 function takes a list of six-tuples and returns six -- lists, analogous to unzip. unzip6 :: () => [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f]) -- | The unzip7 function takes a list of seven-tuples and returns -- seven lists, analogous to unzip. unzip7 :: () => [(a, b, c, d, e, f, g)] -> ([a], [b], [c], [d], [e], [f], [g]) -- | A variant of words with a custom test. In particular, adjacent -- separators are discarded, as are leading or trailing separators. -- --
--   wordsBy (== ':') "::xyz:abc::123::" == ["xyz","abc","123"]
--   \s -> wordsBy isSpace s == words s
--   
wordsBy :: () => a -> Bool -> [a] -> [[a]] -- | zip takes two lists and returns a list of corresponding pairs. -- If one input list is short, excess elements of the longer list are -- discarded. -- -- zip is right-lazy: -- --
--   zip [] _|_ = []
--   
zip :: () => [a] -> [b] -> [(a, b)] -- | zip3 takes three lists and returns a list of triples, analogous -- to zip. zip3 :: () => [a] -> [b] -> [c] -> [(a, b, c)] -- | The zip4 function takes four lists and returns a list of -- quadruples, analogous to zip. zip4 :: () => [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)] -- | The zip5 function takes five lists and returns a list of -- five-tuples, analogous to zip. zip5 :: () => [a] -> [b] -> [c] -> [d] -> [e] -> [(a, b, c, d, e)] -- | The zip6 function takes six lists and returns a list of -- six-tuples, analogous to zip. zip6 :: () => [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a, b, c, d, e, f)] -- | The zip7 function takes seven lists and returns a list of -- seven-tuples, analogous to zip. zip7 :: () => [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a, b, c, d, e, f, g)] -- | zipWith generalises zip by zipping with the function -- given as the first argument, instead of a tupling function. For -- example, zipWith (+) is applied to two lists to -- produce the list of corresponding sums. -- -- zipWith is right-lazy: -- --
--   zipWith f [] _|_ = []
--   
zipWith :: () => a -> b -> c -> [a] -> [b] -> [c] -- | The zipWith3 function takes a function which combines three -- elements, as well as three lists and returns a list of their -- point-wise combination, analogous to zipWith. zipWith3 :: () => a -> b -> c -> d -> [a] -> [b] -> [c] -> [d] -- | The zipWith4 function takes a function which combines four -- elements, as well as four lists and returns a list of their point-wise -- combination, analogous to zipWith. zipWith4 :: () => a -> b -> c -> d -> e -> [a] -> [b] -> [c] -> [d] -> [e] -- | The zipWith5 function takes a function which combines five -- elements, as well as five lists and returns a list of their point-wise -- combination, analogous to zipWith. zipWith5 :: () => a -> b -> c -> d -> e -> f -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -- | The zipWith6 function takes a function which combines six -- elements, as well as six lists and returns a list of their point-wise -- combination, analogous to zipWith. zipWith6 :: () => a -> b -> c -> d -> e -> f -> g -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -- | The zipWith7 function takes a function which combines seven -- elements, as well as seven lists and returns a list of their -- point-wise combination, analogous to zipWith. zipWith7 :: () => a -> b -> c -> d -> e -> f -> g -> h -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [h] -- | A String is a list of characters. String constants in Haskell -- are values of type String. type String = [Char] -- | words breaks a string up into a list of words, which were -- delimited by white space. -- --
--   >>> words "Lorem ipsum\ndolor"
--   ["Lorem","ipsum","dolor"]
--   
words :: String -> [String] -- | unwords is an inverse operation to words. It joins words -- with separating spaces. -- --
--   >>> unwords ["Lorem", "ipsum", "dolor"]
--   "Lorem ipsum dolor"
--   
unwords :: [String] -> String -- | lines breaks a string up into a list of strings at newline -- characters. The resulting strings do not contain newlines. -- -- Note that after splitting the string at newline characters, the last -- part of the string is considered a line even if it doesn't end with a -- newline. For example, -- --
--   >>> lines ""
--   []
--   
-- --
--   >>> lines "\n"
--   [""]
--   
-- --
--   >>> lines "one"
--   ["one"]
--   
-- --
--   >>> lines "one\n"
--   ["one"]
--   
-- --
--   >>> lines "one\n\n"
--   ["one",""]
--   
-- --
--   >>> lines "one\ntwo"
--   ["one","two"]
--   
-- --
--   >>> lines "one\ntwo\n"
--   ["one","two"]
--   
-- -- Thus lines s contains at least as many elements as -- newlines in s. lines :: String -> [String] -- | unlines is an inverse operation to lines. It joins -- lines, after appending a terminating newline to each. -- --
--   >>> unlines ["Hello", "World", "!"]
--   "Hello\nWorld\n!\n"
--   
unlines :: [String] -> String -- | Convert a string to lower case. -- --
--   lower "This is A TEST" == "this is a test"
--   lower "" == ""
--   
lower :: String -> String -- | Convert a string to upper case. -- --
--   upper "This is A TEST" == "THIS IS A TEST"
--   upper "" == ""
--   
upper :: String -> String -- | Remove spaces from either side of a string. A combination of -- trimEnd and trimStart. -- --
--   trim      "  hello   " == "hello"
--   trimStart "  hello   " == "hello   "
--   trimEnd   "  hello   " == "  hello"
--   \s -> trim s == trimEnd (trimStart s)
--   
trim :: String -> String -- | Remove spaces from the start of a string, see trim. trimStart :: String -> String -- | Remove spaces from the end of a string, see trim. trimEnd :: String -> String -- | utility function converting a String to a show function that -- simply prepends the string unchanged. showString :: String -> ShowS -- | Reads a non-empty string of decimal digits. lexDigits :: ReadS String -- | Class for string-like datastructures; used by the overloaded string -- extension (-XOverloadedStrings in GHC). class IsString a fromString :: IsString a => String -> a -- | A Prism stripping a prefix from a list when used as a -- Traversal, or prepending that prefix when run backwards: -- --
--   >>> "preview" ^? prefixed "pre"
--   Just "view"
--   
-- --
--   >>> "review" ^? prefixed "pre"
--   Nothing
--   
-- --
--   >>> prefixed "pre" # "amble"
--   "preamble"
--   
prefixed :: Eq a => [a] -> Prism' [a] [a] -- | A Prism stripping a suffix from a list when used as a -- Traversal, or appending that suffix when run backwards: -- --
--   >>> "review" ^? suffixed "view"
--   Just "re"
--   
-- --
--   >>> "review" ^? suffixed "tire"
--   Nothing
--   
-- --
--   >>> suffixed ".o" # "hello"
--   "hello.o"
--   
suffixed :: Eq a => [a] -> Prism' [a] [a] module List.Builder -- | A difference list is a function that, given a list, returns the -- original contents of the difference list prepended to the given list. -- -- This structure supports O(1) append and snoc operations on -- lists, making it very useful for append-heavy uses (esp. left-nested -- uses of ++), such as logging and pretty printing. -- -- Here is an example using DList as the state type when printing a tree -- with the Writer monad: -- --
--   import Control.Monad.Writer
--   import Data.DList
--   
--   data Tree a = Leaf a | Branch (Tree a) (Tree a)
--   
--   flatten_writer :: Tree x -> DList x
--   flatten_writer = snd . runWriter . flatten
--       where
--         flatten (Leaf x)     = tell (singleton x)
--         flatten (Branch x y) = flatten x >> flatten y
--   
data DList a -- | Convert a list to a dlist fromList :: () => [a] -> DList a -- | Convert a dlist to a list toList :: () => DList a -> [a] -- | Apply a dlist to a list to get the underlying list with an extension -- --
--   apply (fromList xs) ys = xs ++ ys
--   
apply :: () => DList a -> [a] -> [a] -- | Create a dlist containing no elements empty :: () => DList a -- | Create dlist with a single element singleton :: () => a -> DList a -- | O(1). Prepend a single element to a dlist cons :: () => a -> DList a -> DList a infixr 9 `cons` -- | O(1). Append a single element to a dlist snoc :: () => DList a -> a -> DList a infixl 9 `snoc` -- | O(1). Append dlists append :: () => DList a -> DList a -> DList a -- | O(spine). Concatenate dlists concat :: () => [DList a] -> DList a -- | O(n). Create a dlist of the given number of elements replicate :: () => Int -> a -> DList a -- | O(n). List elimination for dlists list :: () => b -> a -> DList a -> b -> DList a -> b -- | O(n). Unfoldr for dlists unfoldr :: () => b -> Maybe (a, b) -> b -> DList a -- | O(n). Foldr over difference lists foldr :: () => a -> b -> b -> b -> DList a -> b -- | O(n). Map over difference lists. map :: () => a -> b -> DList a -> DList b module List.Builder.Partial -- | O(n). Return the head of the dlist head :: () => DList a -> a -- | O(n). Return the tail of the dlist tail :: () => DList a -> DList a module List.Partial -- | List index (subscript) operator, starting from 0. It is an instance of -- the more general genericIndex, which takes an index of any -- integral type. (!!) :: () => [a] -> Int -> a infixl 9 !! -- | Split a list into chunks of a given size. The last chunk may contain -- fewer than n elements. The chunk size must be positive. -- --
--   chunksOf 3 "my test" == ["my ","tes","t"]
--   chunksOf 3 "mytest"  == ["myt","est"]
--   chunksOf 8 ""        == []
--   chunksOf 0 "test"    == undefined
--   
chunksOf :: Partial => Int -> [a] -> [[a]] -- | Extract the first element of a list, which must be non-empty. head :: () => [a] -> a -- | Return all the elements of a list except the last one. The list must -- be non-empty. init :: () => [a] -> [a] -- | Extract the last element of a list, which must be finite and -- non-empty. last :: () => [a] -> a -- | Extract the elements after the head of a list, which must be -- non-empty. tail :: () => [a] -> [a] module List1 -- | Non-empty (and non-strict) list type. data NonEmpty a (:|) :: a -> [a] -> NonEmpty a -- | The break p function is equivalent to span -- (not . p). break :: () => a -> Bool -> NonEmpty a -> ([a], [a]) -- | Synonym for <|. cons :: () => a -> NonEmpty a -> NonEmpty a -- | cycle xs returns the infinite repetition of -- xs: -- --
--   cycle (1 :| [2,3]) = 1 :| [2,3,1,2,3,...]
--   
cycle :: () => NonEmpty a -> NonEmpty a -- | drop n xs drops the first n elements off the -- front of the sequence xs. drop :: () => Int -> NonEmpty a -> [a] -- | dropWhile p xs returns the suffix remaining after -- takeWhile p xs. dropWhile :: () => a -> Bool -> NonEmpty a -> [a] -- | filter p xs removes any elements from xs that -- do not satisfy p. filter :: () => a -> Bool -> NonEmpty a -> [a] -- | group1 operates like group, but uses the knowledge that -- its input is non-empty to produce guaranteed non-empty output. group1 :: Eq a => NonEmpty a -> NonEmpty NonEmpty a -- | groupAllWith1 is to groupWith1 as groupAllWith is -- to groupWith groupAllWith1 :: Ord b => a -> b -> NonEmpty a -> NonEmpty NonEmpty a -- | groupBy1 is to group1 as groupBy is to -- group. groupBy1 :: () => a -> a -> Bool -> NonEmpty a -> NonEmpty NonEmpty a -- | groupWith1 is to group1 as groupWith is to -- group groupWith1 :: Eq b => a -> b -> NonEmpty a -> NonEmpty NonEmpty a -- | Extract the first element of the stream. head :: () => NonEmpty a -> a -- | Extract everything except the last element of the stream. init :: () => NonEmpty a -> [a] -- | 'intersperse x xs' alternates elements of the list with copies of -- x. -- --
--   intersperse 0 (1 :| [2,3]) == 1 :| [0,2,0,3]
--   
intersperse :: () => a -> NonEmpty a -> NonEmpty a -- | The isPrefix function returns True if the first -- argument is a prefix of the second. isPrefixOf :: Eq a => [a] -> NonEmpty a -> Bool -- | iterate f x produces the infinite sequence of repeated -- applications of f to x. -- --
--   iterate f x = x :| [f x, f (f x), ..]
--   
iterate :: () => a -> a -> a -> NonEmpty a -- | Extract the last element of the stream. last :: () => NonEmpty a -> a -- | Map a function over a NonEmpty stream. map :: () => a -> b -> NonEmpty a -> NonEmpty b -- | nonEmpty efficiently turns a normal list into a NonEmpty -- stream, producing Nothing if the input is empty. nonEmpty :: () => [a] -> Maybe NonEmpty a -- | The nub function removes duplicate elements from a list. In -- particular, it keeps only the first occurrence of each element. (The -- name nub means 'essence'.) It is a special case of -- nubBy, which allows the programmer to supply their own -- inequality test. nub :: Eq a => NonEmpty a -> NonEmpty a -- | The nubBy function behaves just like nub, except it uses -- a user-supplied equality predicate instead of the overloaded == -- function. nubBy :: () => a -> a -> Bool -> NonEmpty a -> NonEmpty a -- | The partition function takes a predicate p and a -- stream xs, and returns a pair of lists. The first list -- corresponds to the elements of xs for which p holds; -- the second corresponds to the elements of xs for which -- p does not hold. -- --
--   'partition' p xs = ('filter' p xs, 'filter' (not . p) xs)
--   
partition :: () => a -> Bool -> NonEmpty a -> ([a], [a]) -- | repeat x returns a constant stream, where all elements -- are equal to x. repeat :: () => a -> NonEmpty a -- | reverse a finite NonEmpty stream. reverse :: () => NonEmpty a -> NonEmpty a -- | scanl is similar to foldl, but returns a stream 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 :: Foldable f => b -> a -> b -> b -> f a -> NonEmpty b -- | scanl1 is a variant of scanl that has no starting value -- argument: -- --
--   scanl1 f [x1, x2, ...] == x1 :| [x1 `f` x2, x1 `f` (x2 `f` x3), ...]
--   
scanl1 :: () => a -> a -> a -> NonEmpty a -> NonEmpty a -- | scanr is the right-to-left dual of scanl. Note that -- --
--   head (scanr f z xs) == foldr f z xs.
--   
scanr :: Foldable f => a -> b -> b -> b -> f a -> NonEmpty b -- | scanr1 is a variant of scanr that has no starting value -- argument. scanr1 :: () => a -> a -> a -> NonEmpty a -> NonEmpty a -- | Sort a stream. sort :: Ord a => NonEmpty a -> NonEmpty a -- | sortBy for NonEmpty, behaves the same as sortBy sortBy :: () => a -> a -> Ordering -> NonEmpty a -> NonEmpty a -- | sortWith for NonEmpty, behaves the same as: -- --
--   sortBy . comparing
--   
sortWith :: Ord o => a -> o -> NonEmpty a -> NonEmpty a -- | span p xs returns the longest prefix of xs -- that satisfies p, together with the remainder of the stream. -- --
--   'span' p xs == ('takeWhile' p xs, 'dropWhile' p xs)
--   xs == ys ++ zs where (ys, zs) = 'span' p xs
--   
span :: () => a -> Bool -> NonEmpty a -> ([a], [a]) -- | splitAt n xs returns a pair consisting of the prefix -- of xs of length n and the remaining stream -- immediately following this prefix. -- --
--   'splitAt' n xs == ('take' n xs, 'drop' n xs)
--   xs == ys ++ zs where (ys, zs) = 'splitAt' n xs
--   
splitAt :: () => Int -> NonEmpty a -> ([a], [a]) -- | Extract the possibly-empty tail of the stream. tail :: () => NonEmpty a -> [a] -- | take n xs returns the first n elements of -- xs. take :: () => Int -> NonEmpty a -> [a] -- | takeWhile p xs returns the longest prefix of the -- stream xs for which the predicate p holds. takeWhile :: () => a -> Bool -> NonEmpty a -> [a] -- | transpose for NonEmpty, behaves the same as -- transpose The rows/columns need not be the same length, in -- which case > transpose . transpose /= id transpose :: () => NonEmpty NonEmpty a -> NonEmpty NonEmpty a -- | uncons produces the first element of the stream, and a stream -- of the remaining elements, if any. uncons :: () => NonEmpty a -> (a, Maybe NonEmpty a) -- | The unfoldr function is analogous to Data.List's -- unfoldr operation. unfoldr :: () => a -> (b, Maybe a) -> a -> NonEmpty b -- | Compute n-ary logic exclusive OR operation on NonEmpty list. xor :: NonEmpty Bool -> Bool -- | The zip function takes two streams and returns a stream of -- corresponding pairs. zip :: () => NonEmpty a -> NonEmpty b -> NonEmpty (a, b) -- | The zipWith function generalizes zip. Rather than -- tupling the elements, the elements are combined using the function -- passed as the first argument. zipWith :: () => a -> b -> c -> NonEmpty a -> NonEmpty b -> NonEmpty c module List1.Partial -- | xs !! n returns the element of the stream xs at -- index n. Note that the head of the stream has index 0. -- -- Beware: a negative or out-of-bounds index will cause an error. (!!) :: () => NonEmpty a -> Int -> a infixl 9 !! -- | Converts a normal list to a NonEmpty stream. -- -- Raises an error if given an empty list. fromList :: () => [a] -> NonEmpty a module ListT -- | This is like a list except that you can interleave effects between -- each list element. For example: -- --
--   stdin :: ListT IO String
--   stdin = ListT (do
--       eof <- System.IO.isEOF
--       if eof
--           then return Nil
--           else do
--               line <- getLine
--               return (Cons line stdin) )
--   
-- -- The mnemonic is "List Transformer" because this type takes a base -- Monad, 'm', and returns a new transformed Monad -- that adds support for list comprehensions newtype ListT (m :: * -> *) a ListT :: m Step m a -> ListT a [next] :: ListT a -> m Step m a -- | Use this to drain a ListT, running it to completion and -- discarding all values. For example: -- --
--   stdout :: ListT IO String -> IO ()
--   stdout l = runListT (do
--       str <- l
--       liftIO (putStrLn str) )
--   
-- -- The most common specialized type for runListT will be: -- --
--   runListT :: ListT IO a -> IO ()
--   
runListT :: Monad m => ListT m a -> m () -- | Use this to fold a ListT into a single value. This is designed -- to be used with the foldl library: -- --
--   import Control.Foldl (purely)
--   import List.Transformer (fold)
--   
--   purely fold :: Monad m => Fold a b -> ListT m a -> m b
--   
-- -- ... but you can also use the fold function directly: -- --
--   fold (+) 0 id :: Num a => ListT m a -> m a
--   
fold :: Monad m => x -> a -> x -> x -> x -> b -> ListT m a -> m b -- | Use this to fold a ListT into a single value. This is designed -- to be used with the foldl library: -- --
--   import Control.Foldl (impurely)
--   import List.Transformer (fold)
--   
--   impurely fold :: Monad m => FoldM m a b -> ListT m a -> m b
--   
-- -- ... but you can also use the foldM function directly. foldM :: Monad m => x -> a -> m x -> m x -> x -> m b -> ListT m a -> m b -- | Convert any collection that implements Foldable to another -- collection that implements Alternative -- -- For this library, the most common specialized type for select -- will be: -- --
--   select :: [a] -> ListT IO a
--   
select :: (Foldable f, Alternative m) => f a -> m a -- | take n xs takes n elements from the head of -- xs. -- --
--   >>> let list xs = do x <- select xs; liftIO (print (show x)); return x
--   
--   >>> let sum = fold (+) 0 id
--   
--   >>> sum (take 2 (list [5,4,3,2,1]))
--   "5"
--   "4"
--   9
--   
take :: Monad m => Int -> ListT m a -> ListT m a -- | drop n xs drops n elements from the head of -- xs, but still runs their effects. -- --
--   >>> let list xs = do x <- select xs; liftIO (print (show x)); return x
--   
--   >>> let sum = fold (+) 0 id
--   
--   >>> sum (drop 2 (list [5,4,3,2,1]))
--   "5"
--   "4"
--   "3"
--   "2"
--   "1"
--   6
--   
drop :: Monad m => Int -> ListT m a -> ListT m a -- | takeWhile pred xs takes elements from xs until the -- predicate pred fails -- --
--   >>> let list xs = do x <- select xs; liftIO (print (show x)); return x
--   
--   >>> let sum = fold (+) 0 id
--   
--   >>> sum (takeWhile even (list [2,4,5,7,8]))
--   "2"
--   "4"
--   "5"
--   6
--   
takeWhile :: Monad m => a -> Bool -> ListT m a -> ListT m a -- | unfold step seed generates a ListT from a -- step function and an initial seed. unfold :: Monad m => b -> m Maybe (a, b) -> b -> ListT m a -- | zip xs ys zips two ListT together, running the effects -- of each before possibly recursing. Notice in the example below, -- 4 is output even though it has no corresponding element in -- the second list. -- --
--   >>> let list xs = do x <- select xs; liftIO (print (show x)); return x
--   
--   >>> runListT (zip (list [1,2,3,4,5]) (list [6,7,8]))
--   "1"
--   "6"
--   "2"
--   "7"
--   "3"
--   "8"
--   "4"
--   
zip :: Monad m => ListT m a -> ListT m b -> ListT m (a, b) module Logic -- | The basic Logic monad, for performing backtracking computations -- returning values of type a type Logic = LogicT Identity -- | A smart constructor for Logic computations. logic :: () => forall r. () => a -> r -> r -> r -> r -> Logic a -- | Runs a Logic computation with the specified initial success and -- failure continuations. runLogic :: () => Logic a -> a -> r -> r -> r -> r -- | Extracts all results from a Logic computation. observeAll :: () => Logic a -> [a] -- | A monad transformer for performing backtracking computations layered -- over another monad m newtype LogicT (m :: * -> *) a LogicT :: forall r. () => a -> m r -> m r -> m r -> m r -> LogicT a [unLogicT] :: LogicT a -> forall r. () => a -> m r -> m r -> m r -> m r -- | Runs a LogicT computation with the specified initial success and -- failure continuations. runLogicT :: () => LogicT m a -> a -> m r -> m r -> m r -> m r -- | Extracts the first result from a LogicT computation, failing -- otherwise. observeT :: Monad m => LogicT m a -> m a -- | Extracts up to a given number of results from a LogicT computation. observeManyT :: Monad m => Int -> LogicT m a -> m [a] -- | Extracts all results from a LogicT computation. observeAllT :: Monad m => LogicT m a -> m [a] -- | Minimal implementation: msplit class MonadPlus m => MonadLogic (m :: * -> *) -- | Attempts to split the computation, giving access to the first result. -- Satisfies the following laws: -- --
--   msplit mzero                == return Nothing
--   msplit (return a `mplus` m) == return (Just (a, m))
--   
msplit :: MonadLogic m => m a -> m Maybe (a, m a) -- | Fair disjunction. It is possible for a logical computation to have an -- infinite number of potential results, for instance: -- --
--   odds = return 1 `mplus` liftM (2+) odds
--   
-- -- Such computations can cause problems in some circumstances. Consider: -- --
--   do x <- odds `mplus` return 2
--      if even x then return x else mzero
--   
-- -- Such a computation may never consider the 'return 2', and will -- therefore never terminate. By contrast, interleave ensures fair -- consideration of both branches of a disjunction interleave :: MonadLogic m => m a -> m a -> m a -- | Fair conjunction. Similarly to the previous function, consider the -- distributivity law for MonadPlus: -- --
--   (mplus a b) >>= k = (a >>= k) `mplus` (b >>= k)
--   
-- -- If 'a >>= k' can backtrack arbitrarily many tmes, (b >>= -- k) may never be considered. (>>-) takes similar care to consider -- both branches of a disjunctive computation. (>>-) :: MonadLogic m => m a -> a -> m b -> m b infixl 1 >>- -- | Logical conditional. The equivalent of Prolog's soft-cut. If its first -- argument succeeds at all, then the results will be fed into the -- success branch. Otherwise, the failure branch is taken. satisfies the -- following laws: -- --
--   ifte (return a) th el           == th a
--   ifte mzero th el                == el
--   ifte (return a `mplus` m) th el == th a `mplus` (m >>= th)
--   
ifte :: MonadLogic m => m a -> a -> m b -> m b -> m b -- | Pruning. Selects one result out of many. Useful for when multiple -- results of a computation will be equivalent, or should be treated as -- such. once :: MonadLogic m => m a -> m a -- | The inverse of msplit. Satisfies the following law: -- --
--   msplit m >>= reflect == m
--   
reflect :: MonadLogic m => Maybe (a, m a) -> m a -- | Inverts a logic computation. If m succeeds with at least one -- value, lnot m fails. If m fails, then lnot -- m succeeds the value (). lnot :: MonadLogic m => m a -> m () module Managed -- | A managed resource that you acquire using with data Managed a -- | Build a Managed value managed :: () => forall r. () => a -> IO r -> IO r -> Managed a -- | Like managed but for resource-less operations. managed_ :: forall r. () => IO r -> IO r -> Managed () -- | Acquire a Managed value -- -- This is a potentially unsafe function since it allows a resource to -- escape its scope. For example, you might use Managed to safely -- acquire a file handle, like this: -- --
--   import qualified System.IO as IO
--   
--   example :: Managed Handle
--   example = managed (IO.withFile "foo.txt" IO.ReadMode)
--   
-- -- ... and if you never used the with function then you would -- never run the risk of accessing the Handle after the file was -- closed. However, if you use with then you can incorrectly -- access the handle after the handle is closed, like this: -- --
--   bad :: IO ()
--   bad = do
--       handle <- with example return
--       IO.hPutStrLn handle "bar"  -- This will fail because the handle is closed
--   
-- -- ... so only use with if you know what you are doing and you're -- returning a value that is not a resource being managed. with :: () => Managed a -> a -> IO r -> IO r -- | Run a Managed computation, enforcing that no acquired resources -- leak runManaged :: Managed () -> IO () -- | You can embed a Managed action within any Monad that -- implements MonadManaged by using the using function -- -- All instances must obey the following two laws: -- --
--   using (return x) = return x
--   
--   using (m >>= f) = using m >>= \x -> using (f x)
--   
class MonadIO m => MonadManaged (m :: * -> *) using :: MonadManaged m => Managed a -> m a module Map module Map.Hash module Map.Int module Map.Int.Lazy module Map.Lazy module Maybe -- | 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 -- | 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 -- | Monadic generalisation of maybe. maybeM :: Monad m => m b -> a -> m b -> m Maybe a -> m b -- | 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 fromMaybe function takes a default value and and -- Maybe value. If the Maybe is Nothing, it returns -- the default values; otherwise, it returns the value contained in the -- Maybe. -- --

Examples

-- -- Basic usage: -- --
--   >>> fromMaybe "" (Just "Hello, World!")
--   "Hello, World!"
--   
-- --
--   >>> fromMaybe "" Nothing
--   ""
--   
-- -- Read an integer from a string using readMaybe. If we fail to -- parse an integer, we want to return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> fromMaybe 0 (readMaybe "5")
--   5
--   
--   >>> fromMaybe 0 (readMaybe "")
--   0
--   
fromMaybe :: () => a -> Maybe a -> a -- | The listToMaybe function returns Nothing on an empty -- list or Just a where a is the first element -- of the list. -- --

Examples

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

Examples

-- -- Basic usage: -- --
--   >>> maybeToList (Just 7)
--   [7]
--   
-- --
--   >>> maybeToList Nothing
--   []
--   
-- -- One can use maybeToList to avoid pattern matching when combined -- with a function that (safely) works on lists: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> sum $ maybeToList (readMaybe "3")
--   3
--   
--   >>> sum $ maybeToList (readMaybe "")
--   0
--   
maybeToList :: () => Maybe a -> [a] -- | The 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 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] -- | This Prism provides a Traversal for tweaking the target -- of the value of Just in a Maybe. -- --
--   >>> over _Just (+1) (Just 2)
--   Just 3
--   
-- -- Unlike traverse this is a Prism, and so you can use it -- to inject as well: -- --
--   >>> _Just # 5
--   Just 5
--   
-- --
--   >>> 5^.re _Just
--   Just 5
--   
-- -- Interestingly, -- --
--   m ^? _Just ≡ m
--   
-- --
--   >>> Just x ^? _Just
--   Just x
--   
-- --
--   >>> Nothing ^? _Just
--   Nothing
--   
_Just :: (Choice p, Applicative f) => p a f b -> p Maybe a f Maybe b -- | This Prism provides the Traversal of a Nothing in -- a Maybe. -- --
--   >>> Nothing ^? _Nothing
--   Just ()
--   
-- --
--   >>> Just () ^? _Nothing
--   Nothing
--   
-- -- But you can turn it around and use it to construct Nothing as -- well: -- --
--   >>> _Nothing # ()
--   Nothing
--   
_Nothing :: (Choice p, Applicative f) => p () f () -> p Maybe a f Maybe a -- | 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 newtype Option a Option :: Maybe a -> Option a [getOption] :: Option a -> Maybe a -- | Fold an Option case-wise, just like maybe. option :: () => b -> a -> b -> Option a -> b -- | Maybe monoid returning the leftmost non-Nothing value. -- -- First a is isomorphic to Alt Maybe -- a, but precedes it historically. -- --
--   >>> getFirst (First (Just "hello") <> First Nothing <> First (Just "world"))
--   Just "hello"
--   
newtype First a First :: Maybe a -> First a [getFirst] :: First a -> Maybe a -- | Maybe monoid returning the rightmost non-Nothing value. -- -- Last a is isomorphic to Dual (First -- a), and thus to Dual (Alt Maybe a) -- --
--   >>> getLast (Last (Just "hello") <> Last Nothing <> Last (Just "world"))
--   Just "world"
--   
newtype Last a Last :: Maybe a -> Last a [getLast] :: Last a -> Maybe a module Maybe.Partial -- | The fromJust function extracts the element out of a Just -- and throws an error if its argument is Nothing. -- --

Examples

-- -- Basic usage: -- --
--   >>> fromJust (Just 1)
--   1
--   
-- --
--   >>> 2 * (fromJust (Just 10))
--   20
--   
-- --
--   >>> 2 * (fromJust Nothing)
--   *** Exception: Maybe.fromJust: Nothing
--   
fromJust :: () => Maybe a -> a module MaybeT -- | 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 :: * -> *) a MaybeT :: m Maybe a -> MaybeT a [runMaybeT] :: MaybeT a -> m Maybe a -- | Transform the computation inside a MaybeT. -- -- mapMaybeT :: () => m Maybe a -> n Maybe b -> MaybeT m a -> MaybeT n b module Monad -- | The Monad class defines the basic operations over a -- monad, a concept from a branch of mathematics known as -- category theory. From the perspective of a Haskell programmer, -- however, it is best to think of a monad as an abstract datatype -- of actions. Haskell's do expressions provide a convenient -- syntax for writing monadic expressions. -- -- Instances of Monad should satisfy the following laws: -- -- -- -- Furthermore, the Monad and Applicative operations should -- relate as follows: -- -- -- -- The above laws imply: -- -- -- -- and that pure and (<*>) satisfy the applicative -- functor laws. -- -- The instances of Monad for lists, Maybe and IO -- defined in the Prelude satisfy these laws. class Applicative m => Monad (m :: * -> *) -- | Sequentially compose two actions, passing any value produced by the -- first as an argument to the second. (>>=) :: Monad m => m a -> a -> m b -> m b -- | Inject a value into the monadic type. return :: Monad m => a -> m a -- | Same as >>=, but with the arguments interchanged. (=<<) :: Monad m => a -> m b -> m a -> m b infixr 1 =<< -- | Left-to-right Kleisli composition of monads. (>=>) :: Monad m => a -> m b -> b -> m c -> a -> m c infixr 1 >=> -- | Right-to-left Kleisli composition of monads. -- (>=>), with the arguments flipped. -- -- Note how this operator resembles function composition -- (.): -- --
--   (.)   ::            (b ->   c) -> (a ->   b) -> a ->   c
--   (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
--   
(<=<) :: Monad m => b -> m c -> a -> m b -> a -> m c infixr 1 <=< -- | Strict version of <$>. (<$!>) :: Monad m => a -> b -> m a -> m b infixl 4 <$!> -- | 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 :: Monad m => m m a -> m a -- | A monadic version of loop, where the predicate returns -- Left as a seed for the next loop or Right to abort the -- loop. loopM :: Monad m => a -> m Either a b -> a -> m b -- | Like unless, but where the test can be monadic. unlessM :: Monad m => m Bool -> m () -> m () -- | Like whenJust, but where the test can be monadic. whenJustM :: Monad m => m Maybe a -> a -> m () -> m () -- | Like when, but where the test can be monadic. whenM :: Monad m => m Bool -> m () -> m () -- | Keep running an operation until it becomes False. As an -- example: -- --
--   whileM $ do sleep 0.1; notM $ doesFileExist "foo.txt"
--   readFile "foo.txt"
--   
-- -- If you need some state persisted between each test, use loopM. whileM :: Monad m => m Bool -> m () -- | Kleisli arrows of a monad. newtype Kleisli (m :: * -> *) a b Kleisli :: a -> m b -> Kleisli a b [runKleisli] :: Kleisli a b -> a -> m b -- | A monad in the category of monads, using lift from -- MonadTrans as the analog of return and embed as -- the analog of (=<<): -- --
--   embed lift = id
--   
--   embed f (lift m) = f m
--   
--   embed g (embed f t) = embed (\m -> embed g (f m)) t
--   
class (MFunctor t, MonadTrans t) => MMonad (t :: * -> * -> * -> *) -- | Embed a newly created MMonad layer within an existing layer -- -- embed is analogous to (=<<) embed :: (MMonad t, Monad n) => forall a. () => m a -> t n a -> t m b -> t n b -- | Squash two MMonad layers into a single layer -- -- squash is analogous to join squash :: (Monad m, MMonad t) => t t m a -> t m a -- | Compose two MMonad layer-building functions -- -- (>|>) is analogous to (>=>) (>|>) :: (Monad m3, MMonad t) => forall a. () => m1 a -> t m2 a -> forall b. () => m2 b -> t m3 b -> m1 c -> t m3 c infixr 2 >|> -- | Equivalent to (>|>) with the arguments flipped -- -- (<|<) is analogous to (<=<) (<|<) :: (Monad m3, MMonad t) => forall b. () => m2 b -> t m3 b -> forall a. () => m1 a -> t m2 a -> m1 c -> t m3 c infixl 2 <|< -- | An infix operator equivalent to embed -- -- (=<|) is analogous to (=<<) (=<|) :: (Monad n, MMonad t) => forall a. () => m a -> t n a -> t m b -> t n b infixr 2 =<| -- | Equivalent to (=<|) with the arguments flipped -- -- (|>=) is analogous to (>>=) (|>=) :: (Monad n, MMonad t) => t m b -> forall a. () => m a -> t n a -> t n b infixl 2 |>= module Monad.Base class (Applicative b, Applicative m, Monad b, Monad m) => MonadBase (b :: * -> *) (m :: * -> *) | m -> b -- | Lift a computation from the base monad liftBase :: MonadBase b m => b α -> m α module Monad.Fail -- | 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 :: * -> *) fail :: MonadFail m => String -> m a module Monad.Fix -- | Monads having fixed points with a 'knot-tying' semantics. Instances of -- MonadFix should satisfy the following laws: -- -- -- -- This class is used in the translation of the recursive do -- notation supported by GHC and Hugs. class Monad m => MonadFix (m :: * -> *) -- | The fixed point of a monadic computation. mfix f -- executes the action f only once, with the eventual output fed -- back as the input. Hence f should not be strict, for then -- mfix f would diverge. mfix :: MonadFix m => a -> m a -> m a module Monad.Plus -- | Monads that also support choice and failure. class (Alternative m, Monad m) => MonadPlus (m :: * -> *) -- | 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 -- | endBy p sep parses zero or more occurrences of -- p, separated and ended by sep. Returns a list of -- values returned by p. -- --
--   cStatements = cStatement `endBy` semicolon
--   
endBy :: MonadPlus m => m a -> m sep -> m [a] -- | endBy1 p sep parses one or more occurrences of -- p, separated and ended by sep. Returns a non-empty -- list of values returned by p. endBy1 :: MonadPlus m => m a -> m sep -> m NonEmpty a -- | many p applies the parser p zero or -- more times and returns a list of the values returned by p. -- --
--   identifier = (:) <$> letter <*> many (alphaNumChar <|> char '_')
--   
many :: MonadPlus m => m a -> m [a] -- | Direct MonadPlus equivalent of filter -- filter = (mfilter:: (a -> Bool) -> [a] -- -> [a] applicable to any MonadPlus, for example -- mfilter odd (Just 1) == Just 1 mfilter odd (Just 2) == -- Nothing mfilter :: MonadPlus m => a -> Bool -> m a -> m a -- | sepBy1 p sep parses one or more occurrences of -- p, separated by sep. Returns a non-empty list of -- values returned by p. sepBy1 :: MonadPlus m => m a -> m sep -> m NonEmpty a -- | sepEndBy1 p sep parses one or more occurrences -- of p, separated and optionally ended by sep. Returns -- a non-empty list of values returned by p. sepEndBy1 :: MonadPlus m => m a -> m sep -> m NonEmpty a -- | someTill p end works similarly to manyTill -- p end, but p should succeed at least once. -- -- See also: skipSome, skipSomeTill. someTill :: MonadPlus m => m a -> m end -> m NonEmpty a -- | manyTill p end applies parser p zero -- or more times until parser end succeeds. Returns the list of -- values returned by p. -- -- See also: skipMany, skipManyTill. manyTill :: MonadPlus m => m a -> m end -> m [a] -- | sepBy p sep parses zero or more occurrences of -- p, separated by sep. Returns a list of values -- returned by p. -- --
--   commaSep p = p `sepBy` comma
--   
sepBy :: MonadPlus m => m a -> m sep -> m [a] -- | sepEndBy p sep parses zero or more occurrences -- of p, separated and optionally ended by sep. Returns -- a list of values returned by p. sepEndBy :: MonadPlus m => m a -> m sep -> m [a] -- | skipMany p applies the parser p zero -- or more times, skipping its result. -- -- See also: manyTill, skipManyTill. skipMany :: MonadPlus m => m a -> m () -- | skipManyTill p end applies the parser p -- zero or more times skipping results until parser end -- succeeds. Result parsed by end is then returned. -- -- See also: manyTill, skipMany. skipManyTill :: MonadPlus m => m a -> m end -> m end -- | skipSome p applies the parser p one or -- more times, skipping its result. -- -- See also: someTill, skipSomeTill. skipSome :: MonadPlus m => m a -> m () -- | skipSomeTill p end applies the parser p -- one or more times skipping results until parser end -- succeeds. Result parsed by end is then returned. -- -- See also: someTill, skipSome. skipSomeTill :: MonadPlus m => m a -> m end -> m end module Monad.Trans -- | The class of monad transformers. Instances should satisfy the -- following laws, which state that lift is a monad -- transformation: -- -- class MonadTrans (t :: * -> * -> * -> *) -- | Lift a computation from the argument monad to the constructed monad. lift :: (MonadTrans t, Monad m) => m a -> t m a -- | The base functor for a free monad. data FreeF (f :: * -> *) a b Pure :: a -> FreeF a b Free :: f b -> FreeF a b -- | A version of lift that can be used with just a Functor for f. liftF :: (Functor f, MonadFree f m) => f a -> m a -- | The "free monad" for a functor f. type Free (f :: * -> *) = FreeT f Identity -- | Pushes a layer into a free monad value. free :: () => FreeF f a Free f a -> Free f a -- | Evaluates the first layer out of a free monad value. runFree :: () => Free f a -> FreeF f a Free f a -- | retract is the left inverse of liftF -- --
--   retract . liftF = id
--   
retract :: Monad f => Free f a -> f a -- | Tear down a Free Monad using iteration. iter :: Functor f => f a -> a -> Free f a -> a -- | Like iter for monadic values. iterM :: (Functor f, Monad m) => f m a -> m a -> Free f a -> m a -- | The "free monad transformer" for a functor f newtype FreeT (f :: * -> *) (m :: * -> *) a FreeT :: m FreeF f a FreeT f m a -> FreeT a [runFreeT] :: FreeT a -> m FreeF f a FreeT f m a -- | Tear down a free monad transformer using iteration. iterT :: (Functor f, Monad m) => f m a -> m a -> FreeT f m a -> m a -- | Tear down a free monad transformer using iteration over a transformer. iterTM :: (Functor f, Monad m, MonadTrans t, Monad t m) => f t m a -> t m a -> FreeT f m a -> t m a -- | Lift a monad homomorphism from m to n into a monad -- homomorphism from FreeT f m to FreeT f -- n -- --
--   hoistFreeT :: (Monad m, Functor f) => (m ~> n) -> FreeT f m ~> FreeT f n
--   
hoistFreeT :: (Monad m, Functor f) => forall a. () => m a -> n a -> FreeT f m b -> FreeT f n b -- | The very definition of a free monad transformer is that given a -- natural transformation you get a monad transformer homomorphism. foldFreeT :: (MonadTrans t, Monad t m, Monad m) => forall (n :: * -> *) x. Monad n => f x -> t n x -> FreeT f m a -> t m a -- | Lift a natural transformation from f to g into a -- monad homomorphism from FreeT f m to FreeT -- g m transFreeT :: (Monad m, Functor g) => forall a. () => f a -> g a -> FreeT f m b -> FreeT g m b -- | Pull out and join m layers of FreeT f m a. joinFreeT :: (Monad m, Traversable f) => FreeT f m a -> m Free f a -- | Tear down a free monad transformer using Monad instance for t -- m. retractT :: (MonadTrans t, Monad t m, Monad m) => FreeT t m m a -> t m a -- | Monads provide substitution (fmap) and renormalization -- (join): -- --
--   m >>= f = join (fmap f m)
--   
-- -- A free Monad is one that does no work during the normalization -- step beyond simply grafting the two monadic values together. -- -- [] is not a free Monad (in this sense) because -- join [[a]] smashes the lists flat. -- -- On the other hand, consider: -- --
--   data Tree a = Bin (Tree a) (Tree a) | Tip a
--   
-- --
--   instance Monad Tree where
--     return = Tip
--     Tip a >>= f = f a
--     Bin l r >>= f = Bin (l >>= f) (r >>= f)
--   
-- -- This Monad is the free Monad of Pair: -- --
--   data Pair a = Pair a a
--   
-- -- And we could make an instance of MonadFree for it directly: -- --
--   instance MonadFree Pair Tree where
--      wrap (Pair l r) = Bin l r
--   
-- -- Or we could choose to program with Free Pair instead -- of Tree and thereby avoid having to define our own -- Monad instance. -- -- Moreover, Control.Monad.Free.Church provides a MonadFree -- instance that can improve the asymptotic complexity of code -- that constructs free monads by effectively reassociating the use of -- (>>=). You may also want to take a look at the -- kan-extensions package -- (http://hackage.haskell.org/package/kan-extensions). -- -- See Free for a more formal definition of the free Monad -- for a Functor. class Monad m => MonadFree (f :: * -> *) (m :: * -> *) | m -> f -- | Add a layer. -- --
--   wrap (fmap f x) ≡ wrap (fmap return x) >>= f
--   
wrap :: MonadFree f m => f m a -> m a module Monad.Zip -- | MonadZip type class. Minimal definition: mzip or -- mzipWith -- -- Instances should satisfy the laws: -- -- -- --
--   liftM (f *** g) (mzip ma mb) = mzip (liftM f ma) (liftM g mb)
--   
-- -- -- --
--   liftM (const ()) ma = liftM (const ()) mb
--   ==>
--   munzip (mzip ma mb) = (ma, mb)
--   
class Monad m => MonadZip (m :: * -> *) mzip :: MonadZip m => m a -> m b -> m (a, b) mzipWith :: MonadZip m => a -> b -> c -> m a -> m b -> m c munzip :: MonadZip m => m (a, b) -> (m a, m b) module Monoid -- | The class of monoids (types with an associative binary operation that -- has an identity). Instances should satisfy the following laws: -- -- -- -- The method names refer to the monoid of lists under concatenation, but -- there are many other instances. -- -- Some types can be viewed as a monoid in more than one way, e.g. both -- addition and multiplication on numbers. In such cases we often define -- newtypes and make those instances of Monoid, e.g. -- Sum and Product. -- -- NOTE: Semigroup is a superclass of Monoid since -- base-4.11.0.0. class Semigroup a => Monoid a -- | Identity of mappend mempty :: Monoid a => a -- | Fold a list using the monoid. -- -- For most types, the default definition for mconcat will be -- used, but the function is included in the class definition so that an -- optimized version can be provided for specific types. mconcat :: Monoid a => [a] -> a -- | Generically generate a Monoid mempty for any -- product-like type implementing Generic. -- -- It is only defined for product types. -- --
--   gmappend gmempty a = a = gmappend a gmempty
--   
gmempty :: (Generic a, GMonoid Rep a) => a module MultiSet -- | A multiset of values a. The same value can occur multiple -- times. data MultiSet a -- | The number of occurrences of an element type Occur = Int -- | O(1). Is this the empty multiset? null :: () => MultiSet a -> Bool -- | O(n). The number of elements in the multiset. size :: () => MultiSet a -> Occur -- | O(1). The number of distinct elements in the multiset. distinctSize :: () => MultiSet a -> Occur -- | O(log n). Is the element in the multiset? member :: Ord a => a -> MultiSet a -> Bool -- | O(log n). Is the element not in the multiset? notMember :: Ord a => a -> MultiSet a -> Bool -- | O(log n). The number of occurrences of an element in a -- multiset. occur :: Ord a => a -> MultiSet a -> Occur -- | O(n+m). Is this a subset? (s1 `isSubsetOf` s2) tells -- whether s1 is a subset of s2. isSubsetOf :: Ord a => MultiSet a -> MultiSet a -> Bool -- | O(n+m). Is this a proper subset? (ie. a subset but not equal). isProperSubsetOf :: Ord a => MultiSet a -> MultiSet a -> Bool -- | O(1). The empty mutli set. empty :: () => MultiSet a -- | O(1). Create a singleton mutli set. singleton :: () => a -> MultiSet a -- | O(log n). Insert an element in a multiset. insert :: Ord a => a -> MultiSet a -> MultiSet a -- | O(log n). Insert an element in a multiset a given number of -- times. -- -- Negative numbers remove occurrences of the given element. insertMany :: Ord a => a -> Occur -> MultiSet a -> MultiSet a -- | O(log n). Delete a single element from a multiset. delete :: Ord a => a -> MultiSet a -> MultiSet a -- | O(log n). Delete an element from a multiset a given number of -- times. -- -- Negative numbers add occurrences of the given element. deleteMany :: Ord a => a -> Occur -> MultiSet a -> MultiSet a -- | O(log n). Delete all occurrences of an element from a multiset. deleteAll :: Ord a => a -> MultiSet a -> MultiSet a -- | O(n+m). The union of two multisets. The union adds the -- occurrences together. -- -- The implementation uses the efficient hedge-union algorithm. -- Hedge-union is more efficient on (bigset union smallset). union :: Ord a => MultiSet a -> MultiSet a -> MultiSet a -- | The union of a list of multisets: (unions == foldl -- union empty). unions :: Ord a => [MultiSet a] -> MultiSet a -- | O(n+m). The union of two multisets. The number of occurrences -- of each element in the union is the maximum of the number of -- occurrences in the arguments (instead of the sum). -- -- The implementation uses the efficient hedge-union algorithm. -- Hedge-union is more efficient on (bigset union smallset). maxUnion :: Ord a => MultiSet a -> MultiSet a -> MultiSet a -- | O(n+m). Difference of two multisets. The implementation uses an -- efficient hedge algorithm comparable with hedge-union. difference :: Ord a => MultiSet a -> MultiSet a -> MultiSet a -- | O(n+m). The intersection of two multisets. Elements of the -- result come from the first multiset, so for example -- --
--   import qualified Data.MultiSet as MS
--   data AB = A | B deriving Show
--   instance Ord AB where compare _ _ = EQ
--   instance Eq AB where _ == _ = True
--   main = print (MS.singleton A `MS.intersection` MS.singleton B,
--                 MS.singleton B `MS.intersection` MS.singleton A)
--   
-- -- prints (fromList [A],fromList [B]). intersection :: Ord a => MultiSet a -> MultiSet a -> MultiSet a -- | O(n). Filter all elements that satisfy the predicate. filter :: () => a -> Bool -> MultiSet a -> MultiSet a -- | O(n). Partition the multiset into two multisets, one with all -- elements that satisfy the predicate and one with all elements that -- don't satisfy the predicate. See also split. partition :: () => a -> Bool -> MultiSet a -> (MultiSet a, MultiSet a) -- | O(log n). The expression (split x set) is a -- pair (set1,set2) where all elements in set1 are -- lower than x and all elements in set2 larger than -- x. x is not found in neither set1 nor -- set2. split :: Ord a => a -> MultiSet a -> (MultiSet a, MultiSet a) -- | O(log n). Performs a split but also returns the number -- of occurrences of the pivot element in the original set. splitOccur :: Ord a => a -> MultiSet a -> (MultiSet a, Occur, MultiSet a) -- | O(n*log n). map f s is the multiset obtained by -- applying f to each element of s. map :: Ord b => a -> b -> MultiSet a -> MultiSet b -- | O(n). The -- -- mapMonotonic f s == map f s, but works only -- when f is strictly monotonic. The precondition is not -- checked. Semi-formally, we have: -- --
--   and [x < y ==> f x < f y | x <- ls, y <- ls]
--                       ==> mapMonotonic f s == map f s
--       where ls = toList s
--   
mapMonotonic :: () => a -> b -> MultiSet a -> MultiSet b -- | O(n). Map and collect the Just results. mapMaybe :: Ord b => a -> Maybe b -> MultiSet a -> MultiSet b -- | O(n). Map and separate the Left and Right -- results. mapEither :: (Ord b, Ord c) => a -> Either b c -> MultiSet a -> (MultiSet b, MultiSet c) -- | O(n). Apply a function to each element, and take the union of -- the results concatMap :: Ord b => a -> [b] -> MultiSet a -> MultiSet b -- | O(n). Apply a function to each element, and take the union of -- the results unionsMap :: Ord b => a -> MultiSet b -> MultiSet a -> MultiSet b -- | O(n). The monad bind operation, (>>=), for multisets. bind :: Ord b => MultiSet a -> a -> MultiSet b -> MultiSet b -- | O(n). The monad join operation for multisets. join :: Ord a => MultiSet MultiSet a -> MultiSet a -- | O(t). Fold over the elements of a multiset in an unspecified -- order. fold :: () => a -> b -> b -> b -> MultiSet a -> b -- | O(n). Fold over the elements of a multiset with their -- occurrences. foldOccur :: () => a -> Occur -> b -> b -> b -> MultiSet a -> b -- | O(log n). The minimal element of a multiset. findMin :: () => MultiSet a -> a -- | O(log n). The maximal element of a multiset. findMax :: () => MultiSet a -> a -- | O(log n). Delete the minimal element. deleteMin :: () => MultiSet a -> MultiSet a -- | O(log n). Delete the maximal element. deleteMax :: () => MultiSet a -> MultiSet a -- | O(log n). Delete all occurrences of the minimal element. deleteMinAll :: () => MultiSet a -> MultiSet a -- | O(log n). Delete all occurrences of the maximal element. deleteMaxAll :: () => MultiSet a -> MultiSet a -- | O(log n). Delete and find the minimal element. -- --
--   deleteFindMin set = (findMin set, deleteMin set)
--   
deleteFindMin :: () => MultiSet a -> (a, MultiSet a) -- | O(log n). Delete and find the maximal element. -- --
--   deleteFindMax set = (findMax set, deleteMax set)
--   
deleteFindMax :: () => MultiSet a -> (a, MultiSet a) -- | O(log n). Retrieves the maximal element of the multiset, and -- the set with that element removed. Returns Nothing when -- passed an empty multiset. -- -- Examples: -- --
--   >>> maxView $ fromList ['a', 'a', 'b', 'c']
--   Just ('c',fromOccurList [('a',2),('b',1)])
--   
maxView :: () => MultiSet a -> Maybe (a, MultiSet a) -- | O(log n). Retrieves the minimal element of the multiset, and -- the set with that element removed. Returns Nothing when -- passed an empty multiset. -- -- Examples: -- --
--   >>> minView $ fromList ['a', 'a', 'b', 'c']
--   Just ('a',fromOccurList [('a',1),('b',1),('c',1)])
--   
minView :: () => MultiSet a -> Maybe (a, MultiSet a) -- | O(t). The elements of a multiset. elems :: () => MultiSet a -> [a] -- | O(n). The distinct elements of a multiset, each element occurs -- only once in the list. -- --
--   distinctElems = map fst . toOccurList
--   
distinctElems :: () => MultiSet a -> [a] -- | O(t). Convert the multiset to a list of elements. toList :: () => MultiSet a -> [a] -- | O(t). Convert the multiset to an ascending list of elements. toAscList :: () => MultiSet a -> [a] -- | O(n). Convert the multiset to a list of element/occurrence -- pairs. toOccurList :: () => MultiSet a -> [(a, Occur)] -- | O(n). Convert the multiset to an ascending list of -- element/occurrence pairs. toAscOccurList :: () => MultiSet a -> [(a, Occur)] -- | O(t*log t). Create a multiset from a list of elements. fromList :: Ord a => [a] -> MultiSet a -- | O(t). Build a multiset from an ascending list in linear time. -- The precondition (input list is ascending) is not checked. fromAscList :: Eq a => [a] -> MultiSet a -- | O(n). Build a multiset from an ascending list of distinct -- elements in linear time. The precondition (input list is strictly -- ascending) is not checked. fromDistinctAscList :: () => [a] -> MultiSet a -- | O(n*log n). Create a multiset from a list of element/occurrence -- pairs. Occurrences must be positive. The precondition (all -- occurrences > 0) is not checked. fromOccurList :: Ord a => [(a, Occur)] -> MultiSet a -- | O(n). Build a multiset from an ascending list of -- element/occurrence pairs in linear time. Occurrences must be positive. -- The precondition (input list is ascending, all occurrences > 0) -- is not checked. fromAscOccurList :: Eq a => [(a, Occur)] -> MultiSet a -- | O(n). Build a multiset from an ascending list of -- elements/occurrence pairs where each elements appears only once. -- Occurrences must be positive. The precondition (input list is -- strictly ascending, all occurrences > 0) is not checked. fromDistinctAscOccurList :: () => [(a, Occur)] -> MultiSet a -- | O(1). Convert a multiset to a Map from elements to -- number of occurrences. toMap :: () => MultiSet a -> Map a Occur -- | O(n). Convert a Map from elements to occurrences to a -- multiset. fromMap :: () => Map a Occur -> MultiSet a -- | O(1). Convert a Map from elements to occurrences to a -- multiset. Assumes that the Map contains only values larger than -- zero. The precondition (all elements > 0) is not checked. fromOccurMap :: () => Map a Occur -> MultiSet a -- | O(n). Convert a multiset to a Set, removing duplicates. toSet :: () => MultiSet a -> Set a -- | O(n). Convert a Set to a multiset. fromSet :: () => Set a -> MultiSet a module MultiSet.Int -- | A multiset of integers. The same value can occur multiple times. data IntMultiSet -- | Key type for IntMultiSet type Key = Int -- | O(1). Is this the empty multiset? null :: IntMultiSet -> Bool -- | O(n). The number of elements in the multiset. size :: IntMultiSet -> Int -- | O(1). The number of distinct elements in the multiset. distinctSize :: IntMultiSet -> Int -- | O(min(n,W)). Is the element in the multiset? member :: Key -> IntMultiSet -> Bool -- | O(min(n,W)). Is the element not in the multiset? notMember :: Key -> IntMultiSet -> Bool -- | O(min(n,W)). The number of occurrences of an element in a -- multiset. occur :: Key -> IntMultiSet -> Int -- | O(n+m). Is this a subset? (s1 `isSubsetOf` s2) tells -- whether s1 is a subset of s2. isSubsetOf :: IntMultiSet -> IntMultiSet -> Bool -- | O(n+m). Is this a proper subset? (ie. a subset but not equal). isProperSubsetOf :: IntMultiSet -> IntMultiSet -> Bool -- | O(1). The empty mutli set. empty :: IntMultiSet -- | O(1). Create a singleton mutli set. singleton :: Key -> IntMultiSet -- | O(min(n,W)). Insert an element in a multiset. insert :: Key -> IntMultiSet -> IntMultiSet -- | O(min(n,W)). Insert an element in a multiset a given number of -- times. -- -- Negative numbers remove occurrences of the given element. insertMany :: Key -> Occur -> IntMultiSet -> IntMultiSet -- | O(min(n,W)). Delete a single element from a multiset. delete :: Key -> IntMultiSet -> IntMultiSet -- | O(min(n,W)). Delete an element from a multiset a given number -- of times. -- -- Negative numbers add occurrences of the given element. deleteMany :: Key -> Occur -> IntMultiSet -> IntMultiSet -- | O(min(n,W)). Delete all occurrences of an element from a -- multiset. deleteAll :: Key -> IntMultiSet -> IntMultiSet -- | O(n+m). The union of two multisets. The union adds the -- occurrences together. -- -- The implementation uses the efficient hedge-union algorithm. -- Hedge-union is more efficient on (bigset union smallset). union :: IntMultiSet -> IntMultiSet -> IntMultiSet -- | The union of a list of multisets: (unions == foldl -- union empty). unions :: [IntMultiSet] -> IntMultiSet -- | O(n+m). The union of two multisets. The number of occurrences -- of each element in the union is the maximum of the number of -- occurrences in the arguments (instead of the sum). -- -- The implementation uses the efficient hedge-union algorithm. -- Hedge-union is more efficient on (bigset union smallset). maxUnion :: IntMultiSet -> IntMultiSet -> IntMultiSet -- | O(n+m). Difference of two multisets. The implementation uses an -- efficient hedge algorithm comparable with hedge-union. difference :: IntMultiSet -> IntMultiSet -> IntMultiSet -- | O(n+m). The intersection of two multisets. -- -- prints (fromList [A],fromList [B]). intersection :: IntMultiSet -> IntMultiSet -> IntMultiSet -- | O(n). Filter all elements that satisfy the predicate. filter :: Key -> Bool -> IntMultiSet -> IntMultiSet -- | O(n). Partition the multiset into two multisets, one with all -- elements that satisfy the predicate and one with all elements that -- don't satisfy the predicate. See also split. partition :: Key -> Bool -> IntMultiSet -> (IntMultiSet, IntMultiSet) -- | O(log n). The expression (split x set) is a -- pair (set1,set2) where all elements in set1 are -- lower than x and all elements in set2 larger than -- x. x is not found in neither set1 nor -- set2. split :: Int -> IntMultiSet -> (IntMultiSet, IntMultiSet) -- | O(log n). Performs a split but also returns the number -- of occurrences of the pivot element in the original set. splitOccur :: Int -> IntMultiSet -> (IntMultiSet, Int, IntMultiSet) -- | O(n*log n). map f s is the multiset obtained by -- applying f to each element of s. map :: Key -> Key -> IntMultiSet -> IntMultiSet -- | O(n). The -- -- mapMonotonic f s == map f s, but works only -- when f is strictly monotonic. The precondition is not -- checked. Semi-formally, we have: -- --
--   and [x < y ==> f x < f y | x <- ls, y <- ls]
--                       ==> mapMonotonic f s == map f s
--       where ls = toList s
--   
mapMonotonic :: Key -> Key -> IntMultiSet -> IntMultiSet -- | O(n). Map and collect the Just results. mapMaybe :: Key -> Maybe Key -> IntMultiSet -> IntMultiSet -- | O(n). Map and separate the Left and Right -- results. mapEither :: Key -> Either Key Key -> IntMultiSet -> (IntMultiSet, IntMultiSet) -- | O(n). Apply a function to each element, and take the union of -- the results concatMap :: Key -> [Key] -> IntMultiSet -> IntMultiSet -- | O(n). Apply a function to each element, and take the union of -- the results unionsMap :: Key -> IntMultiSet -> IntMultiSet -> IntMultiSet -- | O(n). The monad bind operation, (>>=), for multisets. bind :: IntMultiSet -> Key -> IntMultiSet -> IntMultiSet -- | O(n). The monad join operation for multisets. join :: MultiSet IntMultiSet -> IntMultiSet -- | O(t). Fold over the elements of a multiset in an unspecified -- order. fold :: () => Key -> b -> b -> b -> IntMultiSet -> b -- | O(n). Fold over the elements of a multiset with their -- occurrences. foldOccur :: () => Key -> Occur -> b -> b -> b -> IntMultiSet -> b -- | O(log n). The minimal element of a multiset. findMin :: IntMultiSet -> Key -- | O(log n). The maximal element of a multiset. findMax :: IntMultiSet -> Key -- | O(log n). Delete the minimal element. deleteMin :: IntMultiSet -> IntMultiSet -- | O(log n). Delete the maximal element. deleteMax :: IntMultiSet -> IntMultiSet -- | O(log n). Delete all occurrences of the minimal element. deleteMinAll :: IntMultiSet -> IntMultiSet -- | O(log n). Delete all occurrences of the maximal element. deleteMaxAll :: IntMultiSet -> IntMultiSet -- | O(log n). Delete and find the minimal element. -- --
--   deleteFindMin set = (findMin set, deleteMin set)
--   
deleteFindMin :: IntMultiSet -> (Key, IntMultiSet) -- | O(log n). Delete and find the maximal element. -- --
--   deleteFindMax set = (findMax set, deleteMax set)
--   
deleteFindMax :: IntMultiSet -> (Key, IntMultiSet) -- | O(log n). Retrieves the maximal element of the multiset, and -- the set stripped from that element fails (in the monad) when -- passed an empty multiset. -- -- Examples: -- --
--   >>> maxView $ fromList [100, 100, 200, 300]
--   Just (300,fromOccurList [(100,2),(200,1)])
--   
maxView :: IntMultiSet -> Maybe (Key, IntMultiSet) -- | O(log n). Retrieves the minimal element of the multiset, and -- the set stripped from that element Returns Nothing when -- passed an empty multiset. -- -- Examples: -- --
--   >>> minView $ fromList [100, 100, 200, 300]
--   Just (100,fromOccurList [(100,1),(200,1),(300,1)])
--   
minView :: IntMultiSet -> Maybe (Key, IntMultiSet) -- | O(t). The elements of a multiset. elems :: IntMultiSet -> [Key] -- | O(n). The distinct elements of a multiset, each element occurs -- only once in the list. -- --
--   distinctElems = map fst . toOccurList
--   
distinctElems :: IntMultiSet -> [Key] -- | O(t). Convert the multiset to a list of elements. toList :: IntMultiSet -> [Key] -- | O(t). Convert the multiset to an ascending list of elements. toAscList :: IntMultiSet -> [Key] -- | O(n). Convert the multiset to a list of element/occurrence -- pairs. toOccurList :: IntMultiSet -> [(Int, Int)] -- | O(n). Convert the multiset to an ascending list of -- element/occurrence pairs. toAscOccurList :: IntMultiSet -> [(Int, Int)] -- | O(t*min(n,W)). Create a multiset from a list of elements. fromList :: [Int] -> IntMultiSet -- | O(t). Build a multiset from an ascending list in linear time. -- The precondition (input list is ascending) is not checked. fromAscList :: [Int] -> IntMultiSet -- | O(n). Build a multiset from an ascending list of distinct -- elements in linear time. The precondition (input list is strictly -- ascending) is not checked. fromDistinctAscList :: [Int] -> IntMultiSet -- | O(n*min(n,W)). Create a multiset from a list of -- element/occurrence pairs. Occurrences must be positive. The -- precondition (all occurrences > 0) is not checked. fromOccurList :: [(Int, Int)] -> IntMultiSet -- | O(n). Build a multiset from an ascending list of -- element/occurrence pairs in linear time. Occurrences must be positive. -- The precondition (input list is ascending, all occurrences > 0) -- is not checked. fromAscOccurList :: [(Int, Int)] -> IntMultiSet -- | O(n). Build a multiset from an ascending list of -- elements/occurrence pairs where each elements appears only once. -- Occurrences must be positive. The precondition (input list is -- strictly ascending, all occurrences > 0) is not checked. fromDistinctAscOccurList :: [(Int, Int)] -> IntMultiSet -- | O(1). Convert a multiset to an IntMap from elements to -- number of occurrences. toMap :: IntMultiSet -> IntMap Int -- | O(n). Convert an IntMap from elements to occurrences to -- a multiset. fromMap :: IntMap Int -> IntMultiSet -- | O(1). Convert an IntMap from elements to occurrences to -- a multiset. Assumes that the IntMap contains only values larger -- than zero. The precondition (all elements > 0) is not -- checked. fromOccurMap :: IntMap Int -> IntMultiSet -- | O(n). Convert a multiset to an IntMap, removing -- duplicates. toSet :: IntMultiSet -> IntSet -- | O(n). Convert an IntMap to a multiset. fromSet :: IntSet -> IntMultiSet module Numeric.Approximate -- | An approximate number, with a likely interval, an expected value and a -- lower bound on the log of probability that the answer falls -- in the interval. -- -- NB: The probabilities associated with confidence are stored in -- the log domain. data Approximate a Approximate :: {-# UNPACK #-} !Log Double -> a -> a -> a -> Approximate a class HasApproximate c a | c -> a approximate :: HasApproximate c a => Lens' c Approximate a confidence :: HasApproximate c a => Lens' c Log Double estimate :: HasApproximate c a => Lens' c a hi :: HasApproximate c a => Lens' c a lo :: HasApproximate c a => Lens' c a exact :: Eq a => Prism' Approximate a a zero :: (Num a, Eq a) => Prism' Approximate a () one :: (Num a, Eq a) => Prism' Approximate a () withMin :: Ord a => a -> Approximate a -> Approximate a withMax :: Ord a => a -> Approximate a -> Approximate a module Numeric.Complex -- | Complex numbers are an algebraic type. -- -- For a complex number z, abs z is a number -- with the magnitude of z, but oriented in the positive real -- direction, whereas signum z has the phase of -- z, but unit magnitude. -- -- The Foldable and Traversable instances traverse the real -- part first. data Complex a -- | Extracts the real part of a complex number. realPart :: () => Complex a -> a -- | Extracts the imaginary part of a complex number. imagPart :: () => Complex a -> a -- | Form a complex number from polar components of magnitude and phase. mkPolar :: Floating a => a -> a -> Complex a -- | cis t is a complex value with magnitude 1 and -- phase t (modulo 2*pi). cis :: Floating a => a -> Complex a -- | The function polar takes a complex number and returns a -- (magnitude, phase) pair in canonical form: the magnitude is -- nonnegative, and the phase in the range (-pi, -- pi]; if the magnitude is zero, then so is the phase. polar :: RealFloat a => Complex a -> (a, a) -- | The nonnegative magnitude of a complex number. magnitude :: RealFloat a => Complex a -> a -- | The phase of a complex number, in the range (-pi, -- pi]. If the magnitude is zero, then so is the phase. phase :: RealFloat a => Complex a -> a -- | The conjugate of a complex number. conjugate :: Num a => Complex a -> Complex a -- | Access the realPart of a Complex number. -- --
--   >>> (a :+ b)^._realPart
--   a
--   
-- --
--   >>> a :+ b & _realPart *~ 2
--   a * 2 :+ b
--   
-- --
--   _realPart :: Functor f => (a -> f a) -> Complex a -> f (Complex a)
--   
_realPart :: Functor f => a -> f a -> Complex a -> f Complex a -- | Access the imagPart of a Complex number. -- --
--   >>> (a :+ b)^._imagPart
--   b
--   
-- --
--   >>> a :+ b & _imagPart *~ 2
--   a :+ b * 2
--   
-- --
--   _imagPart :: Functor f => (a -> f a) -> Complex a -> f (Complex a)
--   
_imagPart :: Functor f => a -> f a -> Complex a -> f Complex a -- | This isn't quite a legal Lens. Notably the -- --
--   view l (set l b a) = b
--   
-- -- law is violated when you set a polar value with 0 -- magnitude and non-zero phase as the phase -- information is lost, or with a negative magnitude which flips -- the phase and retains a positive magnitude. So don't do -- that! -- -- Otherwise, this is a perfectly cromulent Lens. _polar :: RealFloat a => Iso' Complex a (a, a) -- | Access the magnitude of a Complex number. -- --
--   >>> (10.0 :+ 20.0) & _magnitude *~ 2
--   20.0 :+ 40.0
--   
-- -- This isn't quite a legal Lens. Notably the -- --
--   view l (set l b a) = b
--   
-- -- law is violated when you set a negative magnitude. This flips -- the phase and retains a positive magnitude. So don't do -- that! -- -- Otherwise, this is a perfectly cromulent Lens. -- -- Setting the magnitude of a zero Complex number assumes -- the phase is 0. _magnitude :: RealFloat a => Lens' Complex a a -- | Access the phase of a Complex number. -- --
--   >>> (mkPolar 10 (2-pi) & _phase +~ pi & view _phase) ≈ 2
--   True
--   
-- -- This isn't quite a legal Lens. Notably the -- --
--   view l (set l b a) = b
--   
-- -- law is violated when you set a phase outside the range -- (-pi, pi]. The phase is always in that range -- when queried. So don't do that! -- -- Otherwise, this is a perfectly cromulent Lens. _phase :: RealFloat a => Lens' Complex a a -- | Access the conjugate of a Complex number. -- --
--   >>> (2.0 :+ 3.0) & _conjugate . _imagPart -~ 1
--   2.0 :+ 4.0
--   
-- --
--   >>> (mkPolar 10.0 2.0 ^. _conjugate . _phase) ≈ (-2.0)
--   True
--   
_conjugate :: RealFloat a => Iso' Complex a Complex a module Numeric.Double -- | 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 -- | Compute a representation in exponential format with the requested -- number of digits after the decimal point. The last emitted digit is -- rounded. If -1 digits are requested, then the shortest exponential -- representation is computed. toExponential :: Int -> Double -> Text -- | Compute a decimal representation with a fixed number of digits after -- the decimal point. The last emitted digit is rounded. toFixed :: Int -> Double -> Text -- | Compute precision leading digits of the given value either in -- exponential or decimal format. The last computed digit is rounded. toPrecision :: Int -> Double -> Text -- | Compute the shortest string of digits that correctly represent the -- input number. toShortest :: Double -> Text module Numeric.Erf -- | Error function related functions. -- -- The derivative of erf is x -> 2 / sqrt pi * exp -- (x^2), and this uniquely determines erf by erf 0 = -- 0. -- -- Minimal complete definition is erfc or normcdf. class Floating a => Erf a erf :: Erf a => a -> a erfc :: Erf a => a -> a erfcx :: Erf a => a -> a normcdf :: Erf a => a -> a module Numeric.Fast class Floating a => Fast a -- | Calculate an approximate log. flog :: Fast a => a -> a flog_lb :: Fast a => a -> a flog_ub :: Fast a => a -> a -- | Calculate an approximate exp. fexp :: Fast a => a -> a fexp_lb :: Fast a => a -> a fexp_ub :: Fast a => a -> a -- | Calculate an approximate pow. fpow :: Fast a => a -> a -> a fpow_lb :: Fast a => a -> a -> a fpow_ub :: Fast a => a -> a -> a -- | Borchardt’s Algorithm from “Dead Reckoning: Calculating without -- instruments”. -- -- This is a remarkably bad approximate logarithm. -- -- flog had better outperform it! It is provided merely for -- comparison. blog :: Floating a => a -> a module Numeric.Float -- | 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 module Numeric.Floating -- | Trigonometric and hyperbolic functions and related functions. class Fractional a => Floating a pi :: Floating a => a exp :: Floating a => a -> a log :: Floating a => a -> a sqrt :: Floating a => a -> a (**) :: Floating a => a -> a -> a logBase :: Floating a => a -> a -> a sin :: Floating a => a -> a cos :: Floating a => a -> a tan :: Floating a => a -> a asin :: Floating a => a -> a acos :: Floating a => a -> a atan :: Floating a => a -> a sinh :: Floating a => a -> a cosh :: Floating a => a -> a tanh :: Floating a => a -> a asinh :: Floating a => a -> a acosh :: Floating a => a -> a atanh :: Floating a => a -> a -- | log1p x computes log (1 + x), but -- provides more precise results for small (absolute) values of -- x if possible. log1p :: Floating a => a -> a -- | expm1 x computes exp x - 1, but -- provides more precise results for small (absolute) values of -- x if possible. expm1 :: Floating a => a -> a -- | log1pexp x computes log (1 + exp -- x), but provides more precise results if possible. -- -- Examples: -- -- log1pexp :: Floating a => a -> a -- | log1mexp x computes log (1 - exp -- x), but provides more precise results if possible. -- -- Examples: -- -- log1mexp :: Floating a => a -> a module Numeric.Fractional -- | Fractional numbers, supporting real division. 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 module Numeric.Half newtype Half Half :: CUShort -> Half [getHalf] :: Half -> CUShort -- | Is this Half equal to 0? isZero :: Half -> Bool -- | Convert a Half to a Float while preserving NaN fromHalf :: Half -> Float -- | Convert a Float to a Half with proper rounding, while -- preserving NaN and dealing appropriately with infinity toHalf :: Float -> Half -- | Positive infinity -- | Negative infinity -- | Quiet NaN -- | Signalling NaN -- | Smallest positive half -- | Smallest positive normalized half -- | Largest positive half -- | Smallest positive e for which half (1.0 + e) != half (1.0) -- | Number of base 10 digits that can be represented without change module Numeric.Int -- | 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 -- | Calculate the integer logarithm of an Int to base 2. The -- argument must be positive, otherwise an error is thrown. intLog2 :: Int -> 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 module Numeric.Integer -- | Invariant: Jn# and Jp# are used iff value doesn't fit in -- S# -- -- Useful properties resulting from the invariants: -- -- data Integer -- | Calculate the integer logarithm for an arbitrary base. The base must -- be greater than 1, the second argument, the number whose logarithm is -- sought, must be positive, otherwise an error is thrown. If base == -- 2, the specialised version is called, which is more efficient -- than the general algorithm. -- -- Satisfies: -- --
--   base ^ integerLogBase base m <= m < base ^ (integerLogBase base m + 1)
--   
-- -- for base > 1 and m > 0. integerLogBase :: Integer -> Integer -> Int -- | Calculate the integer logarithm of an Integer to base 2. The -- argument must be positive, otherwise an error is thrown. integerLog2 :: Integer -> Int -- | Calculate the integer logarithm of an Integer to base 10. The -- argument must be positive, otherwise an error is thrown. integerLog10 :: Integer -> Int module Numeric.Integral -- | Integral numbers, supporting integer division. 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 even :: Integral a => a -> Bool odd :: 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 -- | general coercion from integral types fromIntegral :: (Integral a, Num b) => a -> b -- | Show non-negative Integral numbers in base 10. showInt :: Integral a => a -> ShowS -- | Shows a non-negative Integral number using the base -- specified by the first argument, and the character representation -- specified by the second. showIntAtBase :: (Integral a, Show a) => a -> Int -> Char -> a -> ShowS -- | Show non-negative Integral numbers in base 8. showOct :: (Integral a, Show a) => a -> ShowS -- | Show non-negative Integral numbers in base 16. showHex :: (Integral a, Show a) => a -> ShowS module Numeric.InvErf -- | Inverse error functions, e.g., inverf . erf = id and erf -- . inverf = id assuming the appropriate codomain for -- inverf. Note that the accuracy may drop radically for extreme -- arguments. class Floating a => InvErf a inverf :: InvErf a => a -> a inverfc :: InvErf a => a -> a invnormcdf :: InvErf a => a -> a module Numeric.Nat -- | (Kind) This is the kind of type-level natural numbers. data Nat -- | 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) natVal :: KnownNat n => proxy n -> Integer natVal' :: KnownNat n => Proxy# n -> Integer -- | This type represents unknown type-level natural numbers. data SomeNat [SomeNat] :: SomeNat -- | Convert an integer into an unknown type-level natural. someNatVal :: Integer -> Maybe SomeNat -- | We either get evidence that this function was instantiated with the -- same type-level numbers, or Nothing. sameNat :: (KnownNat a, KnownNat b) => Proxy a -> Proxy b -> Maybe a :~: b -- | Comparison of type-level naturals, as a constraint. type (<=) (x :: Nat) (y :: Nat) = x <=? y ~ True -- | Comparison of type-level naturals, as a function. NOTE: The -- functionality for this function should be subsumed by CmpNat, -- so this might go away in the future. Please let us know, if you -- encounter discrepancies between the two. -- | Addition of type-level naturals. -- | Multiplication of type-level naturals. -- | Exponentiation of type-level naturals. -- | Subtraction of type-level naturals. type Divides (n :: Nat) (m :: Nat) = n ~ Gcd n m -- | Division (round down) of natural numbers. Div x 0 is -- undefined (i.e., it cannot be reduced). -- | Modulus of natural numbers. Mod x 0 is undefined (i.e., it -- cannot be reduced). -- | Log base 2 (round down) of natural numbers. Log 0 is -- undefined (i.e., it cannot be reduced). -- | Comparison of type-level naturals, as a function. plusNat :: () => (KnownNat n, KnownNat m) :- KnownNat n + m timesNat :: () => (KnownNat n, KnownNat m) :- KnownNat n * m powNat :: () => (KnownNat n, KnownNat m) :- KnownNat n ^ m minNat :: () => (KnownNat n, KnownNat m) :- KnownNat Min n m maxNat :: () => (KnownNat n, KnownNat m) :- KnownNat Max n m gcdNat :: () => (KnownNat n, KnownNat m) :- KnownNat Gcd n m lcmNat :: () => (KnownNat n, KnownNat m) :- KnownNat Lcm n m divNat :: () => (KnownNat n, KnownNat m, 1 <= m) :- KnownNat Div n m modNat :: () => (KnownNat n, KnownNat m, 1 <= m) :- KnownNat Mod n m plusZero :: () => Dict n + 0 ~ n timesZero :: () => Dict n * 0 ~ 0 timesOne :: () => Dict n * 1 ~ n powZero :: () => Dict n ^ 0 ~ 1 powOne :: () => Dict n ^ 1 ~ n maxZero :: () => Dict Max n 0 ~ n minZero :: () => Dict Min n 0 ~ 0 gcdZero :: () => Dict Gcd 0 a ~ a gcdOne :: () => Dict Gcd 1 a ~ 1 lcmZero :: () => Dict Lcm 0 a ~ 0 lcmOne :: () => Dict Lcm 1 a ~ a plusAssociates :: () => Dict m + n + o ~ m + n + o timesAssociates :: () => Dict m * n * o ~ m * n * o minAssociates :: () => Dict Min Min m n o ~ Min m Min n o maxAssociates :: () => Dict Max Max m n o ~ Max m Max n o gcdAssociates :: () => Dict Gcd Gcd a b c ~ Gcd a Gcd b c lcmAssociates :: () => Dict Lcm Lcm a b c ~ Lcm a Lcm b c plusCommutes :: () => Dict m + n ~ n + m timesCommutes :: () => Dict m * n ~ n * m minCommutes :: () => Dict Min m n ~ Min n m maxCommutes :: () => Dict Max m n ~ Max n m gcdCommutes :: () => Dict Gcd a b ~ Gcd b a lcmCommutes :: () => Dict Lcm a b ~ Lcm b a plusDistributesOverTimes :: () => Dict n * m + o ~ n * m + n * o timesDistributesOverPow :: () => Dict n ^ m + o ~ n ^ m * n ^ o timesDistributesOverGcd :: () => Dict n * Gcd m o ~ Gcd n * m n * o timesDistributesOverLcm :: () => Dict n * Lcm m o ~ Lcm n * m n * o minDistributesOverPlus :: () => Dict n + Min m o ~ Min n + m n + o minDistributesOverTimes :: () => Dict n * Min m o ~ Min n * m n * o minDistributesOverPow1 :: () => Dict Min n m ^ o ~ Min n ^ o m ^ o minDistributesOverPow2 :: () => Dict n ^ Min m o ~ Min n ^ m n ^ o minDistributesOverMax :: () => Dict Max n Min m o ~ Min Max n m Max n o maxDistributesOverPlus :: () => Dict n + Max m o ~ Max n + m n + o maxDistributesOverTimes :: () => Dict n * Max m o ~ Max n * m n * o maxDistributesOverPow1 :: () => Dict Max n m ^ o ~ Max n ^ o m ^ o maxDistributesOverPow2 :: () => Dict n ^ Max m o ~ Max n ^ m n ^ o maxDistributesOverMin :: () => Dict Min n Max m o ~ Max Min n m Min n o gcdDistributesOverLcm :: () => Dict Gcd Lcm a b c ~ Lcm Gcd a c Gcd b c lcmDistributesOverGcd :: () => Dict Lcm Gcd a b c ~ Gcd Lcm a c Lcm b c minIsIdempotent :: () => Dict Min n n ~ n maxIsIdempotent :: () => Dict Max n n ~ n lcmIsIdempotent :: () => Dict Lcm n n ~ n gcdIsIdempotent :: () => Dict Gcd n n ~ n plusIsCancellative :: () => n + m ~ n + o :- m ~ o timesIsCancellative :: () => (1 <= n, n * m ~ n * o) :- m ~ o dividesPlus :: () => (Divides a b, Divides a c) :- Divides a b + c dividesTimes :: () => (Divides a b, Divides a c) :- Divides a b * c dividesMin :: () => (Divides a b, Divides a c) :- Divides a Min b c dividesMax :: () => (Divides a b, Divides a c) :- Divides a Max b c dividesPow :: () => (1 <= n, Divides a b) :- Divides a b ^ n dividesGcd :: () => (Divides a b, Divides a c) :- Divides a Gcd b c dividesLcm :: () => (Divides a c, Divides b c) :- Divides Lcm a b c plusMonotone1 :: () => a <= b :- a + c <= b + c plusMonotone2 :: () => b <= c :- a + b <= a + c timesMonotone1 :: () => a <= b :- a * c <= b * c timesMonotone2 :: () => b <= c :- a * b <= a * c powMonotone1 :: () => a <= b :- a ^ c <= b ^ c powMonotone2 :: () => b <= c :- a ^ b <= a ^ c minMonotone1 :: () => a <= b :- Min a c <= Min b c minMonotone2 :: () => b <= c :- Min a b <= Min a c maxMonotone1 :: () => a <= b :- Max a c <= Max b c maxMonotone2 :: () => b <= c :- Max a b <= Max a c divMonotone1 :: () => a <= b :- Div a c <= Div b c divMonotone2 :: () => b <= c :- Div a c <= Div a b euclideanNat :: () => 1 <= c :- a ~ c * Div a c + Mod a c plusMod :: () => 1 <= c :- Mod a + b c ~ Mod Mod a c + Mod b c c timesMod :: () => 1 <= c :- Mod a * b c ~ Mod Mod a c * Mod b c c modBound :: () => 1 <= n :- Mod m n <= n dividesDef :: () => Divides a b :- a * Div b a ~ a timesDiv :: () => Dict a * Div b a <= a eqLe :: () => a ~ b :- a <= b leEq :: () => (a <= b, b <= a) :- a ~ b leId :: () => Dict a <= a leTrans :: () => (b <= c, a <= b) :- a <= c zeroLe :: () => Dict 0 <= a module Numeric.Natural -- | Type representing arbitrary-precision non-negative integers. -- --
--   >>> 2^20 :: Natural
--   1267650600228229401496703205376
--   
-- -- Operations whose result would be negative throw -- (Underflow :: ArithException), -- --
--   >>> -1 :: Natural
--   *** Exception: arithmetic underflow
--   
data Natural -- | Cacluate the integer logarithm for an arbitrary base. The base must be -- greater than 1, the second argument, the number whose logarithm is -- sought, must be positive, otherwise an error is thrown. If base == -- 2, the specialised version is called, which is more efficient -- than the general algorithm. -- -- Satisfies: -- --
--   base ^ integerLogBase base m <= m < base ^ (integerLogBase base m + 1)
--   
-- -- for base > 1 and m > 0. naturalLogBase :: Natural -> Natural -> Int -- | Calculate the natural logarithm of an Natural to base 2. The -- argument must be non-zero, otherwise an error is thrown. naturalLog2 :: Natural -> Int -- | Calculate the integer logarithm of an Integer to base 10. The -- argument must be not zero, otherwise an error is thrown. naturalLog10 :: Natural -> Int module Numeric.Num -- | Basic numeric class. class Num a (+) :: Num a => a -> a -> a (-) :: Num a => a -> a -> a (*) :: Num a => a -> a -> a -- | Unary negation. negate :: Num a => a -> a -- | Absolute value. abs :: Num a => a -> a -- | Sign of a number. The functions abs and signum should -- satisfy the law: -- --
--   abs x * signum x == x
--   
-- -- For real numbers, the signum is either -1 (negative), -- 0 (zero) or 1 (positive). signum :: Num a => a -> a -- | Conversion from an Integer. An integer literal represents the -- application of the function fromInteger to the appropriate -- value of type Integer, so such literals have type -- (Num a) => a. fromInteger :: Num a => Integer -> a -- | 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 -- | Reads an unsigned Integral value in an arbitrary base. readInt :: Num a => a -> Char -> Bool -> Char -> Int -> ReadS a -- | Read an unsigned number in decimal notation. -- --
--   >>> readDec "0644"
--   [(644,"")]
--   
readDec :: (Eq a, Num a) => ReadS a -- | Read an unsigned number in octal notation. -- --
--   >>> readOct "0644"
--   [(420,"")]
--   
readOct :: (Eq a, Num a) => ReadS a -- | Read an unsigned number in hexadecimal notation. Both upper or lower -- case letters are allowed. -- --
--   >>> readHex "deadbeef"
--   [(3735928559,"")]
--   
readHex :: (Eq a, Num a) => ReadS a module Numeric.Product -- | Monoid under multiplication. -- --
--   >>> getProduct (Product 3 <> Product 4 <> mempty)
--   12
--   
newtype Product a Product :: a -> Product a [getProduct] :: Product a -> a module Numeric.Ratio -- | Rational numbers, with numerator and denominator of some -- Integral type. data Ratio a -- | Arbitrary-precision rational numbers, represented as a ratio of two -- Integer values. A rational number may be constructed using the -- % operator. type Rational = Ratio Integer -- | Forms the ratio of two integral numbers. (%) :: Integral a => a -> a -> Ratio a infixl 7 % -- | 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 -- | 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 -- | approxRational, applied to two real fractional numbers -- x and epsilon, returns the simplest rational number -- within epsilon of x. A rational number y is -- said to be simpler than another y' if -- -- -- -- Any real interval contains a unique simplest rational; in particular, -- note that 0/1 is the simplest rational of all. approxRational :: RealFrac a => a -> a -> Rational -- | Converts a Rational value into any type in class -- RealFloat. fromRat :: RealFloat a => Rational -> a module Numeric.Real class (Num a, Ord a) => Real a -- | the rational equivalent of its real argument with full precision toRational :: Real a => a -> Rational -- | generalisation of div to any instance of Real div' :: (Real a, Integral b) => a -> a -> b -- | generalisation of mod to any instance of Real mod' :: Real a => a -> a -> a -- | generalisation of divMod to any instance of Real divMod' :: (Real a, Integral b) => a -> a -> (b, a) -- | general coercion to fractional types realToFrac :: (Real a, Fractional b) => a -> b -- | Converts a possibly-negative Real value to a string. showSigned :: Real a => a -> ShowS -> Int -> a -> ShowS -- | Reads a signed Real value, given a reader for an -- unsigned value. readSigned :: Real a => ReadS a -> ReadS a module Numeric.RealFloat -- | Efficient, machine-independent access to the components of a -- floating-point number. class (RealFrac a, Floating a) => RealFloat a -- | a constant function, returning the radix of the representation (often -- 2) floatRadix :: RealFloat a => a -> Integer -- | a constant function, returning the number of digits of -- floatRadix in the significand floatDigits :: RealFloat a => a -> Int -- | a constant function, returning the lowest and highest values the -- exponent may assume floatRange :: RealFloat a => a -> (Int, Int) -- | The function decodeFloat applied to a real floating-point -- number returns the significand expressed as an Integer and an -- appropriately scaled exponent (an Int). If -- decodeFloat x yields (m,n), then x -- is equal in value to m*b^^n, where b is the -- floating-point radix, and furthermore, either m and -- n are both zero or else b^(d-1) <= abs m < -- b^d, where d is the value of floatDigits -- x. In particular, decodeFloat 0 = (0,0). If the -- type contains a negative zero, also decodeFloat (-0.0) = -- (0,0). The result of decodeFloat x is -- unspecified if either of isNaN x or -- isInfinite x is True. decodeFloat :: RealFloat a => a -> (Integer, Int) -- | encodeFloat performs the inverse of decodeFloat in the -- sense that for finite x with the exception of -0.0, -- uncurry encodeFloat (decodeFloat x) = -- x. encodeFloat m n is one of the two closest -- representable floating-point numbers to m*b^^n (or -- ±Infinity if overflow occurs); usually the closer, but if -- m contains too many bits, the result may be rounded in the -- wrong direction. encodeFloat :: RealFloat a => Integer -> Int -> a -- | exponent corresponds to the second component of -- decodeFloat. exponent 0 = 0 and for finite -- nonzero x, exponent x = snd (decodeFloat x) -- + floatDigits x. If x is a finite floating-point -- number, it is equal in value to significand x * b ^^ -- exponent x, where b is the floating-point radix. -- The behaviour is unspecified on infinite or NaN values. exponent :: RealFloat a => a -> Int -- | The first component of decodeFloat, scaled to lie in the open -- interval (-1,1), either 0.0 or of absolute -- value >= 1/b, where b is the floating-point -- radix. The behaviour is unspecified on infinite or NaN -- values. significand :: RealFloat a => a -> a -- | multiplies a floating-point number by an integer power of the radix scaleFloat :: RealFloat a => Int -> a -> a -- | True if the argument is an IEEE "not-a-number" (NaN) value isNaN :: RealFloat a => a -> Bool -- | True if the argument is an IEEE infinity or negative infinity isInfinite :: RealFloat a => a -> Bool -- | True if the argument is too small to be represented in -- normalized format isDenormalized :: RealFloat a => a -> Bool -- | True if the argument is an IEEE negative zero isNegativeZero :: RealFloat a => a -> Bool -- | True if the argument is an IEEE floating point number isIEEE :: RealFloat a => a -> Bool -- | a version of arctangent taking two real floating-point arguments. For -- real floating x and y, atan2 y x -- computes the angle (from the positive x-axis) of the vector from the -- origin to the point (x,y). atan2 y x returns -- a value in the range [-pi, pi]. It follows the -- Common Lisp semantics for the origin when signed zeroes are supported. -- atan2 y 1, with y in a type that is -- RealFloat, should return the same value as atan -- y. A default definition of atan2 is provided, but -- implementors can provide a more accurate implementation. atan2 :: RealFloat a => a -> a -> a -- | floatToDigits takes a base and a non-negative RealFloat -- number, and returns a list of digits and an exponent. In particular, -- if x>=0, and -- --
--   floatToDigits base x = ([d1,d2,...,dn], e)
--   
-- -- then -- --
    --
  1. n >= 1
  2. --
  3. x = 0.d1d2...dn * (base**e)
  4. --
  5. 0 <= di <= base-1
  6. --
floatToDigits :: RealFloat a => Integer -> a -> ([Int], Int) -- | Show a signed RealFloat value using scientific (exponential) -- notation (e.g. 2.45e2, 1.5e-3). -- -- In the call showEFloat digs val, if digs is -- Nothing, the value is shown to full precision; if digs -- is Just d, then at most d digits after the -- decimal point are shown. showEFloat :: RealFloat a => Maybe Int -> a -> ShowS -- | Show a signed RealFloat value using standard decimal notation -- (e.g. 245000, 0.0015). -- -- In the call showFFloat digs val, if digs is -- Nothing, the value is shown to full precision; if digs -- is Just d, then at most d digits after the -- decimal point are shown. showFFloat :: RealFloat a => Maybe Int -> a -> ShowS -- | Show a signed RealFloat value using standard decimal notation -- for arguments whose absolute value lies between 0.1 and -- 9,999,999, and scientific notation otherwise. -- -- In the call showGFloat digs val, if digs is -- Nothing, the value is shown to full precision; if digs -- is Just d, then at most d digits after the -- decimal point are shown. showGFloat :: RealFloat a => Maybe Int -> a -> ShowS -- | Show a signed RealFloat value using standard decimal notation -- (e.g. 245000, 0.0015). -- -- This behaves as showFFloat, except that a decimal point is -- always guaranteed, even if not needed. showFFloatAlt :: RealFloat a => Maybe Int -> a -> ShowS -- | Show a signed RealFloat value using standard decimal notation -- for arguments whose absolute value lies between 0.1 and -- 9,999,999, and scientific notation otherwise. -- -- This behaves as showFFloat, except that a decimal point is -- always guaranteed, even if not needed. showGFloatAlt :: RealFloat a => Maybe Int -> a -> ShowS -- | Show a signed RealFloat value to full precision using standard -- decimal notation for arguments whose absolute value lies between -- 0.1 and 9,999,999, and scientific notation -- otherwise. showFloat :: RealFloat a => a -> ShowS -- | Show a floating-point value in the hexadecimal format, similar to the -- %a specifier in C's printf. -- --
--   >>> showHFloat (212.21 :: Double) ""
--   "0x1.a86b851eb851fp7"
--   
--   >>> showHFloat (-12.76 :: Float) ""
--   "-0x1.9851ecp3"
--   
--   >>> showHFloat (-0 :: Double) ""
--   "-0x0p+0"
--   
showHFloat :: RealFloat a => a -> ShowS module Numeric.RealFrac -- | 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 -- | Reads an unsigned RealFrac value, expressed in decimal -- scientific notation. readFloat :: RealFrac a => ReadS a module Numeric.Scientific module Numeric.Sum -- | Monoid under addition. -- --
--   >>> getSum (Sum 1 <> Sum 2 <> mempty)
--   3
--   
newtype Sum a Sum :: a -> Sum a [getSum] :: Sum a -> a module Numeric.Word -- | A Word is an unsigned integral type, with the same size as -- Int. data Word -- | Calculate the integer logarithm of a Word to base 2. The -- argument must be positive, otherwise an error is thrown. wordLog2 :: Word -> Int -- | 8-bit unsigned integer type data Word8 -- | 16-bit unsigned integer type data Word16 -- | Swap bytes in Word16. byteSwap16 :: Word16 -> Word16 -- | 32-bit unsigned integer type data Word32 -- | Reverse order of bytes in Word32. byteSwap32 :: Word32 -> Word32 -- | 64-bit unsigned integer type data Word64 -- | Reverse order of bytes in Word64. byteSwap64 :: Word64 -> Word64 module Optic.Fold -- | A Fold describes how to retrieve multiple values in a way that -- can be composed with other LensLike constructions. -- -- A Fold s a provides a structure with operations very -- similar to those of the Foldable typeclass, see -- foldMapOf and the other Fold combinators. -- -- By convention, if there exists a foo method that expects a -- Foldable (f a), then there should be a fooOf -- method that takes a Fold s a and a value of type -- s. -- -- A Getter is a legal Fold that just ignores the supplied -- Monoid. -- -- Unlike a Traversal a Fold is read-only. Since a -- Fold cannot be used to write back there are no Lens laws -- that apply. type Fold s a = forall (f :: * -> *). (Contravariant f, Applicative f) => a -> f a -> s -> f s -- | 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 ^.. -- | 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. -- --
--   >>> Left 4 ^?_Left
--   Just 4
--   
-- --
--   >>> Right 4 ^?_Left
--   Nothing
--   
-- --
--   >>> "world" ^? ix 3
--   Just 'l'
--   
-- --
--   >>> "world" ^? ix 20
--   Nothing
--   
-- --
--   (^?) ≡ flip preview
--   
-- --
--   (^?) :: 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 ^? -- | This converts a Fold to a IndexPreservingGetter that -- returns the first element, if it exists, as a Maybe. -- --
--   pre :: Getter s a     -> IndexPreservingGetter s (Maybe a)
--   pre :: Fold s a       -> IndexPreservingGetter s (Maybe a)
--   pre :: Traversal' s a -> IndexPreservingGetter s (Maybe a)
--   pre :: Lens' s a      -> IndexPreservingGetter s (Maybe a)
--   pre :: Iso' s a       -> IndexPreservingGetter s (Maybe a)
--   pre :: Prism' s a     -> IndexPreservingGetter s (Maybe a)
--   
pre :: () => Getting First a s a -> IndexPreservingGetter s Maybe a -- | Retrieve the first value targeted by a Fold or Traversal -- (or Just the result from a Getter or Lens). See -- also (^?). -- --
--   listToMaybe . toListpreview folded
--   
-- -- This is usually applied in the Reader Monad (->) -- s. -- --
--   preview = view . pre
--   
-- --
--   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
--   
-- -- However, it may be useful to think of its full generality when working -- with a Monad transformer stack: -- --
--   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 -- | Retrieve a function of the first value targeted by a Fold or -- Traversal (or Just the result from a Getter or -- Lens). -- -- This is usually applied in the Reader Monad (->) -- s. previews :: MonadReader s m => Getting First r s a -> a -> r -> m Maybe r -- | 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 a function of the first value targeted by a Fold or -- Traversal (or Just the result from a Getter or -- Lens) into the current state. -- --
--   preuses = uses . pre
--   
-- --
--   preuses :: MonadState s m => Getter s a     -> (a -> r) -> m (Maybe r)
--   preuses :: MonadState s m => Fold s a       -> (a -> r) -> m (Maybe r)
--   preuses :: MonadState s m => Lens' s a      -> (a -> r) -> m (Maybe r)
--   preuses :: MonadState s m => Iso' s a       -> (a -> r) -> m (Maybe r)
--   preuses :: MonadState s m => Traversal' s a -> (a -> r) -> m (Maybe r)
--   
preuses :: MonadState s m => Getting First r s a -> a -> r -> m Maybe r -- | Check to see if this Fold or Traversal matches 1 or more -- entries. -- --
--   >>> has (element 0) []
--   False
--   
-- --
--   >>> has _Left (Left 12)
--   True
--   
-- --
--   >>> has _Right (Left 12)
--   False
--   
-- -- This will always return True for a Lens or -- Getter. -- --
--   >>> has _1 ("hello","world")
--   True
--   
-- --
--   has :: Getter s a     -> s -> Bool
--   has :: Fold s a       -> s -> Bool
--   has :: Iso' s a       -> s -> Bool
--   has :: Lens' s a      -> s -> Bool
--   has :: Traversal' s a -> s -> Bool
--   
has :: () => Getting Any s a -> s -> Bool -- | Check to see if this Fold or Traversal has no matches. -- --
--   >>> hasn't _Left (Right 12)
--   True
--   
-- --
--   >>> hasn't _Left (Left 12)
--   False
--   
hasn't :: () => Getting All s a -> s -> Bool -- | Obtain a Fold by lifting an operation that returns a -- Foldable result. -- -- This can be useful to lift operations from Data.List and -- elsewhere into a Fold. -- --
--   >>> [1,2,3,4]^..folding tail
--   [2,3,4]
--   
folding :: Foldable f => s -> f a -> Fold s a -- | Obtain a Fold from any Foldable indexed by ordinal -- position. -- --
--   >>> Just 3^..folded
--   [3]
--   
-- --
--   >>> Nothing^..folded
--   []
--   
-- --
--   >>> [(1,2),(3,4)]^..folded.both
--   [1,2,3,4]
--   
folded :: Foldable f => IndexedFold Int f a a -- | Obtain a Fold from any Foldable indexed by ordinal -- position. folded64 :: Foldable f => IndexedFold Int64 f a a -- | Build a Fold that unfolds its values from a seed. -- --
--   unfoldrtoListOf . unfolded
--   
-- --
--   >>> 10^..unfolded (\b -> if b == 0 then Nothing else Just (b, b-1))
--   [10,9,8,7,6,5,4,3,2,1]
--   
unfolded :: () => b -> Maybe (a, b) -> Fold b a -- | x ^. iterated f returns an infinite -- Fold1 of repeated applications of f to x. -- --
--   toListOf (iterated f) a ≡ iterate f a
--   
-- --
--   iterated :: (a -> a) -> Fold1 a a
--   
iterated :: Apply f => a -> a -> LensLike' f a a -- | Obtain an Fold that can be composed with to filter another -- Lens, Iso, Getter, Fold (or -- Traversal). -- -- Note: This is not a legal Traversal, unless you are very -- careful not to invalidate the predicate on the target. -- -- Note: This is also not a legal Prism, unless you are -- very careful not to inject a value that matches the predicate. -- -- As a counter example, consider that given evens = filtered -- even the second Traversal law is violated: -- --
--   over evens succ . over evens succ /= over evens (succ . succ)
--   
-- -- So, in order for this to qualify as a legal Traversal you can -- only use it for actions that preserve the result of the predicate! -- --
--   >>> [1..10]^..folded.filtered even
--   [2,4,6,8,10]
--   
-- -- This will preserve an index if it is present. filtered :: (Choice p, Applicative f) => a -> Bool -> Optic' p f a a -- | This allows you to traverse the elements of a pretty much any -- LensLike construction in the opposite order. -- -- This will preserve indexes on Indexed types and will give you -- the elements of a (finite) Fold or Traversal in the -- opposite order. -- -- This has no practical impact on a Getter, Setter, -- Lens or Iso. -- -- NB: To write back through an Iso, you want to use -- from. Similarly, to write back through an Prism, you -- want to use re. backwards :: (Profunctor p, Profunctor q) => Optical p q Backwards f s t a b -> Optical p q f s t a b -- | Form a Fold1 by repeating the input forever. -- --
--   repeattoListOf repeated
--   
-- --
--   >>> timingOut $ 5^..taking 20 repeated
--   [5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5]
--   
-- --
--   repeated :: Fold1 a a
--   
repeated :: Apply f => LensLike' f a a -- | A Fold that replicates its input n times. -- --
--   replicate n ≡ toListOf (replicated n)
--   
-- --
--   >>> 5^..replicated 20
--   [5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5]
--   
replicated :: () => Int -> Fold a a -- | Transform a non-empty Fold into a Fold1 that loops over -- its elements over and over. -- --
--   >>> timingOut $ [1,2,3]^..taking 7 (cycled traverse)
--   [1,2,3,1,2,3,1]
--   
-- --
--   cycled :: Fold1 s a -> Fold1 s a
--   
cycled :: Apply f => LensLike f s t a b -> LensLike f s t a b -- | Obtain a Fold by taking elements from another Fold, -- Lens, Iso, Getter or Traversal while a -- predicate holds. -- --
--   takeWhile p ≡ toListOf (takingWhile p folded)
--   
-- --
--   >>> timingOut $ toListOf (takingWhile (<=3) folded) [1..]
--   [1,2,3]
--   
-- --
--   takingWhile :: (a -> Bool) -> Fold s a                         -> Fold s a
--   takingWhile :: (a -> Bool) -> Getter s a                       -> Fold s a
--   takingWhile :: (a -> Bool) -> Traversal' s a                   -> Fold s a -- * See note below
--   takingWhile :: (a -> Bool) -> Lens' s a                        -> Fold s a -- * See note below
--   takingWhile :: (a -> Bool) -> Prism' s a                       -> Fold s a -- * See note below
--   takingWhile :: (a -> Bool) -> Iso' s a                         -> Fold s a -- * See note below
--   takingWhile :: (a -> Bool) -> IndexedTraversal' i s a          -> IndexedFold i s a -- * See note below
--   takingWhile :: (a -> Bool) -> IndexedLens' i s a               -> IndexedFold i s a -- * See note below
--   takingWhile :: (a -> Bool) -> IndexedFold i s a                -> IndexedFold i s a
--   takingWhile :: (a -> Bool) -> IndexedGetter i s a              -> IndexedFold i s a
--   
-- -- Note: When applied to a Traversal, takingWhile -- yields something that can be used as if it were a Traversal, -- but which is not a Traversal per the laws, unless you are -- careful to ensure that you do not invalidate the predicate when -- writing back through it. takingWhile :: (Conjoined p, Applicative f) => a -> Bool -> Over p TakingWhile p f a a s t a a -> Over p f s t a a -- | Obtain a Fold by dropping elements from another Fold, -- Lens, Iso, Getter or Traversal while a -- predicate holds. -- --
--   dropWhile p ≡ toListOf (droppingWhile p folded)
--   
-- --
--   >>> toListOf (droppingWhile (<=3) folded) [1..6]
--   [4,5,6]
--   
-- --
--   >>> toListOf (droppingWhile (<=3) folded) [1,6,1]
--   [6,1]
--   
-- --
--   droppingWhile :: (a -> Bool) -> Fold s a                         -> Fold s a
--   droppingWhile :: (a -> Bool) -> Getter s a                       -> Fold s a
--   droppingWhile :: (a -> Bool) -> Traversal' s a                   -> Fold s a                -- see notes
--   droppingWhile :: (a -> Bool) -> Lens' s a                        -> Fold s a                -- see notes
--   droppingWhile :: (a -> Bool) -> Prism' s a                       -> Fold s a                -- see notes
--   droppingWhile :: (a -> Bool) -> Iso' s a                         -> Fold s a                -- see notes
--   
-- --
--   droppingWhile :: (a -> Bool) -> IndexPreservingTraversal' s a    -> IndexPreservingFold s a -- see notes
--   droppingWhile :: (a -> Bool) -> IndexPreservingLens' s a         -> IndexPreservingFold s a -- see notes
--   droppingWhile :: (a -> Bool) -> IndexPreservingGetter s a        -> IndexPreservingFold s a
--   droppingWhile :: (a -> Bool) -> IndexPreservingFold s a          -> IndexPreservingFold s a
--   
-- --
--   droppingWhile :: (a -> Bool) -> IndexedTraversal' i s a          -> IndexedFold i s a       -- see notes
--   droppingWhile :: (a -> Bool) -> IndexedLens' i s a               -> IndexedFold i s a       -- see notes
--   droppingWhile :: (a -> Bool) -> IndexedGetter i s a              -> IndexedFold i s a
--   droppingWhile :: (a -> Bool) -> IndexedFold i s a                -> IndexedFold i s a
--   
-- -- Note: Many uses of this combinator will yield something that meets the -- types, but not the laws of a valid Traversal or -- IndexedTraversal. The Traversal and -- IndexedTraversal laws are only satisfied if the new values you -- assign to the first target also does not pass the predicate! Otherwise -- subsequent traversals will visit fewer elements and Traversal -- fusion is not sound. -- -- So for any traversal t and predicate p, -- droppingWhile p t may not be lawful, but -- (dropping 1 . droppingWhile p) t is. For -- example: -- --
--   >>> let l  :: Traversal' [Int] Int; l  = droppingWhile (<= 1) traverse
--   
--   >>> let l' :: Traversal' [Int] Int; l' = dropping 1 l
--   
-- -- l is not a lawful setter because over l f . -- over l g ≢ over l (f . g): -- --
--   >>> [1,2,3] & l .~ 0 & l .~ 4
--   [1,0,0]
--   
--   >>> [1,2,3] & l .~ 4
--   [1,4,4]
--   
-- -- l' on the other hand behaves lawfully: -- --
--   >>> [1,2,3] & l' .~ 0 & l' .~ 4
--   [1,2,4]
--   
--   >>> [1,2,3] & l' .~ 4
--   [1,2,4]
--   
droppingWhile :: (Conjoined p, Profunctor q, Applicative f) => a -> Bool -> Optical p q Compose State Bool f s t a a -> Optical p q f s t a a -- | Map each part of a structure viewed through a Lens, -- Getter, Fold or Traversal to a monoid and combine -- the results. -- --
--   >>> foldMapOf (folded . both . _Just) Sum [(Just 21, Just 21)]
--   Sum {getSum = 42}
--   
-- --
--   foldMap = foldMapOf folded
--   
-- --
--   foldMapOfviews
--   ifoldMapOf l = foldMapOf l . Indexed
--   
-- --
--   foldMapOf ::                Getter s a      -> (a -> r) -> s -> r
--   foldMapOf :: Monoid r    => Fold s a        -> (a -> r) -> s -> r
--   foldMapOf :: Semigroup r => Fold1 s a       -> (a -> r) -> s -> r
--   foldMapOf ::                Lens' s a       -> (a -> r) -> s -> r
--   foldMapOf ::                Iso' s a        -> (a -> r) -> s -> r
--   foldMapOf :: Monoid r    => Traversal' s a  -> (a -> r) -> s -> r
--   foldMapOf :: Semigroup r => Traversal1' s a -> (a -> r) -> s -> r
--   foldMapOf :: Monoid r    => Prism' s a      -> (a -> r) -> s -> r
--   
-- --
--   foldMapOf :: Getting r s a -> (a -> r) -> s -> r
--   
foldMapOf :: () => Getting r s a -> a -> r -> s -> r -- | Fold a value using a specified Fold and Monoid -- operations. This is like foldMapBy where the Foldable -- instance can be manually specified. -- --
--   foldMapByOf foldedfoldMapBy
--   
-- --
--   foldMapByOf :: Getter s a     -> (r -> r -> r) -> r -> (a -> r) -> s -> r
--   foldMapByOf :: Fold s a       -> (r -> r -> r) -> r -> (a -> r) -> s -> r
--   foldMapByOf :: Traversal' s a -> (r -> r -> r) -> r -> (a -> r) -> s -> r
--   foldMapByOf :: Lens' s a      -> (r -> r -> r) -> r -> (a -> r) -> s -> r
--   foldMapByOf :: Iso' s a       -> (r -> r -> r) -> r -> (a -> r) -> s -> r
--   
-- --
--   >>> foldMapByOf both (+) 0 length ("hello","world")
--   10
--   
foldMapByOf :: () => Fold s a -> r -> r -> r -> r -> a -> r -> s -> r -- | Combine the elements of a structure viewed through a Lens, -- Getter, Fold or Traversal using a monoid. -- --
--   >>> foldOf (folded.folded) [[Sum 1,Sum 4],[Sum 8, Sum 8],[Sum 21]]
--   Sum {getSum = 42}
--   
-- --
--   fold = foldOf folded
--   
-- --
--   foldOfview
--   
-- --
--   foldOf ::             Getter s m     -> s -> m
--   foldOf :: Monoid m => Fold s m       -> s -> m
--   foldOf ::             Lens' s m      -> s -> m
--   foldOf ::             Iso' s m       -> s -> m
--   foldOf :: Monoid m => Traversal' s m -> s -> m
--   foldOf :: Monoid m => Prism' s m     -> s -> m
--   
foldOf :: () => Getting a s a -> s -> a -- | Fold a value using a specified Fold and Monoid -- operations. This is like foldBy where the Foldable -- instance can be manually specified. -- --
--   foldByOf foldedfoldBy
--   
-- --
--   foldByOf :: Getter s a     -> (a -> a -> a) -> a -> s -> a
--   foldByOf :: Fold s a       -> (a -> a -> a) -> a -> s -> a
--   foldByOf :: Lens' s a      -> (a -> a -> a) -> a -> s -> a
--   foldByOf :: Traversal' s a -> (a -> a -> a) -> a -> s -> a
--   foldByOf :: Iso' s a       -> (a -> a -> a) -> a -> s -> a
--   
-- --
--   >>> foldByOf both (++) [] ("hello","world")
--   "helloworld"
--   
foldByOf :: () => Fold s a -> a -> a -> a -> a -> s -> a -- | Right-associative fold of parts of a structure that are viewed through -- a Lens, Getter, Fold or Traversal. -- --
--   foldrfoldrOf folded
--   
-- --
--   foldrOf :: Getter s a     -> (a -> r -> r) -> r -> s -> r
--   foldrOf :: Fold s a       -> (a -> r -> r) -> r -> s -> r
--   foldrOf :: Lens' s a      -> (a -> r -> r) -> r -> s -> r
--   foldrOf :: Iso' s a       -> (a -> r -> r) -> r -> s -> r
--   foldrOf :: Traversal' s a -> (a -> r -> r) -> r -> s -> r
--   foldrOf :: Prism' s a     -> (a -> r -> r) -> r -> s -> r
--   
-- --
--   ifoldrOf l ≡ foldrOf l . Indexed
--   
-- --
--   foldrOf :: Getting (Endo r) s a -> (a -> r -> r) -> r -> s -> r
--   
foldrOf :: () => Getting Endo r s a -> a -> r -> r -> r -> s -> r -- | Strictly fold right over the elements of a structure. -- --
--   foldr'foldrOf' folded
--   
-- --
--   foldrOf' :: Getter s a     -> (a -> r -> r) -> r -> s -> r
--   foldrOf' :: Fold s a       -> (a -> r -> r) -> r -> s -> r
--   foldrOf' :: Iso' s a       -> (a -> r -> r) -> r -> s -> r
--   foldrOf' :: Lens' s a      -> (a -> r -> r) -> r -> s -> r
--   foldrOf' :: Traversal' s a -> (a -> r -> r) -> r -> s -> r
--   
foldrOf' :: () => Getting Dual Endo Endo r s a -> a -> r -> r -> r -> s -> r -- | Monadic fold over the elements of a structure, associating to the -- right, i.e. from right to left. -- --
--   foldrMfoldrMOf folded
--   
-- --
--   foldrMOf :: Monad m => Getter s a     -> (a -> r -> m r) -> r -> s -> m r
--   foldrMOf :: Monad m => Fold s a       -> (a -> r -> m r) -> r -> s -> m r
--   foldrMOf :: Monad m => Iso' s a       -> (a -> r -> m r) -> r -> s -> m r
--   foldrMOf :: Monad m => Lens' s a      -> (a -> r -> m r) -> r -> s -> m r
--   foldrMOf :: Monad m => Traversal' s a -> (a -> r -> m r) -> r -> s -> m r
--   
foldrMOf :: Monad m => Getting Dual Endo r -> m r s a -> a -> r -> m r -> r -> s -> m r -- | Fold over the elements of a structure, associating to the left, but -- strictly. -- --
--   foldl'foldlOf' folded
--   
-- --
--   foldlOf' :: Getter s a     -> (r -> a -> r) -> r -> s -> r
--   foldlOf' :: Fold s a       -> (r -> a -> r) -> r -> s -> r
--   foldlOf' :: Iso' s a       -> (r -> a -> r) -> r -> s -> r
--   foldlOf' :: Lens' s a      -> (r -> a -> r) -> r -> s -> r
--   foldlOf' :: Traversal' s a -> (r -> a -> r) -> r -> s -> r
--   
foldlOf' :: () => Getting Endo Endo r s a -> r -> a -> r -> r -> s -> r -- | Monadic fold over the elements of a structure, associating to the -- left, i.e. from left to right. -- --
--   foldlMfoldlMOf folded
--   
-- --
--   foldlMOf :: Monad m => Getter s a     -> (r -> a -> m r) -> r -> s -> m r
--   foldlMOf :: Monad m => Fold s a       -> (r -> a -> m r) -> r -> s -> m r
--   foldlMOf :: Monad m => Iso' s a       -> (r -> a -> m r) -> r -> s -> m r
--   foldlMOf :: Monad m => Lens' s a      -> (r -> a -> m r) -> r -> s -> m r
--   foldlMOf :: Monad m => Traversal' s a -> (r -> a -> m r) -> r -> s -> m r
--   
foldlMOf :: Monad m => Getting Endo r -> m r s a -> r -> a -> m r -> r -> s -> m r -- | Extract a list of the targets of a Fold. See also (^..). -- --
--   toListtoListOf folded
--   (^..) ≡ flip toListOf
--   
toListOf :: () => Getting Endo [a] s a -> s -> [a] -- | Extract a NonEmpty of the targets of Fold1. -- --
--   >>> toNonEmptyOf both1 ("hello", "world")
--   "hello" :| ["world"]
--   
-- --
--   toNonEmptyOf :: Getter s a      -> s -> NonEmpty a
--   toNonEmptyOf :: Fold1 s a       -> s -> NonEmpty a
--   toNonEmptyOf :: Lens' s a       -> s -> NonEmpty a
--   toNonEmptyOf :: Iso' s a        -> s -> NonEmpty a
--   toNonEmptyOf :: Traversal1' s a -> s -> NonEmpty a
--   toNonEmptyOf :: Prism' s a      -> s -> NonEmpty a
--   
toNonEmptyOf :: () => Getting NonEmptyDList a s a -> s -> NonEmpty a -- | Returns True if any target of a Fold satisfies a -- predicate. -- --
--   >>> anyOf both (=='x') ('x','y')
--   True
--   
--   >>> import Data.Data.Lens
--   
--   >>> anyOf biplate (== "world") (((),2::Int),"hello",("world",11::Int))
--   True
--   
-- --
--   anyanyOf folded
--   
-- --
--   ianyOf l ≡ anyOf l . Indexed
--   
-- --
--   anyOf :: Getter s a     -> (a -> Bool) -> s -> Bool
--   anyOf :: Fold s a       -> (a -> Bool) -> s -> Bool
--   anyOf :: Lens' s a      -> (a -> Bool) -> s -> Bool
--   anyOf :: Iso' s a       -> (a -> Bool) -> s -> Bool
--   anyOf :: Traversal' s a -> (a -> Bool) -> s -> Bool
--   anyOf :: Prism' s a     -> (a -> Bool) -> s -> Bool
--   
anyOf :: () => Getting Any s a -> a -> Bool -> s -> Bool -- | Returns True if every target of a Fold satisfies a -- predicate. -- --
--   >>> allOf both (>=3) (4,5)
--   True
--   
--   >>> allOf folded (>=2) [1..10]
--   False
--   
-- --
--   allallOf folded
--   
-- --
--   iallOf l = allOf l . Indexed
--   
-- --
--   allOf :: Getter s a     -> (a -> Bool) -> s -> Bool
--   allOf :: Fold s a       -> (a -> Bool) -> s -> Bool
--   allOf :: Lens' s a      -> (a -> Bool) -> s -> Bool
--   allOf :: Iso' s a       -> (a -> Bool) -> s -> Bool
--   allOf :: Traversal' s a -> (a -> Bool) -> s -> Bool
--   allOf :: Prism' s a     -> (a -> Bool) -> s -> Bool
--   
allOf :: () => Getting All s a -> a -> Bool -> s -> Bool -- | Returns True only if no targets of a Fold satisfy a -- predicate. -- --
--   >>> noneOf each (is _Nothing) (Just 3, Just 4, Just 5)
--   True
--   
--   >>> noneOf (folded.folded) (<10) [[13,99,20],[3,71,42]]
--   False
--   
-- --
--   inoneOf l = noneOf l . Indexed
--   
-- --
--   noneOf :: Getter s a     -> (a -> Bool) -> s -> Bool
--   noneOf :: Fold s a       -> (a -> Bool) -> s -> Bool
--   noneOf :: Lens' s a      -> (a -> Bool) -> s -> Bool
--   noneOf :: Iso' s a       -> (a -> Bool) -> s -> Bool
--   noneOf :: Traversal' s a -> (a -> Bool) -> s -> Bool
--   noneOf :: Prism' s a     -> (a -> Bool) -> s -> Bool
--   
noneOf :: () => Getting Any s a -> a -> Bool -> s -> Bool -- | Returns True if every target of a Fold is True. -- --
--   >>> andOf both (True,False)
--   False
--   
--   >>> andOf both (True,True)
--   True
--   
-- --
--   andandOf folded
--   
-- --
--   andOf :: Getter s Bool     -> s -> Bool
--   andOf :: Fold s Bool       -> s -> Bool
--   andOf :: Lens' s Bool      -> s -> Bool
--   andOf :: Iso' s Bool       -> s -> Bool
--   andOf :: Traversal' s Bool -> s -> Bool
--   andOf :: Prism' s Bool     -> s -> Bool
--   
andOf :: () => Getting All s Bool -> s -> Bool -- | Returns True if any target of a Fold is True. -- --
--   >>> orOf both (True,False)
--   True
--   
--   >>> orOf both (False,False)
--   False
--   
-- --
--   ororOf folded
--   
-- --
--   orOf :: Getter s Bool     -> s -> Bool
--   orOf :: Fold s Bool       -> s -> Bool
--   orOf :: Lens' s Bool      -> s -> Bool
--   orOf :: Iso' s Bool       -> s -> Bool
--   orOf :: Traversal' s Bool -> s -> Bool
--   orOf :: Prism' s Bool     -> s -> Bool
--   
orOf :: () => Getting Any s Bool -> s -> Bool -- | Calculate the Product of every number targeted by a -- Fold. -- --
--   >>> productOf both (4,5)
--   20
--   
--   >>> productOf folded [1,2,3,4,5]
--   120
--   
-- --
--   productproductOf folded
--   
-- -- This operation may be more strict than you would expect. If you want a -- lazier version use ala Product . -- foldMapOf -- --
--   productOf :: Num a => Getter s a     -> s -> a
--   productOf :: Num a => Fold s a       -> s -> a
--   productOf :: Num a => Lens' s a      -> s -> a
--   productOf :: Num a => Iso' s a       -> s -> a
--   productOf :: Num a => Traversal' s a -> s -> a
--   productOf :: Num a => Prism' s a     -> s -> a
--   
productOf :: Num a => Getting Endo Endo a s a -> s -> a -- | Calculate the Sum of every number targeted by a Fold. -- --
--   >>> sumOf both (5,6)
--   11
--   
--   >>> sumOf folded [1,2,3,4]
--   10
--   
--   >>> sumOf (folded.both) [(1,2),(3,4)]
--   10
--   
--   >>> import Data.Data.Lens
--   
--   >>> sumOf biplate [(1::Int,[]),(2,[(3::Int,4::Int)])] :: Int
--   10
--   
-- --
--   sumsumOf folded
--   
-- -- This operation may be more strict than you would expect. If you want a -- lazier version use ala Sum . -- foldMapOf -- --
--   sumOf _1 :: Num a => (a, b) -> a
--   sumOf (folded . _1) :: (Foldable f, Num a) => f (a, b) -> a
--   
-- --
--   sumOf :: Num a => Getter s a     -> s -> a
--   sumOf :: Num a => Fold s a       -> s -> a
--   sumOf :: Num a => Lens' s a      -> s -> a
--   sumOf :: Num a => Iso' s a       -> s -> a
--   sumOf :: Num a => Traversal' s a -> s -> a
--   sumOf :: Num a => Prism' s a     -> s -> a
--   
sumOf :: Num a => Getting Endo Endo a s a -> s -> a -- | Traverse over all of the targets of a Fold (or Getter), -- computing an Applicative (or Functor)-based answer, but -- unlike traverseOf do not construct a new structure. -- traverseOf_ generalizes traverse_ to work over any -- Fold. -- -- When passed a Getter, traverseOf_ can work over any -- Functor, but when passed a Fold, traverseOf_ -- requires an Applicative. -- --
--   >>> traverseOf_ both putStrLn ("hello","world")
--   hello
--   world
--   
-- --
--   traverse_traverseOf_ folded
--   
-- --
--   traverseOf_ _2 :: Functor f => (c -> f r) -> (d, c) -> f ()
--   traverseOf_ _Left :: Applicative f => (a -> f b) -> Either a c -> f ()
--   
-- --
--   itraverseOf_ l ≡ traverseOf_ l . Indexed
--   
-- -- The rather specific signature of traverseOf_ allows it to be -- used as if the signature was any of: -- --
--   traverseOf_ :: Functor f     => Getter s a     -> (a -> f r) -> s -> f ()
--   traverseOf_ :: Applicative f => Fold s a       -> (a -> f r) -> s -> f ()
--   traverseOf_ :: Functor f     => Lens' s a      -> (a -> f r) -> s -> f ()
--   traverseOf_ :: Functor f     => Iso' s a       -> (a -> f r) -> s -> f ()
--   traverseOf_ :: Applicative f => Traversal' s a -> (a -> f r) -> s -> f ()
--   traverseOf_ :: Applicative f => Prism' s a     -> (a -> f r) -> s -> f ()
--   
traverseOf_ :: Functor f => Getting Traversed r f s a -> a -> f r -> s -> f () -- | Traverse over all of the targets of a Fold (or Getter), -- computing an Applicative (or Functor)-based answer, but -- unlike forOf do not construct a new structure. forOf_ -- generalizes for_ to work over any Fold. -- -- When passed a Getter, forOf_ can work over any -- Functor, but when passed a Fold, forOf_ requires -- an Applicative. -- --
--   for_forOf_ folded
--   
-- --
--   >>> forOf_ both ("hello","world") putStrLn
--   hello
--   world
--   
-- -- The rather specific signature of forOf_ allows it to be used as -- if the signature was any of: -- --
--   iforOf_ l s ≡ forOf_ l s . Indexed
--   
-- --
--   forOf_ :: Functor f     => Getter s a     -> s -> (a -> f r) -> f ()
--   forOf_ :: Applicative f => Fold s a       -> s -> (a -> f r) -> f ()
--   forOf_ :: Functor f     => Lens' s a      -> s -> (a -> f r) -> f ()
--   forOf_ :: Functor f     => Iso' s a       -> s -> (a -> f r) -> f ()
--   forOf_ :: Applicative f => Traversal' s a -> s -> (a -> f r) -> f ()
--   forOf_ :: Applicative f => Prism' s a     -> s -> (a -> f r) -> f ()
--   
forOf_ :: Functor f => Getting Traversed r f s a -> s -> a -> f r -> f () -- | Evaluate each action in observed by a Fold on a structure from -- left to right, ignoring the results. -- --
--   sequenceA_sequenceAOf_ folded
--   
-- --
--   >>> sequenceAOf_ both (putStrLn "hello",putStrLn "world")
--   hello
--   world
--   
-- --
--   sequenceAOf_ :: Functor f     => Getter s (f a)     -> s -> f ()
--   sequenceAOf_ :: Applicative f => Fold s (f a)       -> s -> f ()
--   sequenceAOf_ :: Functor f     => Lens' s (f a)      -> s -> f ()
--   sequenceAOf_ :: Functor f     => Iso' s (f a)       -> s -> f ()
--   sequenceAOf_ :: Applicative f => Traversal' s (f a) -> s -> f ()
--   sequenceAOf_ :: Applicative f => Prism' s (f a)     -> s -> f ()
--   
sequenceAOf_ :: Functor f => Getting Traversed a f s f a -> s -> f () -- | The sum of a collection of actions, generalizing concatOf. -- --
--   >>> asumOf both ("hello","world")
--   "helloworld"
--   
-- --
--   >>> asumOf each (Nothing, Just "hello", Nothing)
--   Just "hello"
--   
-- --
--   asumasumOf folded
--   
-- --
--   asumOf :: Alternative f => Getter s (f a)     -> s -> f a
--   asumOf :: Alternative f => Fold s (f a)       -> s -> f a
--   asumOf :: Alternative f => Lens' s (f a)      -> s -> f a
--   asumOf :: Alternative f => Iso' s (f a)       -> s -> f a
--   asumOf :: Alternative f => Traversal' s (f a) -> s -> f a
--   asumOf :: Alternative f => Prism' s (f a)     -> s -> f a
--   
asumOf :: Alternative f => Getting Endo f a s f a -> s -> f a -- | The sum of a collection of actions, generalizing concatOf. -- --
--   >>> msumOf both ("hello","world")
--   "helloworld"
--   
-- --
--   >>> msumOf each (Nothing, Just "hello", Nothing)
--   Just "hello"
--   
-- --
--   msummsumOf folded
--   
-- --
--   msumOf :: MonadPlus m => Getter s (m a)     -> s -> m a
--   msumOf :: MonadPlus m => Fold s (m a)       -> s -> m a
--   msumOf :: MonadPlus m => Lens' s (m a)      -> s -> m a
--   msumOf :: MonadPlus m => Iso' s (m a)       -> s -> m a
--   msumOf :: MonadPlus m => Traversal' s (m a) -> s -> m a
--   msumOf :: MonadPlus m => Prism' s (m a)     -> s -> m a
--   
msumOf :: MonadPlus m => Getting Endo m a s m a -> s -> m a -- | Map a function over all the targets of a Fold of a container -- and concatenate the resulting lists. -- --
--   >>> concatMapOf both (\x -> [x, x + 1]) (1,3)
--   [1,2,3,4]
--   
-- --
--   concatMapconcatMapOf folded
--   
-- --
--   concatMapOf :: Getter s a     -> (a -> [r]) -> s -> [r]
--   concatMapOf :: Fold s a       -> (a -> [r]) -> s -> [r]
--   concatMapOf :: Lens' s a      -> (a -> [r]) -> s -> [r]
--   concatMapOf :: Iso' s a       -> (a -> [r]) -> s -> [r]
--   concatMapOf :: Traversal' s a -> (a -> [r]) -> s -> [r]
--   
concatMapOf :: () => Getting [r] s a -> a -> [r] -> s -> [r] -- | Does the element occur anywhere within a given Fold of the -- structure? -- --
--   >>> elemOf both "hello" ("hello","world")
--   True
--   
-- --
--   elemelemOf folded
--   
-- --
--   elemOf :: Eq a => Getter s a     -> a -> s -> Bool
--   elemOf :: Eq a => Fold s a       -> a -> s -> Bool
--   elemOf :: Eq a => Lens' s a      -> a -> s -> Bool
--   elemOf :: Eq a => Iso' s a       -> a -> s -> Bool
--   elemOf :: Eq a => Traversal' s a -> a -> s -> Bool
--   elemOf :: Eq a => Prism' s a     -> a -> s -> Bool
--   
elemOf :: Eq a => Getting Any s a -> a -> s -> Bool -- | Does the element not occur anywhere within a given Fold of the -- structure? -- --
--   >>> notElemOf each 'd' ('a','b','c')
--   True
--   
-- --
--   >>> notElemOf each 'a' ('a','b','c')
--   False
--   
-- --
--   notElemnotElemOf folded
--   
-- --
--   notElemOf :: Eq a => Getter s a     -> a -> s -> Bool
--   notElemOf :: Eq a => Fold s a       -> a -> s -> Bool
--   notElemOf :: Eq a => Iso' s a       -> a -> s -> Bool
--   notElemOf :: Eq a => Lens' s a      -> a -> s -> Bool
--   notElemOf :: Eq a => Traversal' s a -> a -> s -> Bool
--   notElemOf :: Eq a => Prism' s a     -> a -> s -> Bool
--   
notElemOf :: Eq a => Getting All s a -> a -> s -> Bool -- | Calculate the number of targets there are for a Fold in a given -- container. -- -- Note: This can be rather inefficient for large containers and -- just like length, this will not terminate for infinite folds. -- --
--   lengthlengthOf folded
--   
-- --
--   >>> lengthOf _1 ("hello",())
--   1
--   
-- --
--   >>> lengthOf traverse [1..10]
--   10
--   
-- --
--   >>> lengthOf (traverse.traverse) [[1,2],[3,4],[5,6]]
--   6
--   
-- --
--   lengthOf (folded . folded) :: (Foldable f, Foldable g) => f (g a) -> Int
--   
-- --
--   lengthOf :: Getter s a     -> s -> Int
--   lengthOf :: Fold s a       -> s -> Int
--   lengthOf :: Lens' s a      -> s -> Int
--   lengthOf :: Iso' s a       -> s -> Int
--   lengthOf :: Traversal' s a -> s -> Int
--   
lengthOf :: () => Getting Endo Endo Int s a -> s -> Int -- | Returns True if this Fold or Traversal has no -- targets in the given container. -- -- Note: nullOf on a valid Iso, Lens or -- Getter should always return False. -- --
--   nullnullOf folded
--   
-- -- This may be rather inefficient compared to the null check of -- many containers. -- --
--   >>> nullOf _1 (1,2)
--   False
--   
-- --
--   >>> nullOf ignored ()
--   True
--   
-- --
--   >>> nullOf traverse []
--   True
--   
-- --
--   >>> nullOf (element 20) [1..10]
--   True
--   
-- --
--   nullOf (folded . _1 . folded) :: (Foldable f, Foldable g) => f (g a, b) -> Bool
--   
-- --
--   nullOf :: Getter s a     -> s -> Bool
--   nullOf :: Fold s a       -> s -> Bool
--   nullOf :: Iso' s a       -> s -> Bool
--   nullOf :: Lens' s a      -> s -> Bool
--   nullOf :: Traversal' s a -> s -> Bool
--   
nullOf :: () => Getting All s a -> s -> Bool -- | Returns True if this Fold or Traversal has any -- targets in the given container. -- -- A more "conversational" alias for this combinator is has. -- -- Note: notNullOf on a valid Iso, Lens or -- Getter should always return True. -- --
--   not . nullnotNullOf folded
--   
-- -- This may be rather inefficient compared to the not . -- null check of many containers. -- --
--   >>> notNullOf _1 (1,2)
--   True
--   
-- --
--   >>> notNullOf traverse [1..10]
--   True
--   
-- --
--   >>> notNullOf folded []
--   False
--   
-- --
--   >>> notNullOf (element 20) [1..10]
--   False
--   
-- --
--   notNullOf (folded . _1 . folded) :: (Foldable f, Foldable g) => f (g a, b) -> Bool
--   
-- --
--   notNullOf :: Getter s a     -> s -> Bool
--   notNullOf :: Fold s a       -> s -> Bool
--   notNullOf :: Iso' s a       -> s -> Bool
--   notNullOf :: Lens' s a      -> s -> Bool
--   notNullOf :: Traversal' s a -> s -> Bool
--   
notNullOf :: () => Getting Any s a -> s -> Bool -- | Retrieve the First entry of a Fold or Traversal -- or retrieve Just the result from a Getter or -- Lens. -- -- The answer is computed in a manner that leaks space less than -- ala First . foldMapOf and gives -- you back access to the outermost Just constructor more quickly, -- but may have worse constant factors. -- -- Note: this could been named headOf. -- --
--   >>> firstOf traverse [1..10]
--   Just 1
--   
-- --
--   >>> firstOf both (1,2)
--   Just 1
--   
-- --
--   >>> firstOf ignored ()
--   Nothing
--   
-- --
--   firstOf :: Getter s a     -> s -> Maybe a
--   firstOf :: Fold s a       -> s -> Maybe a
--   firstOf :: Lens' s a      -> s -> Maybe a
--   firstOf :: Iso' s a       -> s -> Maybe a
--   firstOf :: Traversal' s a -> s -> Maybe a
--   
firstOf :: () => Getting Leftmost a s a -> s -> Maybe a -- | Retrieve the Last entry of a Fold or Traversal or -- retrieve Just the result from a Getter or Lens. -- -- The answer is computed in a manner that leaks space less than -- ala Last . foldMapOf and gives -- you back access to the outermost Just constructor more quickly, -- but may have worse constant factors. -- --
--   >>> lastOf traverse [1..10]
--   Just 10
--   
-- --
--   >>> lastOf both (1,2)
--   Just 2
--   
-- --
--   >>> lastOf ignored ()
--   Nothing
--   
-- --
--   lastOf :: Getter s a     -> s -> Maybe a
--   lastOf :: Fold s a       -> s -> Maybe a
--   lastOf :: Lens' s a      -> s -> Maybe a
--   lastOf :: Iso' s a       -> s -> Maybe a
--   lastOf :: Traversal' s a -> s -> Maybe a
--   
lastOf :: () => Getting Rightmost a s a -> s -> Maybe a -- | Obtain the maximum element (if any) targeted by a Fold or -- Traversal safely. -- -- Note: maximumOf on a valid Iso, Lens or -- Getter will always return Just a value. -- --
--   >>> maximumOf traverse [1..10]
--   Just 10
--   
-- --
--   >>> maximumOf traverse []
--   Nothing
--   
-- --
--   >>> maximumOf (folded.filtered even) [1,4,3,6,7,9,2]
--   Just 6
--   
-- --
--   maximumfromMaybe (error "empty") . maximumOf folded
--   
-- -- In the interest of efficiency, This operation has semantics more -- strict than strictly necessary. rmap getMax -- (foldMapOf l Max) has lazier semantics but could -- leak memory. -- --
--   maximumOf :: Ord a => Getter s a     -> s -> Maybe a
--   maximumOf :: Ord a => Fold s a       -> s -> Maybe a
--   maximumOf :: Ord a => Iso' s a       -> s -> Maybe a
--   maximumOf :: Ord a => Lens' s a      -> s -> Maybe a
--   maximumOf :: Ord a => Traversal' s a -> s -> Maybe a
--   
maximumOf :: Ord a => Getting Endo Endo Maybe a s a -> s -> Maybe a -- | Obtain the minimum element (if any) targeted by a Fold or -- Traversal safely. -- -- Note: minimumOf on a valid Iso, Lens or -- Getter will always return Just a value. -- --
--   >>> minimumOf traverse [1..10]
--   Just 1
--   
-- --
--   >>> minimumOf traverse []
--   Nothing
--   
-- --
--   >>> minimumOf (folded.filtered even) [1,4,3,6,7,9,2]
--   Just 2
--   
-- --
--   minimumfromMaybe (error "empty") . minimumOf folded
--   
-- -- In the interest of efficiency, This operation has semantics more -- strict than strictly necessary. rmap getMin -- (foldMapOf l Min) has lazier semantics but could -- leak memory. -- --
--   minimumOf :: Ord a => Getter s a     -> s -> Maybe a
--   minimumOf :: Ord a => Fold s a       -> s -> Maybe a
--   minimumOf :: Ord a => Iso' s a       -> s -> Maybe a
--   minimumOf :: Ord a => Lens' s a      -> s -> Maybe a
--   minimumOf :: Ord a => Traversal' s a -> s -> Maybe a
--   
minimumOf :: Ord a => Getting Endo Endo Maybe a s a -> s -> Maybe a -- | Obtain the maximum element (if any) targeted by a Fold, -- Traversal, Lens, Iso, or Getter according -- to a user supplied Ordering. -- --
--   >>> maximumByOf traverse (compare `on` length) ["mustard","relish","ham"]
--   Just "mustard"
--   
-- -- In the interest of efficiency, This operation has semantics more -- strict than strictly necessary. -- --
--   maximumBy cmp ≡ fromMaybe (error "empty") . maximumByOf folded cmp
--   
-- --
--   maximumByOf :: Getter s a     -> (a -> a -> Ordering) -> s -> Maybe a
--   maximumByOf :: Fold s a       -> (a -> a -> Ordering) -> s -> Maybe a
--   maximumByOf :: Iso' s a       -> (a -> a -> Ordering) -> s -> Maybe a
--   maximumByOf :: Lens' s a      -> (a -> a -> Ordering) -> s -> Maybe a
--   maximumByOf :: Traversal' s a -> (a -> a -> Ordering) -> s -> Maybe a
--   
maximumByOf :: () => Getting Endo Endo Maybe a s a -> a -> a -> Ordering -> s -> Maybe a -- | Obtain the minimum element (if any) targeted by a Fold, -- Traversal, Lens, Iso or Getter according -- to a user supplied Ordering. -- -- In the interest of efficiency, This operation has semantics more -- strict than strictly necessary. -- --
--   >>> minimumByOf traverse (compare `on` length) ["mustard","relish","ham"]
--   Just "ham"
--   
-- --
--   minimumBy cmp ≡ fromMaybe (error "empty") . minimumByOf folded cmp
--   
-- --
--   minimumByOf :: Getter s a     -> (a -> a -> Ordering) -> s -> Maybe a
--   minimumByOf :: Fold s a       -> (a -> a -> Ordering) -> s -> Maybe a
--   minimumByOf :: Iso' s a       -> (a -> a -> Ordering) -> s -> Maybe a
--   minimumByOf :: Lens' s a      -> (a -> a -> Ordering) -> s -> Maybe a
--   minimumByOf :: Traversal' s a -> (a -> a -> Ordering) -> s -> Maybe a
--   
minimumByOf :: () => Getting Endo Endo Maybe a s a -> a -> a -> Ordering -> s -> Maybe a -- | The findOf function takes a Lens (or Getter, -- Iso, Fold, or Traversal), a predicate and a -- structure and returns the leftmost element of the structure matching -- the predicate, or Nothing if there is no such element. -- --
--   >>> findOf each even (1,3,4,6)
--   Just 4
--   
-- --
--   >>> findOf folded even [1,3,5,7]
--   Nothing
--   
-- --
--   findOf :: Getter s a     -> (a -> Bool) -> s -> Maybe a
--   findOf :: Fold s a       -> (a -> Bool) -> s -> Maybe a
--   findOf :: Iso' s a       -> (a -> Bool) -> s -> Maybe a
--   findOf :: Lens' s a      -> (a -> Bool) -> s -> Maybe a
--   findOf :: Traversal' s a -> (a -> Bool) -> s -> Maybe a
--   
-- --
--   findfindOf folded
--   ifindOf l ≡ findOf l . Indexed
--   
-- -- A simpler version that didn't permit indexing, would be: -- --
--   findOf :: Getting (Endo (Maybe a)) s a -> (a -> Bool) -> s -> Maybe a
--   findOf l p = foldrOf l (a y -> if p a then Just a else y) Nothing
--   
findOf :: () => Getting Endo Maybe a s a -> a -> Bool -> s -> Maybe a -- | The findMOf function takes a Lens (or Getter, -- Iso, Fold, or Traversal), a monadic predicate and -- a structure and returns in the monad the leftmost element of the -- structure matching the predicate, or Nothing if there is no -- such element. -- --
--   >>> findMOf each ( \x -> print ("Checking " ++ show x) >> return (even x)) (1,3,4,6)
--   "Checking 1"
--   "Checking 3"
--   "Checking 4"
--   Just 4
--   
-- --
--   >>> findMOf each ( \x -> print ("Checking " ++ show x) >> return (even x)) (1,3,5,7)
--   "Checking 1"
--   "Checking 3"
--   "Checking 5"
--   "Checking 7"
--   Nothing
--   
-- --
--   findMOf :: (Monad m, Getter s a)     -> (a -> m Bool) -> s -> m (Maybe a)
--   findMOf :: (Monad m, Fold s a)       -> (a -> m Bool) -> s -> m (Maybe a)
--   findMOf :: (Monad m, Iso' s a)       -> (a -> m Bool) -> s -> m (Maybe a)
--   findMOf :: (Monad m, Lens' s a)      -> (a -> m Bool) -> s -> m (Maybe a)
--   findMOf :: (Monad m, Traversal' s a) -> (a -> m Bool) -> s -> m (Maybe a)
--   
-- --
--   findMOf folded :: (Monad m, Foldable f) => (a -> m Bool) -> f a -> m (Maybe a)
--   ifindMOf l ≡ findMOf l . Indexed
--   
-- -- A simpler version that didn't permit indexing, would be: -- --
--   findMOf :: Monad m => Getting (Endo (m (Maybe a))) s a -> (a -> m Bool) -> s -> m (Maybe a)
--   findMOf l p = foldrOf l (a y -> p a >>= x -> if x then return (Just a) else y) $ return Nothing
--   
findMOf :: Monad m => Getting Endo m Maybe a s a -> a -> m Bool -> s -> m Maybe a -- | The lookupOf function takes a Fold (or Getter, -- Traversal, Lens, Iso, etc.), a key, and a -- structure containing key/value pairs. It returns the first value -- corresponding to the given key. This function generalizes -- lookup to work on an arbitrary Fold instead of lists. -- --
--   >>> lookupOf folded 4 [(2, 'a'), (4, 'b'), (4, 'c')]
--   Just 'b'
--   
-- --
--   >>> lookupOf each 2 [(2, 'a'), (4, 'b'), (4, 'c')]
--   Just 'a'
--   
-- --
--   lookupOf :: Eq k => Fold s (k,v) -> k -> s -> Maybe v
--   
lookupOf :: Eq k => Getting Endo Maybe v s (k, v) -> k -> s -> Maybe v module Optic.Getter -- | A Getter describes how to retrieve a single value in a way that -- can be composed with other LensLike constructions. -- -- Unlike a Lens a Getter is read-only. Since a -- Getter cannot be used to write back there are no Lens -- laws that can be applied to it. In fact, it is isomorphic to an -- arbitrary function from (s -> a). -- -- Moreover, a Getter can be used directly as a Fold, since -- it just ignores the Applicative. type Getter s a = forall (f :: * -> *). (Contravariant f, Functor f) => a -> f a -> s -> f s -- | Build an (index-preserving) Getter from an arbitrary Haskell -- function. -- --
--   to f . to g ≡ to (g . f)
--   
-- --
--   a ^. to f ≡ f a
--   
-- --
--   >>> a ^.to f
--   f a
--   
-- --
--   >>> ("hello","world")^.to snd
--   "world"
--   
-- --
--   >>> 5^.to succ
--   6
--   
-- --
--   >>> (0, -5)^._2.to abs
--   5
--   
-- --
--   to :: (s -> a) -> IndexPreservingGetter s a
--   
to :: (Profunctor p, Contravariant f) => s -> a -> Optic' p f s a module Optic.Getting -- | When you see this in a type signature it indicates that you can pass -- the function a Lens, Getter, Traversal, -- Fold, Prism, Iso, or one of the indexed variants, -- and it will just "do the right thing". -- -- Most Getter combinators are able to be used with both a -- Getter or a Fold in limited situations, to do so, they -- need to be monomorphic in what we are going to extract with -- Const. To be compatible with Lens, Traversal and -- Iso we also restricted choices of the irrelevant t and -- b parameters. -- -- If a function accepts a Getting r s a, then when -- r is a Monoid, then you can pass a Fold (or -- Traversal), otherwise you can only pass this a Getter or -- Lens. type Getting r s a = a -> Const r a -> s -> Const r s -- | 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 -- | View a function of the value pointed to by a Getter or -- Lens or the result of folding over the result of mapping the -- targets of a Fold or Traversal. -- --
--   views l f ≡ view (l . to f)
--   
-- --
--   >>> views (to f) g a
--   g (f a)
--   
-- --
--   >>> views _2 length (1,"hello")
--   5
--   
-- -- As views 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: -- --
--   views ::             Getter s a     -> (a -> r) -> s -> r
--   views :: Monoid m => Fold s a       -> (a -> m) -> s -> m
--   views ::             Iso' s a       -> (a -> r) -> s -> r
--   views ::             Lens' s a      -> (a -> r) -> s -> r
--   views :: Monoid m => Traversal' s a -> (a -> m) -> s -> m
--   
-- -- In a more general setting, such as when working with a Monad -- transformer stack you can use: -- --
--   views :: MonadReader s m             => Getter s a     -> (a -> r) -> m r
--   views :: (MonadReader s m, Monoid r) => Fold s a       -> (a -> r) -> m r
--   views :: MonadReader s m             => Iso' s a       -> (a -> r) -> m r
--   views :: MonadReader s m             => Lens' s a      -> (a -> r) -> m r
--   views :: (MonadReader s m, Monoid r) => Traversal' s a -> (a -> r) -> m r
--   
-- --
--   views :: MonadReader s m => Getting r s a -> (a -> r) -> m r
--   
views :: MonadReader s m => LensLike' (Const r :: * -> *) s a -> a -> r -> m r -- | 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 -- | 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 (uses _1 length) ("hello","world")
--   5
--   
-- --
--   uses :: MonadState s m             => Getter s a     -> (a -> r) -> m r
--   uses :: (MonadState s m, Monoid r) => Fold s a       -> (a -> r) -> m r
--   uses :: MonadState s m             => Lens' s a      -> (a -> r) -> m r
--   uses :: MonadState s m             => Iso' s a       -> (a -> r) -> m r
--   uses :: (MonadState s m, Monoid r) => Traversal' s a -> (a -> r) -> m r
--   
-- --
--   uses :: MonadState s m => Getting r s t a b -> (a -> r) -> m r
--   
uses :: MonadState s m => LensLike' (Const r :: * -> *) s a -> a -> r -> m r module Optic.Iso -- | Isomorphism families can be composed with another Lens using -- (.) and id. -- -- Since every Iso is both a valid Lens and a valid -- Prism, the laws for those types imply the following laws for an -- Iso f: -- --
--   f . from f ≡ id
--   from f . f ≡ id
--   
-- -- Note: Composition with an Iso is index- and measure- -- preserving. type Iso s t a b = forall (p :: * -> * -> *) (f :: * -> *). (Profunctor p, Functor f) => p a f b -> p s f t -- |
--   type Iso' = Simple Iso
--   
type Iso' s a = Iso s s a a -- | Build a simple isomorphism from a pair of inverse functions. -- --
--   view (iso f g) ≡ f
--   view (from (iso f g)) ≡ g
--   over (iso f g) h ≡ g . h . f
--   over (from (iso f g)) h ≡ f . h . g
--   
iso :: () => s -> a -> b -> t -> Iso s t a b -- | Invert an isomorphism. -- --
--   from (from l) ≡ l
--   
from :: () => AnIso s t a b -> Iso b a t s -- | The opposite of working over a Setter is working -- under an isomorphism. -- --
--   underover . from
--   
-- --
--   under :: Iso s t a b -> (t -> s) -> b -> a
--   
under :: () => AnIso s t a b -> t -> s -> b -> a -- | This isomorphism can be used to convert to or from an instance of -- Enum. -- --
--   >>> LT^.from enum
--   0
--   
-- --
--   >>> 97^.enum :: Char
--   'a'
--   
-- -- Note: this is only an isomorphism from the numeric range actually used -- and it is a bit of a pleasant fiction, since there are questionable -- Enum instances for Double, and Float that exist -- solely for [1.0 .. 4.0] sugar and the instances for those and -- Integer don't cover all values in their range. enum :: Enum a => Iso' Int a -- | The canonical isomorphism for currying and uncurrying a function. -- --
--   curried = iso curry uncurry
--   
-- --
--   >>> (fst^.curried) 3 4
--   3
--   
-- --
--   >>> view curried fst 3 4
--   3
--   
curried :: (Profunctor p, Functor f) => p a -> b -> c f d -> e -> f -> p (a, b) -> c f (d, e) -> f -- | The canonical isomorphism for uncurrying and currying a function. -- --
--   uncurried = iso uncurry curry
--   
-- --
--   uncurried = from curried
--   
-- --
--   >>> ((+)^.uncurried) (1,2)
--   3
--   
uncurried :: (Profunctor p, Functor f) => p (a, b) -> c f (d, e) -> f -> p a -> b -> c f d -> e -> f -- | The isomorphism for flipping a function. -- --
--   >>> ((,)^.flipped) 1 2
--   (2,1)
--   
flipped :: (Profunctor p, Functor f) => p b -> a -> c f b' -> a' -> c' -> p a -> b -> c f a' -> b' -> c' module Optic.Iso.Reversing -- | This class provides a generalized notion of list reversal extended to -- other containers. class Reversing t reversing :: Reversing t => t -> t -- | An Iso between a list, ByteString, Text fragment, -- etc. and its reversal. -- --
--   >>> "live" ^. reversed
--   "evil"
--   
-- --
--   >>> "live" & reversed %~ ('d':)
--   "lived"
--   
reversed :: Reversing a => Iso' a a module Optic.Iso.Strict -- | Ad hoc conversion between "strict" and "lazy" versions of a structure, -- such as Text or ByteString. class Strict lazy strict | lazy -> strict, strict -> lazy strict :: Strict lazy strict => Iso' lazy strict -- | An Iso between the strict variant of a structure and its lazy -- counterpart. -- --
--   lazy = from strict
--   
-- -- See http://hackage.haskell.org/package/strict-base-types for an -- example use. lazy :: Strict lazy strict => Iso' strict lazy module Optic.Lens -- | 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 :: * -> *). Functor f => a -> f b -> s -> f t -- |
--   type Lens' = Simple Lens
--   
type Lens' s a = Lens s s a a -- | Build a Lens from a getter and a setter. -- --
--   lens :: Functor f => (s -> a) -> (s -> b -> t) -> (a -> f b) -> s -> f t
--   
-- --
--   >>> s ^. lens getter setter
--   getter s
--   
-- --
--   >>> s & lens getter setter .~ b
--   setter s b
--   
-- --
--   >>> s & lens getter setter %~ f
--   setter s (f (getter s))
--   
-- --
--   lens :: (s -> a) -> (s -> a -> s) -> Lens' s a
--   
lens :: () => s -> a -> s -> b -> t -> Lens s t a b module Optic.Lens.Contains -- | This class provides a simple Lens that lets you view (and -- modify) information about whether or not a container contains a given -- Index. class Contains m -- |
--   >>> IntSet.fromList [1,2,3,4] ^. contains 3
--   True
--   
-- --
--   >>> IntSet.fromList [1,2,3,4] ^. contains 5
--   False
--   
-- --
--   >>> IntSet.fromList [1,2,3,4] & contains 3 .~ False
--   fromList [1,2,4]
--   
contains :: Contains m => Index m -> Lens' m Bool module Optic.Prism -- | A Prism l is a Traversal that can also be -- turned around with re to obtain a Getter in the opposite -- direction. -- -- There are two laws that a Prism should satisfy: -- -- First, if I re or review a value with a Prism and -- then preview or use (^?), I will get it back: -- --
--   preview l (review l b) ≡ Just b
--   
-- -- Second, if you can extract a value a using a Prism -- l from a value s, then the value s is -- completely described by l and a: -- -- If preview l s ≡ Just a then -- review l a ≡ s -- -- These two laws imply that the Traversal laws hold for every -- Prism and that we traverse at most 1 element: -- --
--   lengthOf l x <= 1
--   
-- -- It may help to think of this as a Iso that can be partial in -- one direction. -- -- Every Prism is a valid Traversal. -- -- Every Iso is a valid Prism. -- -- For example, you might have a Prism' Integer -- Natural allows you to always go from a Natural to -- an Integer, and provide you with tools to check if an -- Integer is a Natural and/or to edit one if it is. -- --
--   nat :: Prism' Integer Natural
--   nat = prism toInteger $ \ i ->
--      if i < 0
--      then Left i
--      else Right (fromInteger i)
--   
-- -- Now we can ask if an Integer is a Natural. -- --
--   >>> 5^?nat
--   Just 5
--   
-- --
--   >>> (-5)^?nat
--   Nothing
--   
-- -- We can update the ones that are: -- --
--   >>> (-3,4) & both.nat *~ 2
--   (-3,8)
--   
-- -- And we can then convert from a Natural to an Integer. -- --
--   >>> 5 ^. re nat -- :: Natural
--   5
--   
-- -- Similarly we can use a Prism to traverse the -- Left half of an Either: -- --
--   >>> Left "hello" & _Left %~ length
--   Left 5
--   
-- -- or to construct an Either: -- --
--   >>> 5^.re _Left
--   Left 5
--   
-- -- such that if you query it with the Prism, you will get your -- original input back. -- --
--   >>> 5^.re _Left ^? _Left
--   Just 5
--   
-- -- Another interesting way to think of a Prism is as the -- categorical dual of a Lens -- a co-Lens, so to speak. -- This is what permits the construction of outside. -- -- Note: Composition with a Prism is index-preserving. type Prism s t a b = forall (p :: * -> * -> *) (f :: * -> *). (Choice p, Applicative f) => p a f b -> p s f t -- | A Simple Prism. type Prism' s a = Prism s s a a -- | Build a Prism. -- -- Either t a is used instead of Maybe a -- to permit the types of s and t to differ. prism :: () => b -> t -> s -> Either t a -> Prism s t a b -- | This is usually used to build a Prism', when you have to use an -- operation like cast which already returns a Maybe. prism' :: () => b -> s -> s -> Maybe a -> Prism s s a b -- | Check to see if this Prism matches. -- --
--   >>> is _Left (Right 12)
--   False
--   
-- --
--   >>> is hex "3f79"
--   True
--   
is :: () => APrism s t a b -> s -> Bool -- | This Prism compares for exact equality with a given value. -- --
--   >>> only 4 # ()
--   4
--   
-- --
--   >>> 5 ^? only 4
--   Nothing
--   
only :: Eq a => a -> Prism' a () module Optic.Prism.Cons -- | This class provides a way to attach or detach elements on the left -- side of a structure in a flexible manner. class Cons s t a b | s -> a, t -> b, s b -> t, t a -> s -- |
--   _Cons :: Prism [a] [b] (a, [a]) (b, [b])
--   _Cons :: Prism (Seq a) (Seq b) (a, Seq a) (b, Seq b)
--   _Cons :: Prism (Vector a) (Vector b) (a, Vector a) (b, Vector b)
--   _Cons :: Prism' String (Char, String)
--   _Cons :: Prism' Text (Char, Text)
--   _Cons :: Prism' ByteString (Word8, ByteString)
--   
_Cons :: Cons s t a b => Prism s t (a, s) (b, t) -- | cons an element onto a container. -- -- This is an infix alias for cons. -- --
--   >>> a <| []
--   [a]
--   
-- --
--   >>> a <| [b, c]
--   [a,b,c]
--   
-- --
--   >>> a <| Seq.fromList []
--   fromList [a]
--   
-- --
--   >>> a <| Seq.fromList [b, c]
--   fromList [a,b,c]
--   
(<|) :: Cons s s a a => a -> s -> s infixr 5 <| -- | cons an element onto a container. -- --
--   >>> cons a []
--   [a]
--   
-- --
--   >>> cons a [b, c]
--   [a,b,c]
--   
-- --
--   >>> cons a (Seq.fromList [])
--   fromList [a]
--   
-- --
--   >>> cons a (Seq.fromList [b, c])
--   fromList [a,b,c]
--   
cons :: Cons s s a a => a -> s -> s infixr 5 `cons` -- | Attempt to extract the left-most element from a container, and a -- version of the container without that element. -- --
--   >>> uncons []
--   Nothing
--   
-- --
--   >>> uncons [a, b, c]
--   Just (a,[b,c])
--   
uncons :: Cons s s a a => s -> Maybe (a, s) -- | A Traversal reading and writing to the head of a -- non-empty container. -- --
--   >>> [a,b,c]^? _head
--   Just a
--   
-- --
--   >>> [a,b,c] & _head .~ d
--   [d,b,c]
--   
-- --
--   >>> [a,b,c] & _head %~ f
--   [f a,b,c]
--   
-- --
--   >>> [] & _head %~ f
--   []
--   
-- --
--   >>> [1,2,3]^?!_head
--   1
--   
-- --
--   >>> []^?_head
--   Nothing
--   
-- --
--   >>> [1,2]^?_head
--   Just 1
--   
-- --
--   >>> [] & _head .~ 1
--   []
--   
-- --
--   >>> [0] & _head .~ 2
--   [2]
--   
-- --
--   >>> [0,1] & _head .~ 2
--   [2,1]
--   
-- -- This isn't limited to lists. -- -- For instance you can also traverse the head of a Seq: -- --
--   >>> Seq.fromList [a,b,c,d] & _head %~ f
--   fromList [f a,b,c,d]
--   
-- --
--   >>> Seq.fromList [] ^? _head
--   Nothing
--   
-- --
--   >>> Seq.fromList [a,b,c,d] ^? _head
--   Just a
--   
-- --
--   _head :: Traversal' [a] a
--   _head :: Traversal' (Seq a) a
--   _head :: Traversal' (Vector a) a
--   
_head :: Cons s s a a => Traversal' s a -- | A Traversal reading and writing to the tail of a -- non-empty container. -- --
--   >>> [a,b] & _tail .~ [c,d,e]
--   [a,c,d,e]
--   
-- --
--   >>> [] & _tail .~ [a,b]
--   []
--   
-- --
--   >>> [a,b,c,d,e] & _tail.traverse %~ f
--   [a,f b,f c,f d,f e]
--   
-- --
--   >>> [1,2] & _tail .~ [3,4,5]
--   [1,3,4,5]
--   
-- --
--   >>> [] & _tail .~ [1,2]
--   []
--   
-- --
--   >>> [a,b,c]^?_tail
--   Just [b,c]
--   
-- --
--   >>> [1,2]^?!_tail
--   [2]
--   
-- --
--   >>> "hello"^._tail
--   "ello"
--   
-- --
--   >>> ""^._tail
--   ""
--   
-- -- This isn't limited to lists. For instance you can also traverse -- the tail of a Seq. -- --
--   >>> Seq.fromList [a,b] & _tail .~ Seq.fromList [c,d,e]
--   fromList [a,c,d,e]
--   
-- --
--   >>> Seq.fromList [a,b,c] ^? _tail
--   Just (fromList [b,c])
--   
-- --
--   >>> Seq.fromList [] ^? _tail
--   Nothing
--   
-- --
--   _tail :: Traversal' [a] [a]
--   _tail :: Traversal' (Seq a) (Seq a)
--   _tail :: Traversal' (Vector a) (Vector a)
--   
_tail :: Cons s s a a => Traversal' s s infixr 5 :< module Optic.Prism.Empty class AsEmpty a -- |
--   >>> isn't _Empty [1,2,3]
--   True
--   
_Empty :: AsEmpty a => Prism' a () module Optic.Prism.Snoc -- | This class provides a way to attach or detach elements on the right -- side of a structure in a flexible manner. class Snoc s t a b | s -> a, t -> b, s b -> t, t a -> s -- |
--   _Snoc :: Prism [a] [b] ([a], a) ([b], b)
--   _Snoc :: Prism (Seq a) (Seq b) (Seq a, a) (Seq b, b)
--   _Snoc :: Prism (Vector a) (Vector b) (Vector a, a) (Vector b, b)
--   _Snoc :: Prism' String (String, Char)
--   _Snoc :: Prism' Text (Text, Char)
--   _Snoc :: Prism' ByteString (ByteString, Word8)
--   
_Snoc :: Snoc s t a b => Prism s t (s, a) (t, b) -- | snoc an element onto the end of a container. -- -- This is an infix alias for snoc. -- --
--   >>> Seq.fromList [] |> a
--   fromList [a]
--   
-- --
--   >>> Seq.fromList [b, c] |> a
--   fromList [b,c,a]
--   
-- --
--   >>> LazyT.pack "hello" |> '!'
--   "hello!"
--   
(|>) :: Snoc s s a a => s -> a -> s infixl 5 |> -- | snoc an element onto the end of a container. -- --
--   >>> snoc (Seq.fromList []) a
--   fromList [a]
--   
-- --
--   >>> snoc (Seq.fromList [b, c]) a
--   fromList [b,c,a]
--   
-- --
--   >>> snoc (LazyT.pack "hello") '!'
--   "hello!"
--   
snoc :: Snoc s s a a => s -> a -> s infixl 5 `snoc` -- | Attempt to extract the right-most element from a container, and a -- version of the container without that element. -- --
--   >>> unsnoc (LazyT.pack "hello!")
--   Just ("hello",'!')
--   
-- --
--   >>> unsnoc (LazyT.pack "")
--   Nothing
--   
-- --
--   >>> unsnoc (Seq.fromList [b,c,a])
--   Just (fromList [b,c],a)
--   
-- --
--   >>> unsnoc (Seq.fromList [])
--   Nothing
--   
unsnoc :: Snoc s s a a => s -> Maybe (s, a) -- | A Traversal reading and replacing all but the a last element of -- a non-empty container. -- --
--   >>> [a,b,c,d]^?_init
--   Just [a,b,c]
--   
-- --
--   >>> []^?_init
--   Nothing
--   
-- --
--   >>> [a,b] & _init .~ [c,d,e]
--   [c,d,e,b]
--   
-- --
--   >>> [] & _init .~ [a,b]
--   []
--   
-- --
--   >>> [a,b,c,d] & _init.traverse %~ f
--   [f a,f b,f c,d]
--   
-- --
--   >>> [1,2,3]^?_init
--   Just [1,2]
--   
-- --
--   >>> [1,2,3,4]^?!_init
--   [1,2,3]
--   
-- --
--   >>> "hello"^._init
--   "hell"
--   
-- --
--   >>> ""^._init
--   ""
--   
-- --
--   _init :: Traversal' [a] [a]
--   _init :: Traversal' (Seq a) (Seq a)
--   _init :: Traversal' (Vector a) (Vector a)
--   
_init :: Snoc s s a a => Traversal' s s -- | A Traversal reading and writing to the last element of a -- non-empty container. -- --
--   >>> [a,b,c]^?!_last
--   c
--   
-- --
--   >>> []^?_last
--   Nothing
--   
-- --
--   >>> [a,b,c] & _last %~ f
--   [a,b,f c]
--   
-- --
--   >>> [1,2]^?_last
--   Just 2
--   
-- --
--   >>> [] & _last .~ 1
--   []
--   
-- --
--   >>> [0] & _last .~ 2
--   [2]
--   
-- --
--   >>> [0,1] & _last .~ 2
--   [0,2]
--   
-- -- This Traversal is not limited to lists, however. We can also -- work with other containers, such as a Vector. -- --
--   >>> Vector.fromList "abcde" ^? _last
--   Just 'e'
--   
-- --
--   >>> Vector.empty ^? _last
--   Nothing
--   
-- --
--   >>> (Vector.fromList "abcde" & _last .~ 'Q') == Vector.fromList "abcdQ"
--   True
--   
-- --
--   _last :: Traversal' [a] a
--   _last :: Traversal' (Seq a) a
--   _last :: Traversal' (Vector a) a
--   
_last :: Snoc s s a a => Traversal' s a infixl 5 :> module Optic.Review -- | This is a limited form of a Prism that can only be used for -- re operations. -- -- Like with a Getter, there are no laws to state for a -- Review. -- -- You can generate a Review by using unto. You can also -- use any Prism or Iso directly as a Review. type Review t b = forall (p :: * -> * -> *) (f :: * -> *). (Choice p, Bifunctor p, Settable f) => Optic' p f t b -- | This can be used to turn an Iso or Prism around and -- view a value (or the current environment) through it the other -- way. -- --
--   reviewview . re
--   review . untoid
--   
-- --
--   >>> review _Left "mustard"
--   Left "mustard"
--   
-- --
--   >>> review (unto succ) 5
--   6
--   
-- -- Usually review is used in the (->) Monad -- with a Prism or Iso, in which case it may be useful to -- think of it as having one of these more restricted type signatures: -- --
--   review :: Iso' s a   -> a -> s
--   review :: Prism' s a -> a -> s
--   
-- -- However, when working with a Monad transformer stack, it is -- sometimes useful to be able to review the current environment, -- in which case it may be beneficial to think of it as having one of -- these slightly more liberal type signatures: -- --
--   review :: MonadReader a m => Iso' s a   -> m s
--   review :: MonadReader a m => Prism' s a -> m s
--   
review :: MonadReader b m => AReview t b -> m t module Optic.Setter -- | The only LensLike law that can apply to a Setter -- l is that -- --
--   set l y (set l x a) ≡ set l y a
--   
-- -- You can't view a Setter in general, so the other two -- laws are irrelevant. -- -- However, two Functor laws apply to a Setter: -- --
--   over l idid
--   over l f . over l g ≡ over l (f . g)
--   
-- -- These can be stated more directly: -- --
--   l purepure
--   l f . untainted . l g ≡ l (f . untainted . g)
--   
-- -- You can compose a Setter with a Lens or a -- Traversal using (.) from the Prelude and the -- result is always only a Setter and nothing more. -- --
--   >>> over traverse f [a,b,c,d]
--   [f a,f b,f c,f d]
--   
-- --
--   >>> over _1 f (a,b)
--   (f a,b)
--   
-- --
--   >>> over (traverse._1) f [(a,b),(c,d)]
--   [(f a,b),(f c,d)]
--   
-- --
--   >>> over both f (a,b)
--   (f a,f b)
--   
-- --
--   >>> over (traverse.both) f [(a,b),(c,d)]
--   [(f a,f b),(f c,f d)]
--   
type Setter s t a b = forall (f :: * -> *). Settable f => a -> f b -> s -> f t -- | A Setter' is just a Setter that doesn't change the -- types. -- -- These are particularly common when talking about monomorphic -- containers. e.g. -- --
--   sets Data.Text.map :: Setter' Text Char
--   
-- --
--   type Setter' = Simple Setter
--   
type Setter' s a = Setter s s a a -- | 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 %~ -- | Increment the target(s) of a numerically valued Lens, -- Setter or Traversal. -- --
--   >>> (a,b) & _1 +~ c
--   (a + c,b)
--   
-- --
--   >>> (a,b) & both +~ c
--   (a + c,b + c)
--   
-- --
--   >>> (1,2) & _2 +~ 1
--   (1,3)
--   
-- --
--   >>> [(a,b),(c,d)] & traverse.both +~ e
--   [(a + e,b + e),(c + e,d + e)]
--   
-- --
--   (+~) :: Num a => Setter' s a    -> a -> s -> s
--   (+~) :: Num a => Iso' s a       -> a -> s -> s
--   (+~) :: Num a => Lens' s a      -> a -> s -> s
--   (+~) :: Num a => Traversal' s a -> a -> s -> s
--   
(+~) :: Num a => ASetter s t a a -> a -> s -> t infixr 4 +~ -- | Decrement the target(s) of a numerically valued Lens, -- Iso, Setter or Traversal. -- --
--   >>> (a,b) & _1 -~ c
--   (a - c,b)
--   
-- --
--   >>> (a,b) & both -~ c
--   (a - c,b - c)
--   
-- --
--   >>> _1 -~ 2 $ (1,2)
--   (-1,2)
--   
-- --
--   >>> mapped.mapped -~ 1 $ [[4,5],[6,7]]
--   [[3,4],[5,6]]
--   
-- --
--   (-~) :: Num a => Setter' s a    -> a -> s -> s
--   (-~) :: Num a => Iso' s a       -> a -> s -> s
--   (-~) :: Num a => Lens' s a      -> a -> s -> s
--   (-~) :: Num a => Traversal' s a -> a -> s -> s
--   
(-~) :: Num a => ASetter s t a a -> a -> s -> t infixr 4 -~ -- | Multiply the target(s) of a numerically valued Lens, -- Iso, Setter or Traversal. -- --
--   >>> (a,b) & _1 *~ c
--   (a * c,b)
--   
-- --
--   >>> (a,b) & both *~ c
--   (a * c,b * c)
--   
-- --
--   >>> (1,2) & _2 *~ 4
--   (1,8)
--   
-- --
--   >>> Just 24 & mapped *~ 2
--   Just 48
--   
-- --
--   (*~) :: Num a => Setter' s a    -> a -> s -> s
--   (*~) :: Num a => Iso' s a       -> a -> s -> s
--   (*~) :: Num a => Lens' s a      -> a -> s -> s
--   (*~) :: Num a => Traversal' s a -> a -> s -> s
--   
(*~) :: Num a => ASetter s t a a -> a -> s -> t infixr 4 *~ -- | Divide the target(s) of a numerically valued Lens, Iso, -- Setter or Traversal. -- --
--   >>> (a,b) & _1 //~ c
--   (a / c,b)
--   
-- --
--   >>> (a,b) & both //~ c
--   (a / c,b / c)
--   
-- --
--   >>> ("Hawaii",10) & _2 //~ 2
--   ("Hawaii",5.0)
--   
-- --
--   (//~) :: Fractional a => Setter' s a    -> a -> s -> s
--   (//~) :: Fractional a => Iso' s a       -> a -> s -> s
--   (//~) :: Fractional a => Lens' s a      -> a -> s -> s
--   (//~) :: Fractional a => Traversal' s a -> a -> s -> s
--   
(//~) :: Fractional a => ASetter s t a a -> a -> s -> t infixr 4 //~ -- | Raise the target(s) of a numerically valued Lens, Setter -- or Traversal to a non-negative integral power. -- --
--   >>> (1,3) & _2 ^~ 2
--   (1,9)
--   
-- --
--   (^~) :: (Num a, Integral e) => Setter' s a    -> e -> s -> s
--   (^~) :: (Num a, Integral e) => Iso' s a       -> e -> s -> s
--   (^~) :: (Num a, Integral e) => Lens' s a      -> e -> s -> s
--   (^~) :: (Num a, Integral e) => Traversal' s a -> e -> s -> s
--   
(^~) :: (Num a, Integral e) => ASetter s t a a -> e -> s -> t infixr 4 ^~ -- | Raise the target(s) of a fractionally valued Lens, -- Setter or Traversal to an integral power. -- --
--   >>> (1,2) & _2 ^^~ (-1)
--   (1,0.5)
--   
-- --
--   (^^~) :: (Fractional a, Integral e) => Setter' s a    -> e -> s -> s
--   (^^~) :: (Fractional a, Integral e) => Iso' s a       -> e -> s -> s
--   (^^~) :: (Fractional a, Integral e) => Lens' s a      -> e -> s -> s
--   (^^~) :: (Fractional a, Integral e) => Traversal' s a -> e -> s -> s
--   
(^^~) :: (Fractional a, Integral e) => ASetter s t a a -> e -> s -> t infixr 4 ^^~ -- | Raise the target(s) of a floating-point valued Lens, -- Setter or Traversal to an arbitrary power. -- --
--   >>> (a,b) & _1 **~ c
--   (a**c,b)
--   
-- --
--   >>> (a,b) & both **~ c
--   (a**c,b**c)
--   
-- --
--   >>> _2 **~ 10 $ (3,2)
--   (3,1024.0)
--   
-- --
--   (**~) :: Floating a => Setter' s a    -> a -> s -> s
--   (**~) :: Floating a => Iso' s a       -> a -> s -> s
--   (**~) :: Floating a => Lens' s a      -> a -> s -> s
--   (**~) :: Floating a => Traversal' s a -> a -> s -> s
--   
(**~) :: Floating a => ASetter s t a a -> a -> s -> t infixr 4 **~ -- | Logically || the target(s) of a Bool-valued Lens -- or Setter. -- --
--   >>> both ||~ True $ (False,True)
--   (True,True)
--   
-- --
--   >>> both ||~ False $ (False,True)
--   (False,True)
--   
-- --
--   (||~) :: Setter' s Bool    -> Bool -> s -> s
--   (||~) :: Iso' s Bool       -> Bool -> s -> s
--   (||~) :: Lens' s Bool      -> Bool -> s -> s
--   (||~) :: Traversal' s Bool -> Bool -> s -> s
--   
(||~) :: () => ASetter s t Bool Bool -> Bool -> s -> t infixr 4 ||~ -- | Logically && the target(s) of a Bool-valued -- Lens or Setter. -- --
--   >>> both &&~ True $ (False, True)
--   (False,True)
--   
-- --
--   >>> both &&~ False $ (False, True)
--   (False,False)
--   
-- --
--   (&&~) :: Setter' s Bool    -> Bool -> s -> s
--   (&&~) :: Iso' s Bool       -> Bool -> s -> s
--   (&&~) :: Lens' s Bool      -> Bool -> s -> s
--   (&&~) :: Traversal' s Bool -> Bool -> s -> s
--   
(&&~) :: () => ASetter s t Bool Bool -> Bool -> 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 module Optic.Traversal -- | 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 :: * -> *). Applicative f => a -> f b -> s -> f t -- |
--   type Traversal' = Simple Traversal
--   
type Traversal' s a = Traversal s s a a -- | Map each element of a structure targeted by a Lens or -- Traversal, evaluate these actions from left to right, and -- collect the results. -- -- This function is only provided for consistency, id is strictly -- more general. -- --
--   >>> traverseOf each print (1,2,3)
--   1
--   2
--   3
--   ((),(),())
--   
-- --
--   traverseOfid
--   itraverseOf l ≡ traverseOf l . Indexed
--   itraverseOf itraverseditraverse
--   
-- -- This yields the obvious law: -- --
--   traversetraverseOf traverse
--   
-- --
--   traverseOf :: Functor f     => Iso s t a b        -> (a -> f b) -> s -> f t
--   traverseOf :: Functor f     => Lens s t a b       -> (a -> f b) -> s -> f t
--   traverseOf :: Apply f       => Traversal1 s t a b -> (a -> f b) -> s -> f t
--   traverseOf :: Applicative f => Traversal s t a b  -> (a -> f b) -> s -> f t
--   
traverseOf :: () => LensLike f s t a b -> a -> f b -> s -> f t -- | A version of traverseOf with the arguments flipped, such that: -- --
--   >>> forOf each (1,2,3) print
--   1
--   2
--   3
--   ((),(),())
--   
-- -- This function is only provided for consistency, flip is -- strictly more general. -- --
--   forOfflip
--   forOfflip . traverseOf
--   
-- --
--   forforOf traverse
--   ifor l s ≡ for l s . Indexed
--   
-- --
--   forOf :: Functor f => Iso s t a b -> s -> (a -> f b) -> f t
--   forOf :: Functor f => Lens s t a b -> s -> (a -> f b) -> f t
--   forOf :: Applicative f => Traversal s t a b -> s -> (a -> f b) -> f t
--   
forOf :: () => LensLike f s t a b -> s -> a -> f b -> f t -- | Evaluate each action in the structure from left to right, and collect -- the results. -- --
--   >>> sequenceAOf both ([1,2],[3,4])
--   [(1,3),(1,4),(2,3),(2,4)]
--   
-- --
--   sequenceAsequenceAOf traversetraverse id
--   sequenceAOf l ≡ traverseOf l id ≡ l id
--   
-- --
--   sequenceAOf :: Functor f => Iso s t (f b) b       -> s -> f t
--   sequenceAOf :: Functor f => Lens s t (f b) b      -> s -> f t
--   sequenceAOf :: Applicative f => Traversal s t (f b) b -> s -> f t
--   
sequenceAOf :: () => LensLike f s t f b b -> s -> f t module Optic.Traversal.Each -- | Extract each element of a (potentially monomorphic) container. -- -- Notably, when applied to a tuple, this generalizes both to -- arbitrary homogeneous tuples. -- --
--   >>> (1,2,3) & each *~ 10
--   (10,20,30)
--   
-- -- It can also be used on monomorphic containers like Text or -- ByteString. -- --
--   >>> over each Char.toUpper ("hello"^.Text.packed)
--   "HELLO"
--   
-- --
--   >>> ("hello","world") & each.each %~ Char.toUpper
--   ("HELLO","WORLD")
--   
class Each s t a b | s -> a, t -> b, s b -> t, t a -> s each :: Each s t a b => Traversal s t a b module Optic.Traversal.Ixed -- | Provides a simple Traversal lets you traverse the value -- at a given key in a Map or element at an ordinal position in a -- list or Seq. class Ixed m -- | NB: Setting the value of this Traversal will only set -- the value in at if it is already present. -- -- If you want to be able to insert missing values, you want -- at. -- --
--   >>> Seq.fromList [a,b,c,d] & ix 2 %~ f
--   fromList [a,b,f c,d]
--   
-- --
--   >>> Seq.fromList [a,b,c,d] & ix 2 .~ e
--   fromList [a,b,e,d]
--   
-- --
--   >>> Seq.fromList [a,b,c,d] ^? ix 2
--   Just c
--   
-- --
--   >>> Seq.fromList [] ^? ix 2
--   Nothing
--   
ix :: Ixed m => Index m -> Traversal' m IxValue m -- | This provides a common notion of a value at an index that is shared by -- both Ixed and At. module Optic.Lens.At -- | At provides a Lens that can be used to read, write or -- delete the value associated with a key in a Map-like container -- on an ad hoc basis. -- -- An instance of At should satisfy: -- --
--   ix k ≡ at k . traverse
--   
class Ixed m => At m -- |
--   >>> Map.fromList [(1,"world")] ^.at 1
--   Just "world"
--   
-- --
--   >>> at 1 ?~ "hello" $ Map.empty
--   fromList [(1,"hello")]
--   
-- -- Note: Map-like containers form a reasonable instance, -- but not Array-like ones, where you cannot satisfy the -- Lens laws. at :: At m => Index m -> Lens' m Maybe IxValue m -- | Delete the value associated with a key in a Map-like container -- --
--   sans k = at k .~ Nothing
--   
sans :: At m => Index m -> m -> m module Ord -- | 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. -- -- 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 data Ordering LT :: Ordering EQ :: Ordering GT :: Ordering -- | Defines a total ordering on a type as per compare -- -- This condition is not checked by the types. You must ensure that the -- supplied values are valid total orderings yourself. newtype Comparison a Comparison :: a -> a -> Ordering -> Comparison a [getComparison] :: Comparison a -> a -> a -> Ordering -- | Compare using compare defaultComparison :: Ord a => Comparison a -- |
--   comparing p x y = compare (p x) (p y)
--   
-- -- Useful combinator for use in conjunction with the xxxBy -- family of functions from Data.List, for example: -- --
--   ... sortBy (comparing fst) ...
--   
comparing :: Ord a => b -> a -> b -> b -> Ordering -- | The Down type allows you to reverse sort order conveniently. A -- value of type Down a contains a value of type -- a (represented as Down a). If a has -- an Ord instance associated with it then comparing two -- values thus wrapped will give you the opposite of their normal sort -- order. This is particularly useful when sorting in generalised list -- comprehensions, as in: then sortWith by Down x newtype Down a Down :: a -> Down a newtype Min a Min :: a -> Min a [getMin] :: Min a -> a newtype Max a Max :: a -> Max a [getMax] :: Max a -> a -- | Arg isn't itself a Semigroup in its own right, but it -- can be placed inside Min and Max to compute an arg min -- or arg max. data Arg a b Arg :: a -> b -> Arg a b type ArgMin a b = Min Arg a b type ArgMax a b = Max Arg a b -- | Lifting of the Ord class to unary type constructors. class Eq1 f => Ord1 (f :: * -> *) -- | Lift a compare function through the type constructor. -- -- The function will usually be applied to a comparison function, but the -- more general type ensures that the implementation uses it to compare -- elements of the first container with elements of the second. liftCompare :: Ord1 f => a -> b -> Ordering -> f a -> f b -> Ordering -- | Lift the standard compare function through the type -- constructor. compare1 :: (Ord1 f, Ord a) => f a -> f a -> Ordering -- | A sensible default liftCompare implementation for -- Generic1 instances. liftCompareDefault :: (GOrd1 NonV4 Rep1 f, Generic1 f) => a -> b -> Ordering -> f a -> f b -> Ordering -- | Lifting of the Ord class to binary type constructors. class Eq2 f => Ord2 (f :: * -> * -> *) -- | Lift compare functions through the type constructor. -- -- The function will usually be applied to comparison functions, but the -- more general type ensures that the implementation uses them to compare -- elements of the first container with elements of the second. liftCompare2 :: Ord2 f => a -> b -> Ordering -> c -> d -> Ordering -> f a c -> f b d -> Ordering -- | Lift the standard compare function through the type -- constructor. compare2 :: (Ord2 f, Ord a, Ord b) => f a b -> f a b -> Ordering module Parallelism par :: () => a -> b -> b infixr 0 `par` pseq :: () => a -> b -> b infixr 0 `pseq` -- | rpar sparks its argument (for evaluation in parallel). rpar :: () => Strategy a -- | Perform a computation in parallel using a strategy. -- --
--   rparWith strat x
--   
-- -- will spark strat x. Note that rparWith strat is -- not the same as rpar dot strat. Specifically, -- rpar dot strat always sparks a computation to reduce -- the result of the strategic computation to WHNF, while rparWith -- strat need not. -- --
--   rparWith r0 = r0
--   rparWith rpar = rpar
--   rparWith rseq = rpar
--   
-- -- rparWith rpar x creates a spark that immediately creates -- another spark to evaluate x. We consider this equivalent to -- rpar because there isn't any real additional parallelism. -- However, it is always less efficient because there's a bit of extra -- work to create the first (useless) spark. Similarly, rparWith -- r0 creates a spark that does precisely nothing. No real -- parallelism is added, but there is a bit of extra work to do nothing. rparWith :: () => Strategy a -> Strategy a -- | Like evalTraversable but evaluates all elements in parallel. parTraversable :: Traversable t => Strategy a -> Strategy t a -- | Evaluate each element of a list in parallel according to given -- strategy. Equivalent to parTraversable at the list type. parList :: () => Strategy a -> Strategy [a] -- | Divides a list into chunks, and applies the strategy -- evalList strat to each chunk in parallel. -- -- It is expected that this function will be replaced by a more generic -- clustering infrastructure in the future. -- -- If the chunk size is 1 or less, parListChunk is equivalent to -- parList parListChunk :: () => Int -> Strategy a -> Strategy [a] -- | A combination of parList and map, encapsulating a common -- pattern: -- --
--   parMap strat f = withStrategy (parList strat) . map f
--   
parMap :: () => Strategy b -> a -> b -> [a] -> [b] parTuple2 :: () => Strategy a -> Strategy b -> Strategy (a, b) parTuple3 :: () => Strategy a -> Strategy b -> Strategy c -> Strategy (a, b, c) parTuple4 :: () => Strategy a -> Strategy b -> Strategy c -> Strategy d -> Strategy (a, b, c, d) parTuple5 :: () => Strategy a -> Strategy b -> Strategy c -> Strategy d -> Strategy e -> Strategy (a, b, c, d, e) parTuple6 :: () => Strategy a -> Strategy b -> Strategy c -> Strategy d -> Strategy e -> Strategy f -> Strategy (a, b, c, d, e, f) parTuple7 :: () => Strategy a -> Strategy b -> Strategy c -> Strategy d -> Strategy e -> Strategy f -> Strategy g -> Strategy (a, b, c, d, e, f, g) parTuple8 :: () => Strategy a -> Strategy b -> Strategy c -> Strategy d -> Strategy e -> Strategy f -> Strategy g -> Strategy h -> Strategy (a, b, c, d, e, f, g, h) parTuple9 :: () => Strategy a -> Strategy b -> Strategy c -> Strategy d -> Strategy e -> Strategy f -> Strategy g -> Strategy h -> Strategy i -> Strategy (a, b, c, d, e, f, g, h, i) module Parser.Binary module Parser.Cli module Parser.Earley module Parser.Env module Parser.Text module Pointed class Pointed (p :: * -> *) point :: Pointed p => a -> p a module Posix module Predicate newtype Predicate a Predicate :: a -> Bool -> Predicate a [getPredicate] :: Predicate a -> a -> Bool module Pretty module Prim module Printf module Process -- | forkProcess corresponds to the POSIX fork system call. -- The IO action passed as an argument is executed in the child -- process; no other threads will be copied to the child process. On -- success, forkProcess returns the child's ProcessID to -- the parent process; in case of an error, an exception is thrown. -- -- The exception masking state of the executed action is inherited (c.f. -- forkIO), see also forkProcessWithUnmask (since: -- 2.7.0.0). -- -- forkProcess comes with a giant warning: since any other running -- threads are not copied into the child process, it's easy to go wrong: -- e.g. by accessing some shared resource that was held by another thread -- in the parent. forkProcess :: IO () -> IO ProcessID -- | Variant of forkProcess in the style of -- forkIOWithUnmask. forkProcessWithUnmask :: forall a. () => IO a -> IO a -> IO () -> IO ProcessID -- | getProcessStatus blk stopped pid calls -- waitpid, returning Just tc, the -- ProcessStatus for process pid if it is available, -- Nothing otherwise. If blk is False, then -- WNOHANG is set in the options for waitpid, otherwise -- not. If stopped is True, then WUNTRACED is -- set in the options for waitpid, otherwise not. getProcessStatus :: Bool -> Bool -> ProcessID -> IO Maybe ProcessStatus -- | getAnyProcessStatus blk stopped calls -- waitpid, returning Just (pid, tc), the -- ProcessID and ProcessStatus for any child process if a -- child process has exited, or Nothing if there are child -- processes but none have exited. If there are no child processes, then -- getAnyProcessStatus raises an isDoesNotExistError -- exception. -- -- If blk is False, then WNOHANG is set in the -- options for waitpid, otherwise not. If stopped is -- True, then WUNTRACED is set in the options for -- waitpid, otherwise not. getAnyProcessStatus :: Bool -> Bool -> IO Maybe (ProcessID, ProcessStatus) -- | getGroupProcessStatus blk stopped pgid calls -- waitpid, returning Just (pid, tc), the -- ProcessID and ProcessStatus for any process in group -- pgid if one is available, or Nothing if there are -- child processes but none have exited. If there are no child processes, -- then getGroupProcessStatus raises an -- isDoesNotExistError exception. -- -- If blk is False, then WNOHANG is set in the -- options for waitpid, otherwise not. If stopped is -- True, then WUNTRACED is set in the options for -- waitpid, otherwise not. getGroupProcessStatus :: Bool -> Bool -> ProcessGroupID -> IO Maybe (ProcessID, ProcessStatus) -- | exitImmediately status calls _exit to -- terminate the process with the indicated exit status. The -- operation never returns. exitImmediately :: ExitCode -> IO () -- | executeFile cmd args env calls one of the -- execv* family, depending on whether or not the current PATH -- is to be searched for the command, and whether or not an environment -- is provided to supersede the process's current environment. The -- basename (leading directory names suppressed) of the command is passed -- to execv* as arg[0]; the argument list passed to -- executeFile therefore begins with arg[1]. executeFile :: () => FilePath -> Bool -> [String] -> Maybe [(String, String)] -> IO a -- | getProcessID calls getpid to obtain the -- ProcessID for the current process. getProcessID :: IO ProcessID -- | getProcessID calls getppid to obtain the -- ProcessID for the parent of the current process. getParentProcessID :: IO ProcessID -- | getProcessGroupID calls getpgrp to obtain the -- ProcessGroupID for the current process. getProcessGroupID :: IO ProcessGroupID -- | getProcessGroupIDOf pid calls getpgid to -- obtain the ProcessGroupID for process pid. getProcessGroupIDOf :: ProcessID -> IO ProcessGroupID -- | createProcessGroupFor pid calls setpgid to -- make process pid a new process group leader. createProcessGroupFor :: ProcessID -> IO ProcessGroupID -- | joinProcessGroup pgid calls setpgid to set -- the ProcessGroupID of the current process to pgid. joinProcessGroup :: ProcessGroupID -> IO () -- | setProcessGroupIDOf pid pgid calls setpgid to -- set the ProcessGroupIDOf for process pid to -- pgid. setProcessGroupIDOf :: ProcessID -> ProcessGroupID -> IO () -- | createSession calls setsid to create a new session -- with the current process as session leader. createSession :: IO ProcessGroupID module Profunctor -- | Formally, the class Profunctor represents a profunctor from -- Hask -> Hask. -- -- Intuitively it is a bifunctor where the first argument is -- contravariant and the second argument is covariant. -- -- You can define a Profunctor by either defining dimap or -- by defining both lmap and rmap. -- -- If you supply dimap, you should ensure that: -- --
--   dimap id idid
--   
-- -- If you supply lmap and rmap, ensure: -- --
--   lmap idid
--   rmap idid
--   
-- -- If you supply both, you should also ensure: -- --
--   dimap f g ≡ lmap f . rmap g
--   
-- -- These ensure by parametricity: -- --
--   dimap (f . g) (h . i) ≡ dimap g h . dimap f i
--   lmap (f . g) ≡ lmap g . lmap f
--   rmap (f . g) ≡ rmap f . rmap g
--   
class Profunctor (p :: * -> * -> *) -- | Map over both arguments at the same time. -- --
--   dimap f g ≡ lmap f . rmap g
--   
dimap :: Profunctor p => a -> b -> c -> d -> p b c -> p a d -- | Map the first argument contravariantly. -- --
--   lmap f ≡ dimap f id
--   
lmap :: Profunctor p => a -> b -> p b c -> p a c -- | Map the second argument covariantly. -- --
--   rmapdimap id
--   
rmap :: Profunctor p => b -> c -> p a b -> p a c module Proxy -- | Proxy is a type that holds no data, but has a phantom parameter -- of arbitrary type (or even kind). Its use is to provide type -- information, even though there is no value available of that type (or -- it may be too costly to create one). -- -- Historically, Proxy :: Proxy a is a safer -- alternative to the 'undefined :: a' idiom. -- --
--   >>> Proxy :: Proxy (Void, Int -> Int)
--   Proxy
--   
-- -- Proxy can even hold types of higher kinds, -- --
--   >>> Proxy :: Proxy Either
--   Proxy
--   
-- --
--   >>> Proxy :: Proxy Functor
--   Proxy
--   
-- --
--   >>> Proxy :: Proxy complicatedStructure
--   Proxy
--   
data Proxy (t :: k) :: forall k. () => k -> * Proxy :: Proxy -- | asProxyTypeOf is a type-restricted version of const. It -- is usually used as an infix operator, and its typing forces its first -- argument (which is usually overloaded) to have the same type as the -- tag of the second. -- --
--   >>> import Data.Word
--   
--   >>> :type asProxyTypeOf 123 (Proxy :: Proxy Word8)
--   asProxyTypeOf 123 (Proxy :: Proxy Word8) :: Word8
--   
-- -- Note the lower-case proxy in the definition. This allows any -- type constructor with just one argument to be passed to the function, -- for example we could also write -- --
--   >>> import Data.Word
--   
--   >>> :type asProxyTypeOf 123 (Just (undefined :: Word8))
--   asProxyTypeOf 123 (Just (undefined :: Word8)) :: Word8
--   
asProxyTypeOf :: () => a -> proxy a -> a -- | A concrete, promotable proxy type, for use at the kind level There are -- no instances for this because it is intended at the kind level only data KProxy t KProxy :: KProxy t module Ptr -- | 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 -- | The constant nullPtr contains a distinguished value of -- Ptr that is not associated with a valid memory location. nullPtr :: () => Ptr a -- | The castPtr function casts a pointer from one type to another. castPtr :: () => Ptr a -> Ptr b -- | Advances the given address by the given offset in bytes. plusPtr :: () => Ptr a -> Int -> Ptr b -- | Given an arbitrary address and an alignment constraint, -- alignPtr yields the next higher address that fulfills the -- alignment constraint. An alignment constraint x is fulfilled -- by any address divisible by x. This operation is idempotent. alignPtr :: () => Ptr a -> Int -> Ptr a -- | Computes the offset required to get from the second to the first -- argument. We have -- --
--   p2 == p1 `plusPtr` (p2 `minusPtr` p1)
--   
minusPtr :: () => Ptr a -> Ptr b -> Int -- | alloca f executes the computation f, passing -- as argument a pointer to a temporarily allocated block of memory -- sufficient to hold values of type a. -- -- The memory is freed when f terminates (either normally or via -- an exception), so the pointer passed to f must not be -- used after this. alloca :: Storable a => Ptr a -> IO b -> IO b -- | allocaBytes n f executes the computation f, -- passing as argument a pointer to a temporarily allocated block of -- memory of n bytes. The block of memory is sufficiently -- aligned for any of the basic foreign types that fits into a memory -- block of the allocated size. -- -- The memory is freed when f terminates (either normally or via -- an exception), so the pointer passed to f must not be -- used after this. allocaBytes :: () => Int -> Ptr a -> IO b -> IO b allocaBytesAligned :: () => Int -> Int -> Ptr a -> IO b -> IO b -- | Allocate a block of memory that is sufficient to hold values of type -- a. The size of the area allocated is determined by the -- sizeOf method from the instance of Storable for the -- appropriate type. -- -- The memory may be deallocated using free or -- finalizerFree when no longer required. malloc :: Storable a => IO Ptr a -- | Allocate a block of memory of the given number of bytes. The block of -- memory is sufficiently aligned for any of the basic foreign types that -- fits into a memory block of the allocated size. -- -- The memory may be deallocated using free or -- finalizerFree when no longer required. mallocBytes :: () => Int -> IO Ptr a -- | Like malloc but memory is filled with bytes of value zero. calloc :: Storable a => IO Ptr a -- | Llike mallocBytes but memory is filled with bytes of value -- zero. callocBytes :: () => Int -> IO Ptr a -- | Resize a memory area that was allocated with malloc or -- mallocBytes to the size needed to store values of type -- b. The returned pointer may refer to an entirely different -- memory area, but will be suitably aligned to hold values of type -- b. The contents of the referenced memory area will be the -- same as of the original pointer up to the minimum of the original size -- and the size of values of type b. -- -- If the argument to realloc is nullPtr, realloc -- behaves like malloc. realloc :: Storable b => Ptr a -> IO Ptr b -- | Resize a memory area that was allocated with malloc or -- mallocBytes to the given size. The returned pointer may refer -- to an entirely different memory area, but will be sufficiently aligned -- for any of the basic foreign types that fits into a memory block of -- the given size. The contents of the referenced memory area will be the -- same as of the original pointer up to the minimum of the original size -- and the given size. -- -- If the pointer argument to reallocBytes is nullPtr, -- reallocBytes behaves like malloc. If the requested size -- is 0, reallocBytes behaves like free. reallocBytes :: () => Ptr a -> Int -> IO Ptr a -- | Copies the given number of bytes from the second area (source) into -- the first (destination); the copied areas may not overlap copyBytes :: () => Ptr a -> Ptr a -> Int -> IO () -- | Copies the given number of bytes from the second area (source) into -- the first (destination); the copied areas may overlap moveBytes :: () => Ptr a -> Ptr a -> Int -> IO () -- | Fill a given number of bytes in memory area with a byte value. fillBytes :: () => Ptr a -> Word8 -> Int -> IO () -- | Free a block of memory that was allocated with malloc, -- mallocBytes, realloc, reallocBytes, new or -- any of the newX functions in -- Foreign.Marshal.Array or Foreign.C.String. free :: () => Ptr a -> IO () -- | Allocate storage for the given number of elements of a storable type -- (like malloc, but for multiple elements). mallocArray :: Storable a => Int -> IO Ptr a -- | Like mallocArray, but add an extra position to hold a special -- termination element. mallocArray0 :: Storable a => Int -> IO Ptr a -- | Temporarily allocate space for the given number of elements (like -- alloca, but for multiple elements). allocaArray :: Storable a => Int -> Ptr a -> IO b -> IO b -- | Like allocaArray, but add an extra position to hold a special -- termination element. allocaArray0 :: Storable a => Int -> Ptr a -> IO b -> IO b -- | Adjust the size of an array reallocArray :: Storable a => Ptr a -> Int -> IO Ptr a -- | Adjust the size of an array including an extra position for the end -- marker. reallocArray0 :: Storable a => Ptr a -> Int -> IO Ptr a -- | Like mallocArray, but allocated memory is filled with bytes of -- value zero. callocArray :: Storable a => Int -> IO Ptr a -- | Like callocArray0, but allocated memory is filled with bytes of -- value zero. callocArray0 :: Storable a => Int -> IO Ptr a -- | Convert an array of given length into a Haskell list. The -- implementation is tail-recursive and so uses constant stack space. peekArray :: Storable a => Int -> Ptr a -> IO [a] -- | Convert an array terminated by the given end marker into a Haskell -- list peekArray0 :: (Storable a, Eq a) => a -> Ptr a -> IO [a] -- | Write the list elements consecutive into memory pokeArray :: Storable a => Ptr a -> [a] -> IO () -- | Write the list elements consecutive into memory and terminate them -- with the given marker element pokeArray0 :: Storable a => a -> Ptr a -> [a] -> IO () -- | Write a list of storable elements into a newly allocated, consecutive -- sequence of storable values (like new, but for multiple -- elements). newArray :: Storable a => [a] -> IO Ptr a -- | Write a list of storable elements into a newly allocated, consecutive -- sequence of storable values, where the end is fixed by the given end -- marker newArray0 :: Storable a => a -> [a] -> IO Ptr a -- | Temporarily store a list of storable values in memory (like -- with, but for multiple elements). withArray :: Storable a => [a] -> Ptr a -> IO b -> IO b -- | Like withArray, but a terminator indicates where the array ends withArray0 :: Storable a => a -> [a] -> Ptr a -> IO b -> IO b -- | Like withArray, but the action gets the number of values as an -- additional parameter withArrayLen :: Storable a => [a] -> Int -> Ptr a -> IO b -> IO b -- | Like withArrayLen, but a terminator indicates where the array -- ends withArrayLen0 :: Storable a => a -> [a] -> Int -> Ptr a -> IO b -> IO b -- | Copy the given number of elements from the second array (source) into -- the first array (destination); the copied areas may not overlap copyArray :: Storable a => Ptr a -> Ptr a -> Int -> IO () -- | Copy the given number of elements from the second array (source) into -- the first array (destination); the copied areas may overlap moveArray :: Storable a => Ptr a -> Ptr a -> Int -> IO () -- | Return the number of elements in an array, excluding the terminator lengthArray0 :: (Storable a, Eq a) => a -> Ptr a -> IO Int -- | Advance a pointer into an array by the given number of elements advancePtr :: Storable a => Ptr a -> Int -> Ptr a -- | A memory pool. data Pool -- | Allocate a fresh memory pool. newPool :: IO Pool -- | Deallocate a memory pool and everything which has been allocated in -- the pool itself. freePool :: Pool -> IO () -- | Execute an action with a fresh memory pool, which gets automatically -- deallocated (including its contents) after the action has finished. withPool :: () => Pool -> IO b -> IO b -- | Allocate space for storable type in the given pool. The size of the -- area allocated is determined by the sizeOf method from the -- instance of Storable for the appropriate type. pooledMalloc :: Storable a => Pool -> IO Ptr a -- | Allocate the given number of bytes of storage in the pool. pooledMallocBytes :: () => Pool -> Int -> IO Ptr a -- | Adjust the storage area for an element in the pool to the given size -- of the required type. pooledRealloc :: Storable a => Pool -> Ptr a -> IO Ptr a -- | Adjust the storage area for an element in the pool to the given size. pooledReallocBytes :: () => Pool -> Ptr a -> Int -> IO Ptr a -- | Allocate storage for the given number of elements of a storable type -- in the pool. pooledMallocArray :: Storable a => Pool -> Int -> IO Ptr a -- | Allocate storage for the given number of elements of a storable type -- in the pool, but leave room for an extra element to signal the end of -- the array. pooledMallocArray0 :: Storable a => Pool -> Int -> IO Ptr a -- | Adjust the size of an array in the given pool. pooledReallocArray :: Storable a => Pool -> Ptr a -> Int -> IO Ptr a -- | Adjust the size of an array with an end marker in the given pool. pooledReallocArray0 :: Storable a => Pool -> Ptr a -> Int -> IO Ptr a -- | Allocate storage for a value in the given pool and marshal the value -- into this storage. pooledNew :: Storable a => Pool -> a -> IO Ptr a -- | Allocate consecutive storage for a list of values in the given pool -- and marshal these values into it. pooledNewArray :: Storable a => Pool -> [a] -> IO Ptr a -- | Allocate consecutive storage for a list of values in the given pool -- and marshal these values into it, terminating the end with the given -- marker. pooledNewArray0 :: Storable a => Pool -> a -> [a] -> IO Ptr a -- | A signed integral type that can be losslessly converted to and from -- Ptr. This type is also compatible with the C99 type -- intptr_t, and can be marshalled to and from that type safely. newtype IntPtr IntPtr :: Int -> IntPtr -- | casts a Ptr to an IntPtr ptrToIntPtr :: () => Ptr a -> IntPtr -- | casts an IntPtr to a Ptr intPtrToPtr :: () => IntPtr -> Ptr a -- | An unsigned integral type that can be losslessly converted to and from -- Ptr. This type is also compatible with the C99 type -- uintptr_t, and can be marshalled to and from that type -- safely. newtype WordPtr WordPtr :: Word -> WordPtr -- | casts a Ptr to a WordPtr ptrToWordPtr :: () => Ptr a -> WordPtr -- | casts a WordPtr to a Ptr wordPtrToPtr :: () => WordPtr -> Ptr a module Ptr.Foreign -- | The type ForeignPtr represents references to objects that are -- maintained in a foreign language, i.e., that are not part of the data -- structures usually managed by the Haskell storage manager. The -- essential difference between ForeignPtrs and vanilla memory -- references of type Ptr a is that the former may be associated -- with finalizers. A finalizer is a routine that is invoked when -- the Haskell storage manager detects that - within the Haskell heap and -- stack - there are no more references left that are pointing to the -- ForeignPtr. Typically, the finalizer will, then, invoke -- routines in the foreign language that free the resources bound by the -- foreign object. -- -- The ForeignPtr is parameterised in the same way as Ptr. -- The type argument of ForeignPtr should normally be an instance -- of class Storable. data ForeignPtr a -- | Turns a plain memory reference into a foreign pointer, and associates -- a finalizer with the reference. The finalizer will be executed after -- the last reference to the foreign object is dropped. There is no -- guarantee of promptness, however the finalizer will be executed before -- the program exits. newForeignPtr :: () => FinalizerPtr a -> Ptr a -> IO ForeignPtr a -- | Turns a plain memory reference into a foreign pointer that may be -- associated with finalizers by using addForeignPtrFinalizer. newForeignPtr_ :: () => Ptr a -> IO ForeignPtr a -- | This function adds a finalizer to the given foreign object. The -- finalizer will run before all other finalizers for the same -- object which have already been registered. addForeignPtrFinalizer :: () => FinalizerPtr a -> ForeignPtr a -> IO () -- | This variant of newForeignPtr adds a finalizer that expects an -- environment in addition to the finalized pointer. The environment that -- will be passed to the finalizer is fixed by the second argument to -- newForeignPtrEnv. newForeignPtrEnv :: () => FinalizerEnvPtr env a -> Ptr env -> Ptr a -> IO ForeignPtr a -- | Like addForeignPtrFinalizerEnv but allows the finalizer to be -- passed an additional environment parameter to be passed to the -- finalizer. The environment passed to the finalizer is fixed by the -- second argument to addForeignPtrFinalizerEnv addForeignPtrFinalizerEnv :: () => FinalizerEnvPtr env a -> Ptr env -> ForeignPtr a -> IO () -- | This is a way to look at the pointer living inside a foreign object. -- This function takes a function which is applied to that pointer. The -- resulting IO action is then executed. The foreign object is -- kept alive at least during the whole action, even if it is not used -- directly inside. Note that it is not safe to return the pointer from -- the action and use it after the action completes. All uses of the -- pointer should be inside the withForeignPtr bracket. The reason -- for this unsafeness is the same as for unsafeForeignPtrToPtr -- below: the finalizer may run earlier than expected, because the -- compiler can only track usage of the ForeignPtr object, not a -- Ptr object made from it. -- -- This function is normally used for marshalling data to or from the -- object pointed to by the ForeignPtr, using the operations from -- the Storable class. withForeignPtr :: () => ForeignPtr a -> Ptr a -> IO b -> IO b -- | Causes the finalizers associated with a foreign pointer to be run -- immediately. finalizeForeignPtr :: () => ForeignPtr a -> IO () -- | This function ensures that the foreign object in question is alive at -- the given place in the sequence of IO actions. In particular -- withForeignPtr does a touchForeignPtr after it executes -- the user action. -- -- Note that this function should not be used to express dependencies -- between finalizers on ForeignPtrs. For example, if the -- finalizer for a ForeignPtr F1 calls -- touchForeignPtr on a second ForeignPtr F2, then -- the only guarantee is that the finalizer for F2 is never -- started before the finalizer for F1. They might be started -- together if for example both F1 and F2 are otherwise -- unreachable, and in that case the scheduler might end up running the -- finalizer for F2 first. -- -- In general, it is not recommended to use finalizers on separate -- objects with ordering constraints between them. To express the -- ordering robustly requires explicit synchronisation using -- MVars between the finalizers, but even then the runtime -- sometimes runs multiple finalizers sequentially in a single thread -- (for performance reasons), so synchronisation between finalizers could -- result in artificial deadlock. Another alternative is to use explicit -- reference counting. touchForeignPtr :: () => ForeignPtr a -> IO () -- | This function casts a ForeignPtr parameterised by one type into -- another type. castForeignPtr :: () => ForeignPtr a -> ForeignPtr b -- | Advances the given address by the given offset in bytes. -- -- The new ForeignPtr shares the finalizer of the original, -- equivalent from a finalization standpoint to just creating another -- reference to the original. That is, the finalizer will not be called -- before the new ForeignPtr is unreachable, nor will it be called -- an additional time due to this call, and the finalizer will be called -- with the same address that it would have had this call not happened, -- *not* the new address. plusForeignPtr :: () => ForeignPtr a -> Int -> ForeignPtr b -- | Allocate some memory and return a ForeignPtr to it. The memory -- will be released automatically when the ForeignPtr is -- discarded. -- -- mallocForeignPtr is equivalent to -- --
--   do { p <- malloc; newForeignPtr finalizerFree p }
--   
-- -- although it may be implemented differently internally: you may not -- assume that the memory returned by mallocForeignPtr has been -- allocated with malloc. -- -- GHC notes: mallocForeignPtr has a heavily optimised -- implementation in GHC. It uses pinned memory in the garbage collected -- heap, so the ForeignPtr does not require a finalizer to free -- the memory. Use of mallocForeignPtr and associated functions is -- strongly recommended in preference to newForeignPtr with a -- finalizer. mallocForeignPtr :: Storable a => IO ForeignPtr a -- | This function is similar to mallocForeignPtr, except that the -- size of the memory required is given explicitly as a number of bytes. mallocForeignPtrBytes :: () => Int -> IO ForeignPtr a -- | This function is similar to mallocArray, but yields a memory -- area that has a finalizer attached that releases the memory area. As -- with mallocForeignPtr, it is not guaranteed that the block of -- memory was allocated by malloc. mallocForeignPtrArray :: Storable a => Int -> IO ForeignPtr a -- | This function is similar to mallocArray0, but yields a memory -- area that has a finalizer attached that releases the memory area. As -- with mallocForeignPtr, it is not guaranteed that the block of -- memory was allocated by malloc. mallocForeignPtrArray0 :: Storable a => Int -> IO ForeignPtr a -- | This function extracts the pointer component of a foreign pointer. -- This is a potentially dangerous operations, as if the argument to -- unsafeForeignPtrToPtr is the last usage occurrence of the given -- foreign pointer, then its finalizer(s) will be run, which potentially -- invalidates the plain pointer just obtained. Hence, -- touchForeignPtr must be used wherever it has to be guaranteed -- that the pointer lives on - i.e., has another usage occurrence. -- -- To avoid subtle coding errors, hand written marshalling code should -- preferably use withForeignPtr rather than combinations of -- unsafeForeignPtrToPtr and touchForeignPtr. However, the -- latter routines are occasionally preferred in tool generated -- marshalling code. unsafeForeignPtrToPtr :: () => ForeignPtr a -> Ptr a module Ptr.Fun -- | 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 constant nullFunPtr contains a distinguished value of -- FunPtr that is not associated with a valid memory location. nullFunPtr :: () => FunPtr a -- | Casts a FunPtr to a FunPtr of a different type. castFunPtr :: () => FunPtr a -> FunPtr b -- | Casts a FunPtr to a Ptr. -- -- Note: this is valid only on architectures where data and -- function pointers range over the same set of addresses, and should -- only be used for bindings to external libraries whose interface -- already relies on this assumption. castFunPtrToPtr :: () => FunPtr a -> Ptr b -- | Casts a Ptr to a FunPtr. -- -- Note: this is valid only on architectures where data and -- function pointers range over the same set of addresses, and should -- only be used for bindings to external libraries whose interface -- already relies on this assumption. castPtrToFunPtr :: () => Ptr a -> FunPtr b -- | Release the storage associated with the given FunPtr, which -- must have been obtained from a wrapper stub. This should be called -- whenever the return value from a foreign import wrapper function is no -- longer required; otherwise, the storage it uses will leak. freeHaskellFunPtr :: () => FunPtr a -> IO () -- | A finalizer is represented as a pointer to a foreign function that, at -- finalisation time, gets as an argument a plain pointer variant of the -- foreign pointer that the finalizer is associated with. -- -- Note that the foreign function must use the ccall -- calling convention. type FinalizerPtr a = FunPtr Ptr a -> IO () type FinalizerEnvPtr env a = FunPtr Ptr env -> Ptr a -> IO () -- | A pointer to a foreign function equivalent to free, which may -- be used as a finalizer (cf ForeignPtr) for storage allocated -- with malloc, mallocBytes, realloc or -- reallocBytes. finalizerFree :: () => FinalizerPtr a module Ptr.Stable -- | A stable pointer is a reference to a Haskell expression that is -- guaranteed not to be affected by garbage collection, i.e., it will -- neither be deallocated nor will the value of the stable pointer itself -- change during garbage collection (ordinary references may be relocated -- during garbage collection). Consequently, stable pointers can be -- passed to foreign code, which can treat it as an opaque reference to a -- Haskell value. -- -- A value of type StablePtr a is a stable pointer to a Haskell -- expression of type a. data StablePtr a -- | Create a stable pointer referring to the given Haskell value. newStablePtr :: () => a -> IO StablePtr a -- | Obtain the Haskell value referenced by a stable pointer, i.e., the -- same value that was passed to the corresponding call to -- makeStablePtr. If the argument to deRefStablePtr has -- already been freed using freeStablePtr, the behaviour of -- deRefStablePtr is undefined. deRefStablePtr :: () => StablePtr a -> IO a -- | Dissolve the association between the stable pointer and the Haskell -- value. Afterwards, if the stable pointer is passed to -- deRefStablePtr or freeStablePtr, the behaviour is -- undefined. However, the stable pointer may still be passed to -- castStablePtrToPtr, but the Ptr () value -- returned by castStablePtrToPtr, in this case, is undefined (in -- particular, it may be nullPtr). Nevertheless, the call to -- castStablePtrToPtr is guaranteed not to diverge. freeStablePtr :: () => StablePtr a -> IO () -- | Coerce a stable pointer to an address. No guarantees are made about -- the resulting value, except that the original stable pointer can be -- recovered by castPtrToStablePtr. In particular, the address may -- not refer to an accessible memory location and any attempt to pass it -- to the member functions of the class Storable leads to -- undefined behaviour. castStablePtrToPtr :: () => StablePtr a -> Ptr () -- | The inverse of castStablePtrToPtr, i.e., we have the identity -- --
--   sp == castPtrToStablePtr (castStablePtrToPtr sp)
--   
-- -- for any stable pointer sp on which freeStablePtr has -- not been executed yet. Moreover, castPtrToStablePtr may only be -- applied to pointers that have been produced by -- castStablePtrToPtr. castPtrToStablePtr :: () => Ptr () -> StablePtr a module Ptr.Static -- | A reference to a value of type a. data StaticPtr a -- | Dereferences a static pointer. deRefStaticPtr :: () => StaticPtr a -> a -- | A key for StaticPtrs that can be serialized and used with -- unsafeLookupStaticPtr. type StaticKey = Fingerprint -- | The StaticKey that can be used to look up the given -- StaticPtr. staticKey :: () => StaticPtr a -> StaticKey -- | Looks up a StaticPtr by its StaticKey. -- -- If the StaticPtr is not found returns Nothing. -- -- This function is unsafe because the program behavior is undefined if -- the type of the returned StaticPtr does not match the expected -- one. unsafeLookupStaticPtr :: () => StaticKey -> IO Maybe StaticPtr a -- | Miscelaneous information available for debugging purposes. data StaticPtrInfo StaticPtrInfo :: String -> String -> (Int, Int) -> StaticPtrInfo -- | Package key of the package where the static pointer is defined [spInfoUnitId] :: StaticPtrInfo -> String -- | Name of the module where the static pointer is defined [spInfoModuleName] :: StaticPtrInfo -> String -- | Source location of the definition of the static pointer as a -- (Line, Column) pair. [spInfoSrcLoc] :: StaticPtrInfo -> (Int, Int) -- | StaticPtrInfo of the given StaticPtr. staticPtrInfo :: () => StaticPtr a -> StaticPtrInfo -- | A list of all known keys. staticPtrKeys :: IO [StaticKey] -- | A class for things buildable from static pointers. class IsStatic (p :: * -> *) fromStaticPtr :: IsStatic p => StaticPtr a -> p a module Ptr.Weak -- | A weak pointer object with a key and a value. The value has type -- v. -- -- A weak pointer expresses a relationship between two objects, the -- key and the value: if the key is considered to be alive -- by the garbage collector, then the value is also alive. A reference -- from the value to the key does not keep the key alive. -- -- A weak pointer may also have a finalizer of type IO (); if it -- does, then the finalizer will be run at most once, at a time after the -- key has become unreachable by the program ("dead"). The storage -- manager attempts to run the finalizer(s) for an object soon after the -- object dies, but promptness is not guaranteed. -- -- It is not guaranteed that a finalizer will eventually run, and no -- attempt is made to run outstanding finalizers when the program exits. -- Therefore finalizers should not be relied on to clean up resources - -- other methods (eg. exception handlers) should be employed, possibly in -- addition to finalizers. -- -- References from the finalizer to the key are treated in the same way -- as references from the value to the key: they do not keep the key -- alive. A finalizer may therefore ressurrect the key, perhaps by -- storing it in the same data structure. -- -- The finalizer, and the relationship between the key and the value, -- exist regardless of whether the program keeps a reference to the -- Weak object or not. -- -- There may be multiple weak pointers with the same key. In this case, -- the finalizers for each of these weak pointers will all be run in some -- arbitrary order, or perhaps concurrently, when the key dies. If the -- programmer specifies a finalizer that assumes it has the only -- reference to an object (for example, a file that it wishes to close), -- then the programmer must ensure that there is only one such finalizer. -- -- If there are no other threads to run, the runtime system will check -- for runnable finalizers before declaring the system to be deadlocked. -- -- WARNING: weak pointers to ordinary non-primitive Haskell types are -- particularly fragile, because the compiler is free to optimise away or -- duplicate the underlying data structure. Therefore attempting to place -- a finalizer on an ordinary Haskell type may well result in the -- finalizer running earlier than you expected. This is not a problem for -- caches and memo tables where early finalization is benign. -- -- Finalizers can be used reliably for types that are created -- explicitly and have identity, such as IORef and -- MVar. However, to place a finalizer on one of these types, -- you should use the specific operation provided for that type, e.g. -- mkWeakIORef and addMVarFinalizer respectively (the -- non-uniformity is accidental). These operations attach the finalizer -- to the primitive object inside the box (e.g. MutVar# in the -- case of IORef), because attaching the finalizer to the box -- itself fails when the outer box is optimised away by the compiler. data Weak v -- | Establishes a weak pointer to k, with value v and a -- finalizer. -- -- This is the most general interface for building a weak pointer. mkWeak :: () => k -> v -> Maybe IO () -> IO Weak v -- | Dereferences a weak pointer. If the key is still alive, then -- Just v is returned (where v is the -- value in the weak pointer), otherwise Nothing is -- returned. -- -- The return value of deRefWeak depends on when the garbage -- collector runs, hence it is in the IO monad. deRefWeak :: () => Weak v -> IO Maybe v -- | Causes a the finalizer associated with a weak pointer to be run -- immediately. finalize :: () => Weak v -> IO () -- | A specialised version of mkWeak, where the key and the value -- are the same object: -- --
--   mkWeakPtr key finalizer = mkWeak key key finalizer
--   
mkWeakPtr :: () => k -> Maybe IO () -> IO Weak k -- | A specialised version of mkWeakPtr, where the Weak -- object returned is simply thrown away (however the finalizer will be -- remembered by the garbage collector, and will still be run when the -- key becomes unreachable). -- -- Note: adding a finalizer to a ForeignPtr using -- addFinalizer won't work; use the specialised version -- addForeignPtrFinalizer instead. For discussion see the -- Weak type. . addFinalizer :: () => key -> IO () -> IO () -- | A specialised version of mkWeak where the value is actually a -- pair of the key and value passed to mkWeakPair: -- --
--   mkWeakPair key val finalizer = mkWeak key (key,val) finalizer
--   
-- -- The advantage of this is that the key can be retrieved by -- deRefWeak in addition to the value. mkWeakPair :: () => k -> v -> Maybe IO () -> IO Weak (k, v) module Queue.Prio.Hash -- | A priority search queue with keys of type k and priorities of -- type p and values of type v. It is strict in keys, -- priorities and values. data HashPSQ k p v -- | O(1) The empty queue. empty :: () => HashPSQ k p v -- | O(1) Build a queue with one element. singleton :: (Hashable k, Ord k, Ord p) => k -> p -> v -> HashPSQ k p v -- | O(n*min(n,W)) Build a queue from a list of (key, priority, -- value) tuples. If the list contains more than one priority and value -- for the same key, the last priority and value for the key is retained. fromList :: (Hashable k, Ord k, Ord p) => [(k, p, v)] -> HashPSQ k p v -- | O(1) True if the queue is empty. null :: () => HashPSQ k p v -> Bool -- | O(n) The number of elements stored in the PSQ. size :: () => HashPSQ k p v -> Int -- | O(min(n,W)) Check if a key is present in the the queue. member :: (Hashable k, Ord k, Ord p) => k -> HashPSQ k p v -> Bool -- | O(min(n,W)) The priority and value of a given key, or -- Nothing if the key is not bound. lookup :: (Ord k, Hashable k, Ord p) => k -> HashPSQ k p v -> Maybe (p, v) -- | O(1) The element with the lowest priority. findMin :: (Hashable k, Ord k, Ord p) => HashPSQ k p v -> Maybe (k, p, v) -- | O(min(n,W)) Retrieve the binding with the least priority, and -- the rest of the queue stripped of that binding. minView :: (Hashable k, Ord k, Ord p) => HashPSQ k p v -> Maybe (k, p, v, HashPSQ k p v) -- | Return a list of elements ordered by key whose priorities are at most -- pt, and the rest of the queue stripped of these elements. The -- returned list of elements can be in any order: no guarantees there. atMostView :: (Hashable k, Ord k, Ord p) => p -> HashPSQ k p v -> ([(k, p, v)], HashPSQ k p v) -- | O(min(n,W)) Insert a new key, priority and value into the -- queue. If the key is already present in the queue, the associated -- priority and value are replaced with the supplied priority and value. insert :: (Ord k, Hashable k, Ord p) => k -> p -> v -> HashPSQ k p v -> HashPSQ k p v -- | O(min(n,W)) Insert a new key, priority and value into the -- queue. If the key is already present in the queue, then the evicted -- priority and value can be found the first element of the returned -- tuple. insertView :: (Hashable k, Ord k, Ord p) => k -> p -> v -> HashPSQ k p v -> (Maybe (p, v), HashPSQ k p v) -- | O(min(n,W)) Delete a key and its priority and value from the -- queue. When the key is not a member of the queue, the original queue -- is returned. delete :: (Hashable k, Ord k, Ord p) => k -> HashPSQ k p v -> HashPSQ k p v -- | O(min(n,W)) Delete a key and its priority and value from the -- queue. If the key was present, the associated priority and value are -- returned in addition to the updated queue. deleteView :: (Hashable k, Ord k, Ord p) => k -> HashPSQ k p v -> Maybe (p, v, HashPSQ k p v) -- | O(min(n,W)) The expression alter f k queue alters the -- value x at k, or absence thereof. alter can -- be used to insert, delete, or update a value in a queue. It also -- allows you to calculate an additional value b. alter :: (Hashable k, Ord k, Ord p) => Maybe (p, v) -> (b, Maybe (p, v)) -> k -> HashPSQ k p v -> (b, HashPSQ k p v) -- | O(min(n,W)) A variant of alter which works on the -- element with the minimum priority. Unlike alter, this variant -- also allows you to change the key of the element. alterMin :: (Hashable k, Ord k, Ord p) => Maybe (k, p, v) -> (b, Maybe (k, p, v)) -> HashPSQ k p v -> (b, HashPSQ k p v) -- | O(n) Modify every value in the queue. map :: () => k -> p -> v -> w -> HashPSQ k p v -> HashPSQ k p w -- | O(n) Maps a function over the values and priorities of the -- queue. The function f must be monotonic with respect to the -- priorities. I.e. if x < y, then fst (f k x v) < fst -- (f k y v). The precondition is not checked. If f -- is not monotonic, then the result will be invalid. unsafeMapMonotonic :: () => k -> p -> v -> (q, w) -> HashPSQ k p v -> HashPSQ k q w -- | O(n) Convert a queue to a list of (key, priority, value) -- tuples. The order of the list is not specified. toList :: (Hashable k, Ord k, Ord p) => HashPSQ k p v -> [(k, p, v)] -- | O(n) Obtain the list of present keys in the queue. keys :: (Hashable k, Ord k, Ord p) => HashPSQ k p v -> [k] -- | O(n) Strict fold over every key, priority and value in the -- queue. The order in which the fold is performed is not specified. fold' :: () => k -> p -> v -> a -> a -> a -> HashPSQ k p v -> a module Queue.Prio.Int -- | A priority search queue with Int keys and priorities of type -- p and values of type v. It is strict in keys, -- priorities and values. data IntPSQ p v -- | O(1) The empty queue. empty :: () => IntPSQ p v -- | O(1) Build a queue with one element. singleton :: Ord p => Int -> p -> v -> IntPSQ p v -- | O(n*min(n,W)) Build a queue from a list of (key, priority, -- value) tuples. If the list contains more than one priority and value -- for the same key, the last priority and value for the key is retained. fromList :: Ord p => [(Int, p, v)] -> IntPSQ p v -- | O(1) True if the queue is empty. null :: () => IntPSQ p v -> Bool -- | O(n) The number of elements stored in the queue. size :: () => IntPSQ p v -> Int -- | O(min(n,W)) Check if a key is present in the the queue. member :: () => Int -> IntPSQ p v -> Bool -- | O(min(n,W)) The priority and value of a given key, or -- Nothing if the key is not bound. lookup :: () => Int -> IntPSQ p v -> Maybe (p, v) -- | O(1) The element with the lowest priority. findMin :: Ord p => IntPSQ p v -> Maybe (Int, p, v) -- | O(min(n,W)) Retrieve the binding with the least priority, and -- the rest of the queue stripped of that binding. minView :: Ord p => IntPSQ p v -> Maybe (Int, p, v, IntPSQ p v) -- | Return a list of elements ordered by key whose priorities are at most -- pt, and the rest of the queue stripped of these elements. The -- returned list of elements can be in any order: no guarantees there. atMostView :: Ord p => p -> IntPSQ p v -> ([(Int, p, v)], IntPSQ p v) -- | O(min(n,W)) Insert a new key, priority and value into the -- queue. If the key is already present in the queue, the associated -- priority and value are replaced with the supplied priority and value. insert :: Ord p => Int -> p -> v -> IntPSQ p v -> IntPSQ p v -- | O(min(n,W)) Insert a new key, priority and value into the -- queue. If the key is already present in the queue, then the evicted -- priority and value can be found the first element of the returned -- tuple. insertView :: Ord p => Int -> p -> v -> IntPSQ p v -> (Maybe (p, v), IntPSQ p v) -- | O(min(n,W)) Delete a key and its priority and value from the -- queue. When the key is not a member of the queue, the original queue -- is returned. delete :: Ord p => Int -> IntPSQ p v -> IntPSQ p v -- | O(min(n,W)) Delete a key and its priority and value from the -- queue. If the key was present, the associated priority and value are -- returned in addition to the updated queue. deleteView :: Ord p => Int -> IntPSQ p v -> Maybe (p, v, IntPSQ p v) -- | O(min(n,W)) The expression alter f k queue alters the -- value x at k, or absence thereof. alter can -- be used to insert, delete, or update a value in a queue. It also -- allows you to calculate an additional value b. alter :: Ord p => Maybe (p, v) -> (b, Maybe (p, v)) -> Int -> IntPSQ p v -> (b, IntPSQ p v) -- | O(min(n,W)) A variant of alter which works on the -- element with the minimum priority. Unlike alter, this variant -- also allows you to change the key of the element. alterMin :: Ord p => Maybe (Int, p, v) -> (b, Maybe (Int, p, v)) -> IntPSQ p v -> (b, IntPSQ p v) -- | O(n) Modify every value in the queue. map :: () => Int -> p -> v -> w -> IntPSQ p v -> IntPSQ p w -- | O(n) Maps a function over the values and priorities of the -- queue. The function f must be monotonic with respect to the -- priorities. I.e. if x < y, then fst (f k x v) < fst -- (f k y v). The precondition is not checked. If f -- is not monotonic, then the result will be invalid. unsafeMapMonotonic :: () => Key -> p -> v -> (q, w) -> IntPSQ p v -> IntPSQ q w -- | O(n) Convert a queue to a list of (key, priority, value) -- tuples. The order of the list is not specified. toList :: () => IntPSQ p v -> [(Int, p, v)] -- | O(n) Obtain the list of present keys in the queue. keys :: () => IntPSQ p v -> [Int] -- | O(n) Strict fold over every key, priority and value in the -- queue. The order in which the fold is performed is not specified. fold' :: () => Int -> p -> v -> a -> a -> a -> IntPSQ p v -> a module Queue.Prio.Ord -- | A mapping from keys k to priorites p and values -- v. It is strict in keys, priorities and values. data OrdPSQ k p v -- | O(1) The empty queue. empty :: () => OrdPSQ k p v -- | O(1) Build a queue with one element. singleton :: () => k -> p -> v -> OrdPSQ k p v -- | O(n*log n) Build a queue from a list of (key, priority, value) -- tuples. If the list contains more than one priority and value for the -- same key, the last priority and value for the key is retained. fromList :: (Ord k, Ord p) => [(k, p, v)] -> OrdPSQ k p v -- | O(1) True if the queue is empty. null :: () => OrdPSQ k p v -> Bool -- | O(1) The number of elements in a queue. size :: () => OrdPSQ k p v -> Int -- | O(log n) Check if a key is present in the the queue. member :: Ord k => k -> OrdPSQ k p v -> Bool -- | O(log n) The priority and value of a given key, or -- Nothing if the key is not bound. lookup :: Ord k => k -> OrdPSQ k p v -> Maybe (p, v) -- | O(1) The element with the lowest priority. findMin :: () => OrdPSQ k p v -> Maybe (k, p, v) -- | O(log n) Retrieve the binding with the least priority, and the -- rest of the queue stripped of that binding. minView :: (Ord k, Ord p) => OrdPSQ k p v -> Maybe (k, p, v, OrdPSQ k p v) -- | Return a list of elements ordered by key whose priorities are at most -- pt, and the rest of the queue stripped of these elements. The -- returned list of elements can be in any order: no guarantees there. atMostView :: (Ord k, Ord p) => p -> OrdPSQ k p v -> ([(k, p, v)], OrdPSQ k p v) -- | O(log n) Insert a new key, priority and value into the queue. -- If the key is already present in the queue, the associated priority -- and value are replaced with the supplied priority and value. insert :: (Ord k, Ord p) => k -> p -> v -> OrdPSQ k p v -> OrdPSQ k p v -- | O(log n) Insert a new key, priority and value into the queue. -- If the key is already present in the queue, then the evicted priority -- and value can be found the first element of the returned tuple. insertView :: (Ord k, Ord p) => k -> p -> v -> OrdPSQ k p v -> (Maybe (p, v), OrdPSQ k p v) -- | O(log n) Delete a key and its priority and value from the -- queue. When the key is not a member of the queue, the original queue -- is returned. delete :: (Ord k, Ord p) => k -> OrdPSQ k p v -> OrdPSQ k p v -- | O(log n) Delete a key and its priority and value from the -- queue. If the key was present, the associated priority and value are -- returned in addition to the updated queue. deleteView :: (Ord k, Ord p) => k -> OrdPSQ k p v -> Maybe (p, v, OrdPSQ k p v) -- | O(log n) The expression alter f k queue alters the -- value x at k, or absence thereof. alter can -- be used to insert, delete, or update a value in a queue. It also -- allows you to calculate an additional value b. alter :: (Ord k, Ord p) => Maybe (p, v) -> (b, Maybe (p, v)) -> k -> OrdPSQ k p v -> (b, OrdPSQ k p v) -- | O(log n) A variant of alter which works on the element -- with the minimum priority. Unlike alter, this variant also -- allows you to change the key of the element. alterMin :: (Ord k, Ord p) => Maybe (k, p, v) -> (b, Maybe (k, p, v)) -> OrdPSQ k p v -> (b, OrdPSQ k p v) -- | O(n) Modify every value in the queue. map :: () => k -> p -> v -> w -> OrdPSQ k p v -> OrdPSQ k p w -- | O(n) Maps a function over the values and priorities of the -- queue. The function f must be monotonic with respect to the -- priorities. I.e. if x < y, then fst (f k x v) < fst -- (f k y v). The precondition is not checked. If f -- is not monotonic, then the result will be invalid. unsafeMapMonotonic :: () => k -> p -> v -> (q, w) -> OrdPSQ k p v -> OrdPSQ k q w -- | O(n) Convert a queue to a list of (key, priority, value) -- tuples. The order of the list is not specified. toList :: () => OrdPSQ k p v -> [(k, p, v)] -- | O(n) Convert to an ascending list. toAscList :: () => OrdPSQ k p v -> [(k, p, v)] -- | O(n) Obtain the list of present keys in the queue. keys :: () => OrdPSQ k p v -> [k] -- | O(n) Strict fold over every key, priority and value in the -- queue. The order in which the fold is performed is not specified. fold' :: () => k -> p -> v -> a -> a -> a -> OrdPSQ k p v -> a module Random module Read -- | Parsing of Strings, producing values. -- -- Derived instances of Read make the following assumptions, which -- derived instances of Show obey: -- -- -- -- For example, given the declarations -- --
--   infixr 5 :^:
--   data Tree a =  Leaf a  |  Tree a :^: Tree a
--   
-- -- the derived instance of Read in Haskell 2010 is equivalent to -- --
--   instance (Read a) => Read (Tree a) where
--   
--           readsPrec d r =  readParen (d > app_prec)
--                            (\r -> [(Leaf m,t) |
--                                    ("Leaf",s) <- lex r,
--                                    (m,t) <- readsPrec (app_prec+1) s]) r
--   
--                         ++ readParen (d > up_prec)
--                            (\r -> [(u:^:v,w) |
--                                    (u,s) <- readsPrec (up_prec+1) r,
--                                    (":^:",t) <- lex s,
--                                    (v,w) <- readsPrec (up_prec+1) t]) r
--   
--             where app_prec = 10
--                   up_prec = 5
--   
-- -- Note that right-associativity of :^: is unused. -- -- The derived instance in GHC is equivalent to -- --
--   instance (Read a) => Read (Tree a) where
--   
--           readPrec = parens $ (prec app_prec $ do
--                                    Ident "Leaf" <- lexP
--                                    m <- step readPrec
--                                    return (Leaf m))
--   
--                        +++ (prec up_prec $ do
--                                    u <- step readPrec
--                                    Symbol ":^:" <- lexP
--                                    v <- step readPrec
--                                    return (u :^: v))
--   
--             where app_prec = 10
--                   up_prec = 5
--   
--           readListPrec = readListPrecDefault
--   
-- -- Why do both readsPrec and readPrec exist, and why does -- GHC opt to implement readPrec in derived Read instances -- instead of readsPrec? The reason is that readsPrec is -- based on the ReadS type, and although ReadS is mentioned -- in the Haskell 2010 Report, it is not a very efficient parser data -- structure. -- -- readPrec, on the other hand, is based on a much more efficient -- ReadPrec datatype (a.k.a "new-style parsers"), but its -- definition relies on the use of the RankNTypes language -- extension. Therefore, readPrec (and its cousin, -- readListPrec) are marked as GHC-only. Nevertheless, it is -- recommended to use readPrec instead of readsPrec -- whenever possible for the efficiency improvements it brings. -- -- As mentioned above, derived Read instances in GHC will -- implement readPrec instead of readsPrec. The default -- implementations of readsPrec (and its cousin, readList) -- will simply use readPrec under the hood. If you are writing a -- Read instance by hand, it is recommended to write it like so: -- --
--   instance Read T where
--     readPrec     = ...
--     readListPrec = readListPrecDefault
--   
class Read a -- | attempts to parse a value from the front of the string, returning a -- list of (parsed value, remaining string) pairs. If there is no -- successful parse, the returned list is empty. -- -- Derived instances of Read and Show satisfy the -- following: -- -- -- -- That is, readsPrec parses the string produced by -- showsPrec, and delivers the value that showsPrec started -- with. readsPrec :: Read a => Int -> ReadS a -- | The method readList is provided to allow the programmer to give -- a specialised way of parsing lists of values. For example, this is -- used by the predefined Read instance of the Char type, -- where values of type String should be are expected to use -- double quotes, rather than square brackets. readList :: Read a => ReadS [a] -- | Proposed replacement for readsPrec using new-style parsers (GHC -- only). readPrec :: Read a => ReadPrec a -- | Proposed replacement for readList using new-style parsers (GHC -- only). The default definition uses readList. Instances that -- define readPrec should also define readListPrec as -- readListPrecDefault. readListPrec :: Read a => ReadPrec [a] -- | A parser for a type a, represented as a function that takes a -- String and returns a list of possible parses as -- (a,String) pairs. -- -- Note that this kind of backtracking parser is very inefficient; -- reading a large structure may be quite slow (cf ReadP). type ReadS a = String -> [(a, String)] -- | equivalent to readsPrec with a precedence of 0. reads :: Read a => ReadS a -- | Parse a string using the Read instance. Succeeds if there is -- exactly one valid result. -- --
--   >>> readMaybe "123" :: Maybe Int
--   Just 123
--   
-- --
--   >>> readMaybe "hello" :: Maybe Int
--   Nothing
--   
readMaybe :: Read a => String -> Maybe a -- | Parse a string using the Read instance. Succeeds if there is -- exactly one valid result. A Left value indicates a parse error. -- --
--   >>> readEither "123" :: Either String Int
--   Right 123
--   
-- --
--   >>> readEither "hello" :: Either String Int
--   Left "Prelude.read: no parse"
--   
readEither :: Read a => String -> Either String a -- | readParen True p parses what p parses, -- but surrounded with parentheses. -- -- readParen False p parses what p -- parses, but optionally surrounded with parentheses. readParen :: () => Bool -> ReadS a -> ReadS a -- | readsData p d is a parser for datatypes where each -- alternative begins with a data constructor. It parses the constructor -- and passes it to p. Parsers for various constructors can be -- constructed with readsUnary, readsUnary1 and -- readsBinary1, and combined with mappend from the -- Monoid class. readsData :: () => String -> ReadS a -> Int -> ReadS a -- | readData p is a parser for datatypes where each -- alternative begins with a data constructor. It parses the constructor -- and passes it to p. Parsers for various constructors can be -- constructed with readUnaryWith and readBinaryWith, and -- combined with '(|)' from the Alternative class. readData :: () => ReadPrec a -> ReadPrec a -- | readsUnaryWith rp n c n' matches the name of a unary -- data constructor and then parses its argument using rp. readsUnaryWith :: () => Int -> ReadS a -> String -> a -> t -> String -> ReadS t -- | readUnaryWith rp n c' matches the name of a unary data -- constructor and then parses its argument using rp. readUnaryWith :: () => ReadPrec a -> String -> a -> t -> ReadPrec t -- | readsBinaryWith rp1 rp2 n c n' matches the name of a -- binary data constructor and then parses its arguments using -- rp1 and rp2 respectively. readsBinaryWith :: () => Int -> ReadS a -> Int -> ReadS b -> String -> a -> b -> t -> String -> ReadS t -- | readBinaryWith rp1 rp2 n c' matches the name of a -- binary data constructor and then parses its arguments using -- rp1 and rp2 respectively. readBinaryWith :: () => ReadPrec a -> ReadPrec b -> String -> a -> b -> t -> ReadPrec t -- | Lifting of the Read class to unary type constructors. -- -- Both liftReadsPrec and liftReadPrec exist to match the -- interface provided in the Read type class, but it is -- recommended to implement Read1 instances using -- liftReadPrec as opposed to liftReadsPrec, since the -- former is more efficient than the latter. For example: -- --
--   instance Read1 T where
--     liftReadPrec     = ...
--     liftReadListPrec = liftReadListPrecDefault
--   
-- -- For more information, refer to the documentation for the Read -- class. class Read1 (f :: * -> *) -- | readsPrec function for an application of the type constructor -- based on readsPrec and readList functions for the -- argument type. liftReadsPrec :: Read1 f => Int -> ReadS a -> ReadS [a] -> Int -> ReadS f a -- | readList function for an application of the type constructor -- based on readsPrec and readList functions for the -- argument type. The default implementation using standard list syntax -- is correct for most types. liftReadList :: Read1 f => Int -> ReadS a -> ReadS [a] -> ReadS [f a] -- | readPrec function for an application of the type constructor -- based on readPrec and readListPrec functions for the -- argument type. liftReadPrec :: Read1 f => ReadPrec a -> ReadPrec [a] -> ReadPrec f a -- | readListPrec function for an application of the type -- constructor based on readPrec and readListPrec functions -- for the argument type. -- -- The default definition uses liftReadList. Instances that define -- liftReadPrec should also define liftReadListPrec as -- liftReadListPrecDefault. liftReadListPrec :: Read1 f => ReadPrec a -> ReadPrec [a] -> ReadPrec [f a] -- | Lift the standard readsPrec and readList functions -- through the type constructor. readsPrec1 :: (Read1 f, Read a) => Int -> ReadS f a -- | Lift the standard readPrec and readListPrec functions -- through the type constructor. readPrec1 :: (Read1 f, Read a) => ReadPrec f a -- | A possible replacement definition for the liftReadList method. -- This is only needed for Read1 instances where -- liftReadListPrec isn't defined as -- liftReadListPrecDefault. liftReadListDefault :: Read1 f => Int -> ReadS a -> ReadS [a] -> ReadS [f a] -- | A possible replacement definition for the liftReadListPrec -- method, defined using liftReadPrec. liftReadListPrecDefault :: Read1 f => ReadPrec a -> ReadPrec [a] -> ReadPrec [f a] -- | Lifting of the Read class to binary type constructors. -- -- Both liftReadsPrec2 and liftReadPrec2 exist to match the -- interface provided in the Read type class, but it is -- recommended to implement Read2 instances using -- liftReadPrec2 as opposed to liftReadsPrec2, since the -- former is more efficient than the latter. For example: -- --
--   instance Read2 T where
--     liftReadPrec2     = ...
--     liftReadListPrec2 = liftReadListPrec2Default
--   
-- -- For more information, refer to the documentation for the Read -- class. @since 4.9.0.0 class Read2 (f :: * -> * -> *) -- | readsPrec function for an application of the type constructor -- based on readsPrec and readList functions for the -- argument types. liftReadsPrec2 :: Read2 f => Int -> ReadS a -> ReadS [a] -> Int -> ReadS b -> ReadS [b] -> Int -> ReadS f a b -- | readList function for an application of the type constructor -- based on readsPrec and readList functions for the -- argument types. The default implementation using standard list syntax -- is correct for most types. liftReadList2 :: Read2 f => Int -> ReadS a -> ReadS [a] -> Int -> ReadS b -> ReadS [b] -> ReadS [f a b] -- | readPrec function for an application of the type constructor -- based on readPrec and readListPrec functions for the -- argument types. liftReadPrec2 :: Read2 f => ReadPrec a -> ReadPrec [a] -> ReadPrec b -> ReadPrec [b] -> ReadPrec f a b -- | readListPrec function for an application of the type -- constructor based on readPrec and readListPrec functions -- for the argument types. -- -- The default definition uses liftReadList2. Instances that -- define liftReadPrec2 should also define -- liftReadListPrec2 as liftReadListPrec2Default. liftReadListPrec2 :: Read2 f => ReadPrec a -> ReadPrec [a] -> ReadPrec b -> ReadPrec [b] -> ReadPrec [f a b] -- | Lift the standard readsPrec function through the type -- constructor. readsPrec2 :: (Read2 f, Read a, Read b) => Int -> ReadS f a b -- | Lift the standard readPrec function through the type -- constructor. readPrec2 :: (Read2 f, Read a, Read b) => ReadPrec f a b -- | A possible replacement definition for the liftReadList2 method. -- This is only needed for Read2 instances where -- liftReadListPrec2 isn't defined as -- liftReadListPrec2Default. liftReadList2Default :: Read2 f => Int -> ReadS a -> ReadS [a] -> Int -> ReadS b -> ReadS [b] -> ReadS [f a b] -- | A possible replacement definition for the liftReadListPrec2 -- method, defined using liftReadPrec2. liftReadListPrec2Default :: Read2 f => ReadPrec a -> ReadPrec [a] -> ReadPrec b -> ReadPrec [b] -> ReadPrec [f a b] module Read.Partial -- | The read function reads input from a string, which must be -- completely consumed by the input process. read fails with an -- error if the parse is unsuccessful, and it is therefore -- discouraged from being used in real applications. Use readMaybe -- or readEither for safe alternatives. -- --
--   >>> read "123" :: Int
--   123
--   
-- --
--   >>> read "hello" :: Int
--   *** Exception: Prelude.read: no parse
--   
read :: Read a => String -> a module Reader -- | The parameterizable reader monad. -- -- Computations are functions of a shared environment. -- -- The return function ignores the environment, while -- >>= passes the inherited environment to both -- subcomputations. type Reader r = ReaderT r Identity -- | Runs a Reader and extracts the final value from it. (The -- inverse of reader.) runReader :: () => Reader r a -> r -> a -- | Transform the value returned by a Reader. -- -- mapReader :: () => a -> b -> Reader r a -> Reader r b -- | Execute a computation in a modified environment (a specialization of -- withReaderT). -- -- withReader :: () => r' -> r -> Reader r a -> Reader r' 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 :: k -> *) (a :: k) :: forall k. () => * -> k -> * -> k -> * ReaderT :: r -> m a -> ReaderT r [runReaderT] :: ReaderT r -> r -> m a -- | Transform the computation inside a ReaderT. -- -- mapReaderT :: () => m a -> n b -> ReaderT r m a -> ReaderT r n b -- | Execute a computation in a modified environment (a more general -- version of local). -- -- withReaderT :: () => r' -> r -> ReaderT r m a -> ReaderT r' m a -- | See examples in Control.Monad.Reader. Note, the partially -- applied function type (->) r is a simple reader monad. See -- the instance declaration below. class Monad m => MonadReader r (m :: * -> *) | 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 -- | This class allows us to use magnify part of the environment, -- changing the environment supplied by many different Monad -- transformers. Unlike zoom this can change the environment of a -- deeply nested Monad transformer. -- -- Also, unlike zoom, this can be used with any valid -- Getter, but cannot be used with a Traversal or -- Fold. class (Magnified m ~ Magnified n, MonadReader b m, MonadReader a n) => Magnify (m :: * -> *) (n :: * -> *) b a | m -> b, n -> a, m a -> n, n b -> m -- | Run a monadic action in a larger environment than it was defined in, -- using a Getter. -- -- This acts like local, but can in many cases change the type of -- the environment as well. -- -- This is commonly used to lift actions in a simpler Reader -- Monad into a Monad with a larger environment type. -- -- This can be used to edit pretty much any Monad transformer -- stack with an environment in it: -- --
--   >>> (1,2) & magnify _2 (+1)
--   3
--   
-- --
--   >>> flip Reader.runReader (1,2) $ magnify _1 Reader.ask
--   1
--   
-- --
--   >>> flip Reader.runReader (1,2,[10..20]) $ magnify (_3._tail) Reader.ask
--   [11,12,13,14,15,16,17,18,19,20]
--   
-- --
--   magnify :: Getter s a -> (a -> r) -> s -> r
--   magnify :: Monoid r => Fold s a   -> (a -> r) -> s -> r
--   
-- --
--   magnify :: Monoid w                 => Getter s t -> RWS t w st c -> RWS s w st c
--   magnify :: (Monoid w, Monoid c) => Fold s a   -> RWS a w st c -> RWS s w st c
--   ...
--   
magnify :: Magnify m n b a => LensLike' Magnified m c a b -> m c -> n c infixr 2 `magnify` module Reflection class Reifies (s :: k) a | s -> a -- | Recover a value inside a reify context, given a proxy for its -- reified type. reflect :: Reifies s a => proxy s -> a -- | Reify a value at the type level, to be recovered with reflect. reify :: () => a -> forall s. Reifies s a => Proxy s -> r -> r -- | This upgraded version of reify can be used to generate a -- KnownNat suitable for use with other APIs. -- -- Available only on GHC 7.8+ -- --
--   >>> reifyNat 4 natVal
--   4
--   
-- --
--   >>> reifyNat 4 reflect
--   4
--   
reifyNat :: () => Integer -> forall (n :: Nat). KnownNat n => Proxy n -> r -> r -- | This upgraded version of reify can be used to generate a -- KnownSymbol suitable for use with other APIs. -- -- Available only on GHC 7.8+ -- --
--   >>> reifySymbol "hello" symbolVal
--   "hello"
--   
-- --
--   >>> reifySymbol "hello" reflect
--   "hello"
--   
reifySymbol :: () => String -> forall (n :: Symbol). KnownSymbol n => Proxy n -> r -> r -- | Reify a value at the type level in a Typeable-compatible -- fashion, to be recovered with reflect. -- -- This can be necessary to work around the changes to -- Data.Typeable in GHC HEAD. reifyTypeable :: Typeable a => a -> forall s. (Typeable s, Reifies s a) => Proxy s -> r -> r module Regex -- | Type of regular expressions that recognize symbols of type s -- and produce a result of type a. -- -- Regular expressions can be built using Functor, -- Applicative and Alternative instances in the following -- natural way: -- -- data RE s a data Greediness Greedy :: Greediness NonGreedy :: Greediness -- | Match and return the given symbol sym :: Eq s => s -> RE s s -- | Match and return a single symbol which satisfies the predicate psym :: () => s -> Bool -> RE s s -- | Like psym, but allows to return a computed value instead of the -- original symbol msym :: () => s -> Maybe a -> RE s a -- | Match and return any single symbol anySym :: () => RE s s -- | Match zero or more instances of the given expression, but as few of -- them as possible (i.e. non-greedily). A greedy equivalent of -- few is many. -- -- Examples: -- --
--   Text.Regex.Applicative> findFirstPrefix (few anySym  <* "b") "ababab"
--   Just ("a","abab")
--   Text.Regex.Applicative> findFirstPrefix (many anySym  <* "b") "ababab"
--   Just ("ababa","")
--   
few :: () => RE s a -> RE s [a] -- | Match zero or more instances of the given expression, which are -- combined using the given folding function. -- -- Greediness argument controls whether this regular expression -- should match as many as possible (Greedy) or as few as possible -- (NonGreedy) instances of the underlying expression. reFoldl :: () => Greediness -> b -> a -> b -> b -> RE s a -> RE s b -- | Return matched symbols as part of the return value withMatched :: () => RE s a -> RE s (a, [s]) -- | Match and return the given sequence of symbols. -- -- Note that there is an IsString instance for regular expression, -- so if you enable the OverloadedStrings language extension, -- you can write string "foo" simply as "foo". -- -- Example: -- --
--   {-# LANGUAGE OverloadedStrings #-}
--   import Text.Regex.Applicative
--   
--   number = "one" *> pure 1  <|>  "two" *> pure 2
--   
--   main = print $ "two" =~ number
--   
string :: Eq a => [a] -> RE a [a] -- | Decimal digit, i.e. '0'..'9' digit :: Num a => RE Char a -- | Hexadecimal digit i.e. '0'..'9', -- 'a'..'f', 'A'..'F'. hexDigit :: Num a => RE Char a -- | Add optional sign signed :: Num a => RE Char a -> RE Char a -- | Parse decimal number without sign. decimal :: Num a => RE Char a -- | Parse decimal number without sign. hexadecimal :: Num a => RE Char a -- | Attempt to match a string of symbols against the regular expression. -- Note that the whole string (not just some part of it) should be -- matched. -- -- Examples: -- --
--   Text.Regex.Applicative> match (sym 'a' <|> sym 'b') "a"
--   Just 'a'
--   Text.Regex.Applicative> match (sym 'a' <|> sym 'b') "ab"
--   Nothing
--   
match :: () => RE s a -> [s] -> Maybe a -- |
--   s =~ a = match a s
--   
(=~) :: () => [s] -> RE s a -> Maybe a infix 2 =~ -- | Replace matches of the regular expression with its value. -- --
--   Text.Regex.Applicative > replace ("!" <$ sym 'f' <* some (sym 'o')) "quuxfoofooooofoobarfobar"
--   "quux!!!bar!bar"
--   
replace :: () => RE s [s] -> [s] -> [s] -- | Find a string prefix which is matched by the regular expression. -- -- Of all matching prefixes, pick one using left bias (prefer the left -- part of <|> to the right part) and greediness. -- -- This is the match which a backtracking engine (such as Perl's one) -- would find first. -- -- If match is found, the rest of the input is also returned. -- -- Examples: -- --
--   Text.Regex.Applicative> findFirstPrefix ("a" <|> "ab") "abc"
--   Just ("a","bc")
--   Text.Regex.Applicative> findFirstPrefix ("ab" <|> "a") "abc"
--   Just ("ab","c")
--   Text.Regex.Applicative> findFirstPrefix "bc" "abc"
--   Nothing
--   
findFirstPrefix :: () => RE s a -> [s] -> Maybe (a, [s]) -- | Find the longest string prefix which is matched by the regular -- expression. -- -- Submatches are still determined using left bias and greediness, so -- this is different from POSIX semantics. -- -- If match is found, the rest of the input is also returned. -- -- Examples: -- --
--   Text.Regex.Applicative Data.Char> let keyword = "if"
--   Text.Regex.Applicative Data.Char> let identifier = many $ psym isAlpha
--   Text.Regex.Applicative Data.Char> let lexeme = (Left <$> keyword) <|> (Right <$> identifier)
--   Text.Regex.Applicative Data.Char> findLongestPrefix lexeme "if foo"
--   Just (Left "if"," foo")
--   Text.Regex.Applicative Data.Char> findLongestPrefix lexeme "iffoo"
--   Just (Right "iffoo","")
--   
findLongestPrefix :: () => RE s a -> [s] -> Maybe (a, [s]) -- | Find the shortest prefix (analogous to findLongestPrefix) findShortestPrefix :: () => RE s a -> [s] -> Maybe (a, [s]) -- | Find the leftmost substring that is matched by the regular expression. -- Otherwise behaves like findFirstPrefix. Returns the result -- together with the prefix and suffix of the string surrounding the -- match. findFirstInfix :: () => RE s a -> [s] -> Maybe ([s], a, [s]) -- | Find the leftmost substring that is matched by the regular expression. -- Otherwise behaves like findLongestPrefix. Returns the result -- together with the prefix and suffix of the string surrounding the -- match. findLongestInfix :: () => RE s a -> [s] -> Maybe ([s], a, [s]) -- | Find the leftmost substring that is matched by the regular expression. -- Otherwise behaves like findShortestPrefix. Returns the result -- together with the prefix and suffix of the string surrounding the -- match. findShortestInfix :: () => RE s a -> [s] -> Maybe ([s], a, [s]) module RuntimeSystem -- | Triggers an immediate major garbage collection. performGC :: IO () -- | Triggers an immediate major garbage collection. performMajorGC :: IO () -- | Triggers an immediate minor garbage collection. performMinorGC :: IO () -- | Every thread has an allocation counter that tracks how much memory has -- been allocated by the thread. The counter is initialized to zero, and -- setAllocationCounter sets the current value. The allocation -- counter counts *down*, so in the absence of a call to -- setAllocationCounter its value is the negation of the number of -- bytes of memory allocated by the thread. -- -- There are two things that you can do with this counter: -- -- -- -- Allocation accounting is accurate only to about 4Kbytes. setAllocationCounter :: Int64 -> IO () -- | Return the current value of the allocation counter for the current -- thread. getAllocationCounter :: IO Int64 -- | Enables the allocation counter to be treated as a limit for the -- current thread. When the allocation limit is enabled, if the -- allocation counter counts down below zero, the thread will be sent the -- AllocationLimitExceeded asynchronous exception. When this -- happens, the counter is reinitialised (by default to 100K, but tunable -- with the +RTS -xq option) so that it can handle the exception -- and perform any necessary clean up. If it exhausts this additional -- allowance, another AllocationLimitExceeded exception is sent, -- and so forth. Like other asynchronous exceptions, the -- AllocationLimitExceeded exception is deferred while the thread -- is inside mask or an exception handler in catch. -- -- Note that memory allocation is unrelated to live memory, also -- known as heap residency. A thread can allocate a large amount -- of memory and retain anything between none and all of it. It is better -- to think of the allocation limit as a limit on CPU time, rather -- than a limit on memory. -- -- Compared to using timeouts, allocation limits don't count time spent -- blocked or in foreign calls. enableAllocationLimit :: IO () -- | Disable allocation limit processing for the current thread. disableAllocationLimit :: IO () -- | Returns the number of Haskell threads that can run truly -- simultaneously (on separate physical processors) at any given time. To -- change this value, use setNumCapabilities. getNumCapabilities :: IO Int -- | Set the number of Haskell threads that can run truly simultaneously -- (on separate physical processors) at any given time. The number passed -- to forkOn is interpreted modulo this value. The initial value -- is given by the +RTS -N runtime flag. -- -- This is also the number of threads that will participate in parallel -- garbage collection. It is strongly recommended that the number of -- capabilities is not set larger than the number of physical processor -- cores, and it may often be beneficial to leave one or more cores free -- to avoid contention with other processes in the machine. setNumCapabilities :: Int -> IO () -- | Returns the number of sparks currently in the local spark pool numSparks :: IO Int -- | Internal function used by the RTS to run sparks. runSparks :: IO () -- | Returns the number of CPUs that the machine has getNumProcessors :: IO Int getUncaughtExceptionHandler :: IO SomeException -> IO () setUncaughtExceptionHandler :: SomeException -> IO () -> IO () -- | The event manager state. data EventManager -- | Retrieve the system event manager for the capability on which the -- calling thread is running. -- -- This function always returns Just the current thread's event -- manager when using the threaded RTS and Nothing otherwise. getSystemEventManager :: IO Maybe EventManager -- | Create a new event manager. new :: IO EventManager -- | An I/O event. data Event -- | Data is available to be read. evtRead :: Event -- | The file descriptor is ready to accept a write. evtWrite :: Event -- | Callback invoked on I/O events. type IOCallback = FdKey -> Event -> IO () -- | A file descriptor registration cookie. data FdKey -- | The lifetime of an event registration. data Lifetime -- | registerFd mgr cb fd evs lt registers interest in the events -- evs on the file descriptor fd for lifetime -- lt. cb is called for each event that occurs. Returns -- a cookie that can be handed to unregisterFd. registerFd :: EventManager -> IOCallback -> Fd -> Event -> Lifetime -> IO FdKey -- | Drop a previous file descriptor registration. unregisterFd :: EventManager -> FdKey -> IO () -- | Drop a previous file descriptor registration, without waking the event -- manager thread. The return value indicates whether the event manager -- ought to be woken. unregisterFd_ :: EventManager -> FdKey -> IO Bool -- | Close a file descriptor in a race-safe way. closeFd :: EventManager -> Fd -> IO () -> Fd -> IO () -- | The event manager state. data TimerManager -- | Callback invoked on timeout events. type TimeoutCallback = IO () -- | A timeout registration cookie. data TimeoutKey -- | Register a timeout in the given number of microseconds. The returned -- TimeoutKey can be used to later unregister or update the -- timeout. The timeout is automatically unregistered after the given -- time has passed. registerTimeout :: TimerManager -> Int -> TimeoutCallback -> IO TimeoutKey -- | Update an active timeout to fire in the given number of microseconds. updateTimeout :: TimerManager -> TimeoutKey -> Int -> IO () -- | Unregister an active timeout. unregisterTimeout :: TimerManager -> TimeoutKey -> IO () -- | Statistics about runtime activity since the start of the program. This -- is a mirror of the C struct RTSStats in RtsAPI.h data RTSStats RTSStats :: Word32 -> Word32 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> RtsTime -> RtsTime -> RtsTime -> RtsTime -> RtsTime -> RtsTime -> GCDetails -> RTSStats -- | Total number of GCs [gcs] :: RTSStats -> Word32 -- | Total number of major (oldest generation) GCs [major_gcs] :: RTSStats -> Word32 -- | Total bytes allocated [allocated_bytes] :: RTSStats -> Word64 -- | Maximum live data (including large objects + compact regions) [max_live_bytes] :: RTSStats -> Word64 -- | Maximum live data in large objects [max_large_objects_bytes] :: RTSStats -> Word64 -- | Maximum live data in compact regions [max_compact_bytes] :: RTSStats -> Word64 -- | Maximum slop [max_slop_bytes] :: RTSStats -> Word64 -- | Maximum memory in use by the RTS [max_mem_in_use_bytes] :: RTSStats -> Word64 -- | Sum of live bytes across all major GCs. Divided by major_gcs gives the -- average live data over the lifetime of the program. [cumulative_live_bytes] :: RTSStats -> Word64 -- | Sum of copied_bytes across all GCs [copied_bytes] :: RTSStats -> Word64 -- | Sum of copied_bytes across all parallel GCs [par_copied_bytes] :: RTSStats -> Word64 -- | Sum of par_max_copied_bytes across all parallel GCs. Deprecated. [cumulative_par_max_copied_bytes] :: RTSStats -> Word64 -- | Sum of par_balanced_copied bytes across all parallel GCs [cumulative_par_balanced_copied_bytes] :: RTSStats -> Word64 -- | Total CPU time used by the mutator [mutator_cpu_ns] :: RTSStats -> RtsTime -- | Total elapsed time used by the mutator [mutator_elapsed_ns] :: RTSStats -> RtsTime -- | Total CPU time used by the GC [gc_cpu_ns] :: RTSStats -> RtsTime -- | Total elapsed time used by the GC [gc_elapsed_ns] :: RTSStats -> RtsTime -- | Total CPU time (at the previous GC) [cpu_ns] :: RTSStats -> RtsTime -- | Total elapsed time (at the previous GC) [elapsed_ns] :: RTSStats -> RtsTime -- | Details about the most recent GC [gc] :: RTSStats -> GCDetails -- | Statistics about a single GC. This is a mirror of the C struct -- GCDetails in RtsAPI.h, with the field prefixed with -- gc_ to avoid collisions with RTSStats. data GCDetails GCDetails :: Word32 -> Word32 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> RtsTime -> RtsTime -> RtsTime -> GCDetails -- | The generation number of this GC [gcdetails_gen] :: GCDetails -> Word32 -- | Number of threads used in this GC [gcdetails_threads] :: GCDetails -> Word32 -- | Number of bytes allocated since the previous GC [gcdetails_allocated_bytes] :: GCDetails -> Word64 -- | Total amount of live data in the heap (incliudes large + compact data) [gcdetails_live_bytes] :: GCDetails -> Word64 -- | Total amount of live data in large objects [gcdetails_large_objects_bytes] :: GCDetails -> Word64 -- | Total amount of live data in compact regions [gcdetails_compact_bytes] :: GCDetails -> Word64 -- | Total amount of slop (wasted memory) [gcdetails_slop_bytes] :: GCDetails -> Word64 -- | Total amount of memory in use by the RTS [gcdetails_mem_in_use_bytes] :: GCDetails -> Word64 -- | Total amount of data copied during this GC [gcdetails_copied_bytes] :: GCDetails -> Word64 -- | In parallel GC, the max amount of data copied by any one thread. -- Deprecated. [gcdetails_par_max_copied_bytes] :: GCDetails -> Word64 -- | In parallel GC, the amount of balanced data copied by all threads [gcdetails_par_balanced_copied_bytes] :: GCDetails -> Word64 -- | The time elapsed during synchronisation before GC [gcdetails_sync_elapsed_ns] :: GCDetails -> RtsTime -- | The CPU time used during GC itself [gcdetails_cpu_ns] :: GCDetails -> RtsTime -- | The time elapsed during GC itself [gcdetails_elapsed_ns] :: GCDetails -> RtsTime -- | Time values from the RTS, using a fixed resolution of nanoseconds. type RtsTime = Int64 -- | Get current runtime system statistics. getRTSStats :: IO RTSStats -- | Returns whether GC stats have been enabled (with +RTS -T, for -- example). getRTSStatsEnabled :: IO Bool -- | Memory barrier implemented by the GHC rts (see SMP.h). -- storeLoadBarrier :: IO () -- -- Memory barrier implemented by the GHC rts (see SMP.h). loadLoadBarrier -- :: IO () -- -- Memory barrier implemented by the GHC rts (see SMP.h). writeBarrier :: -- IO () -- -- Memory barrier implemented by the GHC rts (see SMP.h). storeLoadBarrier :: IO () -- | Memory barrier implemented by the GHC rts (see SMP.h). loadLoadBarrier :: IO () -- | Memory barrier implemented by the GHC rts (see SMP.h). writeBarrier :: IO () module ST -- | The strict state-transformer monad. A computation of type -- ST s a transforms an internal state indexed by -- s, and returns a value of type a. The s -- parameter is either -- -- -- -- It serves to keep the internal states of different invocations of -- runST separate from each other and from invocations of -- stToIO. -- -- The >>= and >> operations are strict in the -- state (though not in values stored in the state). For example, -- --
--   runST (writeSTRef _|_ v >>= f) = _|_
--   
data ST s a -- | Return the value computed by a state transformer computation. The -- forall ensures that the internal state used by the ST -- computation is inaccessible to the rest of the program. runST :: () => forall s. () => ST s a -> a -- | Allow the result of a state transformer computation to be used -- (lazily) inside the computation. Note that if f is strict, -- fixST f = _|_. fixST :: () => a -> ST s a -> ST s a -- | RealWorld is deeply magical. It is primitive, but it -- is not unlifted (hence ptrArg). We never manipulate -- values of type RealWorld; it's only used in the type system, -- to parameterise State#. data RealWorld -- | Embed a strict state transformer in an IO action. The -- RealWorld parameter indicates that the internal state used by -- the ST computation is a special one supplied by the IO -- monad, and thus distinct from those used by invocations of -- runST. stToIO :: () => ST RealWorld a -> IO a data STE e s a -- | runSTE is the workhorse of the STE monad. Runs an STE -- computation, and also does the toplevel handling of the abortive -- throwSTE operator. The naive way to handle errors is to simply write -- handleSTE id md. runSTE does not and -- cannot (by design) handle pure or async exceptions. runSTE :: () => forall s. () => STE e s a -> Either e a -> b -> b -- | Allow the result of a state transformer computation to be used -- (lazily) inside the computation. Note that if f is strict, -- fixSTE f = _|_. fixSTE :: () => a -> STE e s a -> STE e s a -- | throwSTE is the STE sibling of throwIO, and its -- argument must match the e parameter in STE e s -- a. There is also no Exception e constraint. throwSTE -- should be thought of as an "abort" operation which is guaranteed to be -- caught/handled by runSTE. throwSTE :: () => e -> STE e s a -- | handleSTE is a flipped convenience function version of -- runSTE handleSTE :: () => Either e a -> b -> forall s. () => STE e s a -> b unsafeInterleaveSTE :: () => STE e s a -> STE e s a unsafeIOToSTE :: () => IO a -> STE e s a unsafeSTEToIO :: () => STE e s a -> IO a -- | a value of type STRef s a is a mutable variable in state -- thread s, containing a value of type a -- --
--   >>> :{
--   runST (do
--       ref <- newSTRef "hello"
--       x <- readSTRef ref
--       writeSTRef ref (x ++ "world")
--       readSTRef ref )
--   :}
--   "helloworld"
--   
data STRef s a -- | Build a new STRef in the current state thread newSTRef :: () => a -> ST s STRef s a -- | Read the value of an STRef readSTRef :: () => STRef s a -> ST s a -- | Write a new value into an STRef writeSTRef :: () => STRef s a -> a -> ST s () -- | Mutate the contents of an STRef. -- --
--   >>> :{
--   runST (do
--       ref <- newSTRef ""
--       modifySTRef ref (const "world")
--       modifySTRef ref (++ "!")
--       modifySTRef ref ("Hello, " ++)
--       readSTRef ref )
--   :}
--   "Hello, world!"
--   
-- -- Be warned that modifySTRef does not apply the function -- strictly. This means if the program calls modifySTRef many -- times, but seldomly uses the value, thunks will pile up in memory -- resulting in a space leak. This is a common mistake made when using an -- STRef as a counter. For example, the following will leak memory and -- may produce a stack overflow: -- --
--   >>> import Control.Monad (replicateM_)
--   
--   >>> :{
--   print (runST (do
--       ref <- newSTRef 0
--       replicateM_ 1000 $ modifySTRef ref (+1)
--       readSTRef ref ))
--   :}
--   1000
--   
-- -- To avoid this problem, use modifySTRef' instead. modifySTRef :: () => STRef s a -> a -> a -> ST s () -- | Strict version of modifySTRef modifySTRef' :: () => STRef s a -> a -> a -> ST s () module Semigroup -- | The class of semigroups (types with an associative binary operation). -- -- Instances should satisfy the associativity law: -- -- class Semigroup a -- | An associative operation. (<>) :: Semigroup a => a -> a -> a -- | Reduce a non-empty list with <> -- -- The default definition should be sufficient, but this can be -- overridden for efficiency. sconcat :: Semigroup a => NonEmpty a -> a -- | Repeat a value n times. -- -- Given that this works on a Semigroup it is allowed to fail if -- you request 0 or fewer repetitions, and the default definition will do -- so. -- -- By making this a member of the class, idempotent semigroups and -- monoids can upgrade this to execute in O(1) by picking -- stimes = stimesIdempotent or stimes = -- stimesIdempotentMonoid respectively. stimes :: (Semigroup a, Integral b) => b -> a -> a -- | Generically generate a Semigroup (<>) operation -- for any type implementing Generic. This operation will append -- two values by point-wise appending their component fields. It is only -- defined for product types. -- --
--   gmappend a (gmappend b c) = gmappend (gmappend a b) c
--   
gmappend :: (Generic a, GSemigroup Rep a) => a -> a -> a -- | Use Option (First a) to get the behavior of -- First from Data.Monoid. newtype First a First :: a -> First a [getFirst] :: First a -> a -- | Use Option (Last a) to get the behavior of -- Last from Data.Monoid newtype Last a Last :: a -> Last a [getLast] :: Last a -> a -- | 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 -- | This lets you use a difference list of a Semigroup as a -- Monoid. diff :: Semigroup m => m -> Endo m -- | A generalization of cycle to an arbitrary Semigroup. May -- fail to terminate for some values in some semigroups. cycle1 :: Semigroup m => m -> m module Semigroupoid -- | Category sans id class Semigroupoid (c :: k -> k -> *) o :: Semigroupoid c => c j k1 -> c i j -> c i k1 newtype Semi m (a :: k) (b :: k1) :: forall k k1. () => * -> k -> k1 -> * Semi :: m -> Semi m [getSemi] :: Semi m -> m newtype Dual (k2 :: k1 -> k -> *) (a :: k) (b :: k1) :: forall k k1. () => k1 -> k -> * -> k -> k1 -> * Dual :: k2 b a -> Dual [getDual] :: Dual -> k2 b a module Semilattice -- | A join semilattice is an idempotent commutative semigroup. class Join s -- | The join operation. -- -- Laws: -- -- Idempotence: -- --
--   x \/ x = x
--   
-- -- Associativity: -- --
--   a \/ (b \/ c) = (a \/ b) \/ c
--   
-- -- Commutativity: -- --
--   a \/ b = b \/ a
--   
-- -- Additionally, if s has a Lower bound, then -- lowerBound must be its identity: -- --
--   lowerBound \/ a = a
--   a \/ lowerBound = a
--   
-- -- If s has an Upper bound, then upperBound -- must be its absorbing element: -- --
--   upperBound \/ a = upperBound
--   a \/ upperBound = upperBound
--   
(\/) :: Join s => s -> s -> s -- | A meet semilattice is an idempotent commutative semigroup. class Meet s -- | The meet operation. -- -- Laws: -- -- Idempotence: -- --
--   x /\ x = x
--   
-- -- Associativity: -- --
--   a /\ (b /\ c) = (a /\ b) /\ c
--   
-- -- Commutativity: -- --
--   a /\ b = b /\ a
--   
-- -- Additionally, if s has an Upper bound, then -- upperBound must be its identity: -- --
--   upperBound /\ a = a
--   a /\ upperBound = a
--   
-- -- If s has a Lower bound, then lowerBound -- must be its absorbing element: -- --
--   lowerBound /\ a = lowerBound
--   a /\ lowerBound = lowerBound
--   
(/\) :: Meet s => s -> s -> s -- | A Join- and Meet-semilattice for any total -- Ordering. newtype Order a Order :: a -> Order a [getOrder] :: Order a -> a module Sequence -- | A Seq is isomorphic to a ViewL -- --
--   viewl m ≡ m ^. viewL
--   
-- --
--   >>> Seq.fromList [a,b,c] ^. viewL
--   a :< fromList [b,c]
--   
-- --
--   >>> Seq.empty ^. viewL
--   EmptyL
--   
-- --
--   >>> EmptyL ^. from viewL
--   fromList []
--   
-- --
--   >>> review viewL $ a Seq.:< fromList [b,c]
--   fromList [a,b,c]
--   
viewL :: (Profunctor p, Functor f) => p ViewL a f ViewL b -> p Seq a f Seq b -- | A Seq is isomorphic to a ViewR -- --
--   viewr m ≡ m ^. viewR
--   
-- --
--   >>> Seq.fromList [a,b,c] ^. viewR
--   fromList [a,b] :> c
--   
-- --
--   >>> Seq.empty ^. viewR
--   EmptyR
--   
-- --
--   >>> EmptyR ^. from viewR
--   fromList []
--   
-- --
--   >>> review viewR $ fromList [a,b] Seq.:> c
--   fromList [a,b,c]
--   
viewR :: (Profunctor p, Functor f) => p ViewR a f ViewR b -> p Seq a f Seq b -- | Traverse all the elements numbered from i to j of a -- Seq -- --
--   >>> fromList [a,b,c,d,e] & sliced 1 3 %~ f
--   fromList [a,f b,f c,d,e]
--   
sliced :: () => Int -> Int -> IndexedTraversal' Int Seq a a -- | Traverse the first n elements of a Seq -- --
--   >>> fromList [a,b,c,d,e] ^.. slicedTo 2
--   [a,b]
--   
-- --
--   >>> fromList [a,b,c,d,e] & slicedTo 2 %~ f
--   fromList [f a,f b,c,d,e]
--   
-- --
--   >>> fromList [a,b,c,d,e] & slicedTo 10 .~ x
--   fromList [x,x,x,x,x]
--   
slicedTo :: () => Int -> IndexedTraversal' Int Seq a a -- | Traverse all but the first n elements of a Seq -- --
--   >>> fromList [a,b,c,d,e] ^.. slicedFrom 2
--   [c,d,e]
--   
-- --
--   >>> fromList [a,b,c,d,e] & slicedFrom 2 %~ f
--   fromList [a,b,f c,f d,f e]
--   
-- --
--   >>> fromList [a,b,c,d,e] & slicedFrom 10 .~ x
--   fromList [a,b,c,d,e]
--   
slicedFrom :: () => Int -> IndexedTraversal' Int Seq a a -- | Construct a Seq from a Getter, Fold, -- Traversal, Lens or Iso. -- --
--   >>> seqOf folded ["hello","world"]
--   fromList ["hello","world"]
--   
-- --
--   >>> seqOf (folded._2) [("hello",1),("world",2),("!!!",3)]
--   fromList [1,2,3]
--   
-- --
--   seqOf :: Getter s a     -> s -> Seq a
--   seqOf :: Fold s a       -> s -> Seq a
--   seqOf :: Iso' s a       -> s -> Seq a
--   seqOf :: Lens' s a      -> s -> Seq a
--   seqOf :: Traversal' s a -> s -> Seq a
--   
seqOf :: () => Getting Seq a s a -> s -> Seq a module Serialise -- | Serialise a Haskell value to an external binary representation. -- -- The output is represented as a lazy ByteString and is -- constructed incrementally. serialise :: Serialise a => a -> ByteString -- | Serialise a Haskell value to an external binary representation. -- -- The output is represented as a Builder and is constructed -- incrementally. The representation as a Builder allows efficient -- concatenation with other data. serialiseIncremental :: Serialise a => a -> Builder -- | Deserialise a Haskell value from the external binary representation, -- or get back a DeserialiseFailure. deserialiseOrFail :: Serialise a => ByteString -> Either DeserialiseFailure a -- | Deserialise a Haskell value from the external binary representation. -- -- This allows input data to be provided incrementally, rather -- than all in one go. It also gives an explicit representation of -- deserialisation errors. -- -- Note that the incremental behaviour is only for the input data, not -- the output value: the final deserialised value is constructed and -- returned as a whole, not incrementally. deserialiseIncremental :: Serialise a => ST s IDecode s a -- | An exception type that may be returned (by pure functions) or thrown -- (by IO actions) that fail to deserialise a given input. data DeserialiseFailure DeserialiseFailure :: ByteOffset -> String -> DeserialiseFailure -- | Simple alias for Int64, used to make types more -- descriptive. type ByteOffset = Int64 -- | An Incremental decoder, used to represent the result of attempting to -- run a decoder over a given input, and return a value of type -- a. data IDecode s a -- | The decoder has consumed the available input and needs more to -- continue. Provide Just if more input is available and -- Nothing otherwise, and you will get a new -- IDecode. Partial :: Maybe ByteString -> ST s IDecode s a -> IDecode s a -- | The decoder has successfully finished. Except for the output value you -- also get any unused input as well as the number of bytes consumed. Done :: !ByteString -> {-# UNPACK #-} !ByteOffset -> a -> IDecode s a -- | The decoder ran into an error. The decoder either used -- fail or was not provided enough input. Contains any -- unconsumed input, the number of bytes consumed, and a -- DeserialiseFailure exception describing the reason why -- the failure occurred. Fail :: !ByteString -> {-# UNPACK #-} !ByteOffset -> DeserialiseFailure -> IDecode s a -- | Types that are instances of the Serialise class allow -- values to be quickly encoded or decoded directly to a CBOR -- representation, for object transmission or storage. class Serialise a -- | Definition for encoding a given type into a binary representation, -- using the Encoding Monoid. encode :: Serialise a => a -> Encoding -- | Definition of a given Decoder for a type. decode :: Serialise a => Decoder s a module Set -- | This Setter can be used to change the type of a Set by -- mapping the elements to new values. -- -- Sadly, you can't create a valid Traversal for a Set, but -- you can manipulate it by reading using folded and reindexing it -- via setmapped. -- --
--   >>> over setmapped (+1) (fromList [1,2,3,4])
--   fromList [2,3,4,5]
--   
setmapped :: Ord j => IndexPreservingSetter Set i Set j i j -- | Construct a set from a Getter, Fold, Traversal, -- Lens or Iso. -- --
--   >>> setOf folded ["hello","world"]
--   fromList ["hello","world"]
--   
-- --
--   >>> setOf (folded._2) [("hello",1),("world",2),("!!!",3)]
--   fromList [1,2,3]
--   
-- --
--   setOf ::          Getter s a     -> s -> Set a
--   setOf :: Ord a => Fold s a       -> s -> Set a
--   setOf ::          Iso' s a       -> s -> Set a
--   setOf ::          Lens' s a      -> s -> Set a
--   setOf :: Ord a => Traversal' s a -> s -> Set a
--   
setOf :: () => Getting Set a s a -> s -> Set a module Set.Hash -- | Construct a set from a Getter, Fold, Traversal, -- Lens or Iso. -- --
--   setOf :: Hashable a         => Getter s a     -> s -> HashSet a
--   setOf :: (Eq a, Hashable a) => Fold s a       -> s -> HashSet a
--   setOf :: Hashable a         => Iso' s a       -> s -> HashSet a
--   setOf :: Hashable a         => Lens' s a      -> s -> HashSet a
--   setOf :: (Eq a, Hashable a) => Traversal' s a -> s -> HashSet a
--   
setOf :: Hashable a => Getting HashSet a s a -> s -> HashSet a module Set.Int -- | IntSet isn't Foldable, but this Fold can be used to access the -- members of an IntSet. -- --
--   >>> sumOf members $ setOf folded [1,2,3,4]
--   10
--   
members :: Fold IntSet Int -- | This Setter can be used to change the contents of an -- IntSet by mapping the elements to new values. -- -- Sadly, you can't create a valid Traversal for a Set, -- because the number of elements might change but you can manipulate it -- by reading using folded and reindexing it via setmapped. -- --
--   >>> over setmapped (+1) (fromList [1,2,3,4])
--   fromList [2,3,4,5]
--   
setmapped :: IndexPreservingSetter' IntSet Int -- | Construct an IntSet from a Getter, Fold, -- Traversal, Lens or Iso. -- --
--   >>> setOf folded [1,2,3,4]
--   fromList [1,2,3,4]
--   
-- --
--   >>> setOf (folded._2) [("hello",1),("world",2),("!!!",3)]
--   fromList [1,2,3]
--   
-- --
--   setOf :: Getter s Int     -> s -> IntSet
--   setOf :: Fold s Int       -> s -> IntSet
--   setOf :: Iso' s Int       -> s -> IntSet
--   setOf :: Lens' s Int      -> s -> IntSet
--   setOf :: Traversal' s Int -> s -> IntSet
--   
setOf :: () => Getting IntSet s Int -> s -> IntSet module Show -- | Conversion of values to readable Strings. -- -- Derived instances of Show have the following properties, which -- are compatible with derived instances of Read: -- -- -- -- For example, given the declarations -- --
--   infixr 5 :^:
--   data Tree a =  Leaf a  |  Tree a :^: Tree a
--   
-- -- the derived instance of Show is equivalent to -- --
--   instance (Show a) => Show (Tree a) where
--   
--          showsPrec d (Leaf m) = showParen (d > app_prec) $
--               showString "Leaf " . showsPrec (app_prec+1) m
--            where app_prec = 10
--   
--          showsPrec d (u :^: v) = showParen (d > up_prec) $
--               showsPrec (up_prec+1) u .
--               showString " :^: "      .
--               showsPrec (up_prec+1) v
--            where up_prec = 5
--   
-- -- Note that right-associativity of :^: is ignored. For example, -- -- class Show a -- | Convert a value to a readable String. -- -- showsPrec should satisfy the law -- --
--   showsPrec d x r ++ s  ==  showsPrec d x (r ++ s)
--   
-- -- Derived instances of Read and Show satisfy the -- following: -- -- -- -- That is, readsPrec parses the string produced by -- showsPrec, and delivers the value that showsPrec started -- with. showsPrec :: Show a => Int -> a -> ShowS -- | A specialised variant of showsPrec, using precedence context -- zero, and returning an ordinary String. show :: Show a => a -> String -- | The method showList is provided to allow the programmer to give -- a specialised way of showing lists of values. For example, this is -- used by the predefined Show instance of the Char type, -- where values of type String should be shown in double quotes, -- rather than between square brackets. showList :: Show a => [a] -> ShowS -- | The shows functions return a function that prepends the -- output String to an existing String. This allows -- constant-time concatenation of results using function composition. type ShowS = String -> String -- | equivalent to showsPrec with a precedence of 0. shows :: Show a => a -> ShowS -- | utility function that surrounds the inner show function with -- parentheses when the Bool parameter is True. showParen :: Bool -> ShowS -> ShowS -- | Show a list (using square brackets and commas), given a function for -- showing elements. showListWith :: () => a -> ShowS -> [a] -> ShowS -- | showsUnaryWith sp n d x produces the string -- representation of a unary data constructor with name n and -- argument x, in precedence context d. showsUnaryWith :: () => Int -> a -> ShowS -> String -> Int -> a -> ShowS -- | showsBinaryWith sp1 sp2 n d x y produces the string -- representation of a binary data constructor with name n and -- arguments x and y, in precedence context d. showsBinaryWith :: () => Int -> a -> ShowS -> Int -> b -> ShowS -> String -> Int -> a -> b -> ShowS -- | Lifting of the Show class to unary type constructors. class Show1 (f :: * -> *) -- | showsPrec function for an application of the type constructor -- based on showsPrec and showList functions for the -- argument type. liftShowsPrec :: Show1 f => Int -> a -> ShowS -> [a] -> ShowS -> Int -> f a -> ShowS -- | showList function for an application of the type constructor -- based on showsPrec and showList functions for the -- argument type. The default implementation using standard list syntax -- is correct for most types. liftShowList :: Show1 f => Int -> a -> ShowS -> [a] -> ShowS -> [f a] -> ShowS -- | Lift the standard showsPrec and showList functions -- through the type constructor. showsPrec1 :: (Show1 f, Show a) => Int -> f a -> ShowS -- | A sensible default liftShowsPrec implementation for -- Generic1 instances. liftShowsPrecDefault :: (GShow1 NonV4 Rep1 f, Generic1 f) => Int -> a -> ShowS -> [a] -> ShowS -> Int -> f a -> ShowS -- | Lifting of the Show class to binary type constructors. class Show2 (f :: * -> * -> *) -- | showsPrec function for an application of the type constructor -- based on showsPrec and showList functions for the -- argument types. liftShowsPrec2 :: Show2 f => Int -> a -> ShowS -> [a] -> ShowS -> Int -> b -> ShowS -> [b] -> ShowS -> Int -> f a b -> ShowS -- | showList function for an application of the type constructor -- based on showsPrec and showList functions for the -- argument types. The default implementation using standard list syntax -- is correct for most types. liftShowList2 :: Show2 f => Int -> a -> ShowS -> [a] -> ShowS -> Int -> b -> ShowS -> [b] -> ShowS -> [f a b] -> ShowS -- | Lift the standard showsPrec function through the type -- constructor. showsPrec2 :: (Show2 f, Show a, Show b) => Int -> f a b -> ShowS module Socket -- | A socket data type. Sockets are not GCed unless they are closed -- by close. data Socket MkSocket :: CInt -> Family -> SocketType -> ProtocolNumber -> MVar SocketStatus -> Socket -- | Address families. -- -- A constructor being present here does not mean it is supported by the -- operating system: see isSupportedFamily. data Family AF_UNSPEC :: Family AF_UNIX :: Family AF_INET :: Family AF_INET6 :: Family AF_IMPLINK :: Family AF_PUP :: Family AF_CHAOS :: Family AF_NS :: Family AF_NBS :: Family AF_ECMA :: Family AF_DATAKIT :: Family AF_CCITT :: Family AF_SNA :: Family AF_DECnet :: Family AF_DLI :: Family AF_LAT :: Family AF_HYLINK :: Family AF_APPLETALK :: Family AF_ROUTE :: Family AF_NETBIOS :: Family AF_NIT :: Family AF_802 :: Family AF_ISO :: Family AF_OSI :: Family AF_NETMAN :: Family AF_X25 :: Family AF_AX25 :: Family AF_OSINET :: Family AF_GOSSIP :: Family AF_IPX :: Family Pseudo_AF_XTP :: Family AF_CTF :: Family AF_WAN :: Family AF_SDL :: Family AF_NETWARE :: Family AF_NDD :: Family AF_INTF :: Family AF_COIP :: Family AF_CNT :: Family Pseudo_AF_RTIP :: Family Pseudo_AF_PIP :: Family AF_SIP :: Family AF_ISDN :: Family Pseudo_AF_KEY :: Family AF_NATM :: Family AF_ARP :: Family Pseudo_AF_HDRCMPLT :: Family AF_ENCAP :: Family AF_LINK :: Family AF_RAW :: Family AF_RIF :: Family AF_NETROM :: Family AF_BRIDGE :: Family AF_ATMPVC :: Family AF_ROSE :: Family AF_NETBEUI :: Family AF_SECURITY :: Family AF_PACKET :: Family AF_ASH :: Family AF_ECONET :: Family AF_ATMSVC :: Family AF_IRDA :: Family AF_PPPOX :: Family AF_WANPIPE :: Family AF_BLUETOOTH :: Family AF_CAN :: Family -- | Does the AF_ constant corresponding to the given family exist on this -- system? isSupportedFamily :: Family -> Bool -- | Socket Types. -- -- The existence of a constructor does not necessarily imply that that -- socket type is supported on your system: see -- isSupportedSocketType. data SocketType -- | 0, used in getAddrInfo hints, for example NoSocketType :: SocketType -- | SOCK_STREAM Stream :: SocketType -- | SOCK_DGRAM Datagram :: SocketType -- | SOCK_RAW Raw :: SocketType -- | SOCK_RDM RDM :: SocketType -- | SOCK_SEQPACKET SeqPacket :: SocketType -- | Does the SOCK_ constant corresponding to the given SocketType exist on -- this system? isSupportedSocketType :: SocketType -> Bool -- | The existence of a constructor does not necessarily imply that that -- socket address type is supported on your system: see -- isSupportedSockAddr. data SockAddr SockAddrInet :: PortNumber -> HostAddress -> SockAddr SockAddrInet6 :: PortNumber -> FlowInfo -> HostAddress6 -> ScopeID -> SockAddr SockAddrUnix :: String -> SockAddr SockAddrCan :: Int32 -> SockAddr -- | Is the socket address type supported on this system? isSupportedSockAddr :: SockAddr -> Bool -- | The status of the socket as determined by this library, not -- necessarily reflecting the state of the connection itself. -- -- For example, the Closed status is applied when the -- close function is called. data SocketStatus -- | Newly created, unconnected socket NotConnected :: SocketStatus -- | Bound, via bind Bound :: SocketStatus -- | Listening, via listen Listening :: SocketStatus -- | Connected or accepted, via connect or accept Connected :: SocketStatus -- | Is now a Handle (via socketToHandle), don't touch ConvertedToHandle :: SocketStatus -- | Closed was closed by close Closed :: SocketStatus -- | The raw network byte order number is read using host byte order. -- Therefore on little-endian architectures the byte order is swapped. -- For example 127.0.0.1 is represented as 0x0100007f -- on little-endian hosts and as 0x7f000001 on big-endian hosts. -- -- For direct manipulation prefer hostAddressToTuple and -- tupleToHostAddress. type HostAddress = Word32 -- | The IPv4 wild card address. iNADDR_ANY :: HostAddress -- | Converts HostAddress to representation-independent IPv4 -- quadruple. For example for 127.0.0.1 the function will return -- (0x7f, 0, 0, 1) regardless of host endianness. hostAddressToTuple :: HostAddress -> (Word8, Word8, Word8, Word8) -- | Converts IPv4 quadruple to HostAddress. tupleToHostAddress :: (Word8, Word8, Word8, Word8) -> HostAddress -- | Independent of endianness. For example ::1 is stored as -- (0, 0, 0, 1). -- -- For direct manipulation prefer hostAddress6ToTuple and -- tupleToHostAddress6. type HostAddress6 = (Word32, Word32, Word32, Word32) -- | The IPv6 wild card address. iN6ADDR_ANY :: HostAddress6 hostAddress6ToTuple :: HostAddress6 -> (Word16, Word16, Word16, Word16, Word16, Word16, Word16, Word16) tupleToHostAddress6 :: (Word16, Word16, Word16, Word16, Word16, Word16, Word16, Word16) -> HostAddress6 type FlowInfo = Word32 type ScopeID = Word32 -- | Converts the from host byte order to network byte order. htonl :: Word32 -> Word32 -- | Converts the from network byte order to host byte order. ntohl :: Word32 -> Word32 data ShutdownCmd ShutdownReceive :: ShutdownCmd ShutdownSend :: ShutdownCmd ShutdownBoth :: ShutdownCmd type ProtocolNumber = CInt -- | This is the default protocol for a given service. defaultProtocol :: ProtocolNumber -- | Use the Num instance (i.e. use a literal) to create a -- PortNumber value with the correct network-byte-ordering. You -- should not use the PortNum constructor. It will be removed in the next -- release. -- --
--   >>> 1 :: PortNumber
--   1
--   
--   >>> read "1" :: PortNumber
--   1
--   
data PortNumber aNY_PORT :: PortNumber -- | Either a host name e.g., "haskell.org" or a numeric host -- address string consisting of a dotted decimal IPv4 address or an IPv6 -- address e.g., "192.168.0.1". type HostName = String type ServiceName = String data AddrInfo AddrInfo :: [AddrInfoFlag] -> Family -> SocketType -> ProtocolNumber -> SockAddr -> Maybe String -> AddrInfo [addrFlags] :: AddrInfo -> [AddrInfoFlag] [addrFamily] :: AddrInfo -> Family [addrSocketType] :: AddrInfo -> SocketType [addrProtocol] :: AddrInfo -> ProtocolNumber [addrAddress] :: AddrInfo -> SockAddr [addrCanonName] :: AddrInfo -> Maybe String -- | Flags that control the querying behaviour of getAddrInfo. For -- more information, see -- https://tools.ietf.org/html/rfc3493#page-25 data AddrInfoFlag -- | The list of returned AddrInfo values will only contain IPv4 -- addresses if the local system has at least one IPv4 interface -- configured, and likewise for IPv6. (Only some platforms support this.) AI_ADDRCONFIG :: AddrInfoFlag -- | If AI_ALL is specified, return all matching IPv6 and IPv4 -- addresses. Otherwise, this flag has no effect. (Only some platforms -- support this.) AI_ALL :: AddrInfoFlag -- | The addrCanonName field of the first returned AddrInfo -- will contain the "canonical name" of the host. AI_CANONNAME :: AddrInfoFlag -- | The HostName argument must be a numeric address in -- string form, and network name lookups will not be attempted. AI_NUMERICHOST :: AddrInfoFlag -- | The ServiceName argument must be a port number in string -- form, and service name lookups will not be attempted. (Only some -- platforms support this.) AI_NUMERICSERV :: AddrInfoFlag -- | If no HostName value is provided, the network address in each -- SockAddr will be left as a "wild card". This is useful for -- server applications that will accept connections from any client. AI_PASSIVE :: AddrInfoFlag -- | If an IPv6 lookup is performed, and no IPv6 addresses are found, -- IPv6-mapped IPv4 addresses will be returned. (Only some platforms -- support this.) AI_V4MAPPED :: AddrInfoFlag -- | Indicate whether the given AddrInfoFlag will have any effect on -- this system. addrInfoFlagImplemented :: AddrInfoFlag -> Bool -- | Default hints for address lookup with getAddrInfo. The values -- of the addrAddress and addrCanonName fields are -- undefined, and are never inspected by getAddrInfo. -- --
--   >>> addrFlags defaultHints
--   []
--   
--   >>> addrFamily defaultHints
--   AF_UNSPEC
--   
--   >>> addrSocketType defaultHints
--   NoSocketType
--   
--   >>> addrProtocol defaultHints
--   0
--   
defaultHints :: AddrInfo -- | Resolve a host or service name to one or more addresses. The -- AddrInfo values that this function returns contain -- SockAddr values that you can pass directly to connect or -- bind. -- -- This function is protocol independent. It can return both IPv4 and -- IPv6 address information. -- -- The AddrInfo argument specifies the preferred query behaviour, -- socket options, or protocol. You can override these conveniently using -- Haskell's record update syntax on defaultHints, for example as -- follows: -- --
--   >>> let hints = defaultHints { addrFlags = [AI_NUMERICHOST], addrSocketType = Stream }
--   
-- -- You must provide a Just value for at least one of the -- HostName or ServiceName arguments. HostName can -- be either a numeric network address (dotted quad for IPv4, -- colon-separated hex for IPv6) or a hostname. In the latter case, its -- addresses will be looked up unless AI_NUMERICHOST is specified -- as a hint. If you do not provide a HostName value and do -- not set AI_PASSIVE as a hint, network addresses in the result -- will contain the address of the loopback interface. -- -- If the query fails, this function throws an IO exception instead of -- returning an empty list. Otherwise, it returns a non-empty list of -- AddrInfo values. -- -- There are several reasons why a query might result in several values. -- For example, the queried-for host could be multihomed, or the service -- might be available via several protocols. -- -- Note: the order of arguments is slightly different to that defined for -- getaddrinfo in RFC 2553. The AddrInfo parameter comes -- first to make partial application easier. -- --
--   >>> addr:_ <- getAddrInfo (Just hints) (Just "127.0.0.1") (Just "http")
--   
--   >>> addrAddress addr
--   127.0.0.1:80
--   
getAddrInfo :: Maybe AddrInfo -> Maybe HostName -> Maybe ServiceName -> IO [AddrInfo] -- | Flags that control the querying behaviour of getNameInfo. For -- more information, see -- https://tools.ietf.org/html/rfc3493#page-30 data NameInfoFlag -- | Resolve a datagram-based service name. This is required only for the -- few protocols that have different port numbers for their -- datagram-based versions than for their stream-based versions. NI_DGRAM :: NameInfoFlag -- | If the hostname cannot be looked up, an IO error is thrown. NI_NAMEREQD :: NameInfoFlag -- | If a host is local, return only the hostname part of the FQDN. NI_NOFQDN :: NameInfoFlag -- | The name of the host is not looked up. Instead, a numeric -- representation of the host's address is returned. For an IPv4 address, -- this will be a dotted-quad string. For IPv6, it will be -- colon-separated hexadecimal. NI_NUMERICHOST :: NameInfoFlag -- | The name of the service is not looked up. Instead, a numeric -- representation of the service is returned. NI_NUMERICSERV :: NameInfoFlag -- | Resolve an address to a host or service name. This function is -- protocol independent. The list of NameInfoFlag values controls -- query behaviour. -- -- If a host or service's name cannot be looked up, then the numeric form -- of the address or service will be returned. -- -- If the query fails, this function throws an IO exception. -- -- Example: (hostName, _) <- getNameInfo [] True False myAddress -- getNameInfo :: [NameInfoFlag] -> Bool -> Bool -> SockAddr -> IO (Maybe HostName, Maybe ServiceName) -- | Create a new socket using the given address family, socket type and -- protocol number. The address family is usually AF_INET, -- AF_INET6, or AF_UNIX. The socket type is usually -- Stream or Datagram. The protocol number is usually -- defaultProtocol. If AF_INET6 is used and the socket type -- is Stream or Datagram, the IPv6Only socket option -- is set to 0 so that both IPv4 and IPv6 can be handled with one socket. -- --
--   >>> let hints = defaultHints { addrFlags = [AI_NUMERICHOST, AI_NUMERICSERV], addrSocketType = Stream }
--   
--   >>> addr:_ <- getAddrInfo (Just hints) (Just "127.0.0.1") (Just "5000")
--   
--   >>> sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
--   
--   >>> bind sock (addrAddress addr)
--   
--   >>> getSocketName sock
--   127.0.0.1:5000
--   
socket :: Family -> SocketType -> ProtocolNumber -> IO Socket -- | Build a pair of connected socket objects using the given address -- family, socket type, and protocol number. Address family, socket type, -- and protocol number are as for the socket function above. -- Availability: Unix. socketPair :: Family -> SocketType -> ProtocolNumber -> IO (Socket, Socket) -- | Connect to a remote socket at address. connect :: Socket -> SockAddr -> IO () -- | Bind the socket to an address. The socket must not already be bound. -- The Family passed to bind must be the same as that -- passed to socket. If the special port number defaultPort -- is passed then the system assigns the next available use port. bind :: Socket -> SockAddr -> IO () -- | Listen for connections made to the socket. The second argument -- specifies the maximum number of queued connections and should be at -- least 1; the maximum value is system-dependent (usually 5). listen :: Socket -> Int -> IO () -- | Accept a connection. The socket must be bound to an address and -- listening for connections. The return value is a pair (conn, -- address) where conn is a new socket object usable to -- send and receive data on the connection, and address is the -- address bound to the socket on the other end of the connection. accept :: Socket -> IO (Socket, SockAddr) getPeerName :: Socket -> IO SockAddr getSocketName :: Socket -> IO SockAddr -- | Returns the processID, userID and groupID of the socket's peer. -- -- Only available on platforms that support SO_PEERCRED or GETPEEREID(3) -- on domain sockets. GETPEEREID(3) returns userID and groupID. processID -- is always 0. getPeerCred :: Socket -> IO (CUInt, CUInt, CUInt) -- | Getting the port of socket. IOError is thrown if a port is not -- available. socketPort :: Socket -> IO PortNumber -- | Turns a Socket into an Handle. By default, the new handle is -- unbuffered. Use hSetBuffering to change the buffering. -- -- Note that since a Handle is automatically closed by a finalizer -- when it is no longer referenced, you should avoid doing any more -- operations on the Socket after calling socketToHandle. -- To close the Socket after socketToHandle, call -- hClose on the Handle. socketToHandle :: Socket -> IOMode -> IO Handle -- | Send data to the socket. The socket must be connected to a remote -- socket. Returns the number of bytes sent. Applications are responsible -- for ensuring that all data has been sent. -- -- Sending data to closed socket may lead to undefined behaviour. send :: Socket -> ByteString -> IO Int -- | Send data to the socket. The recipient can be specified explicitly, so -- the socket need not be in a connected state. Returns the number of -- bytes sent. Applications are responsible for ensuring that all data -- has been sent. -- -- Sending data to closed socket may lead to undefined behaviour. sendTo :: Socket -> ByteString -> SockAddr -> IO Int -- | Send data to the socket. The socket must be connected to a remote -- socket. Unlike send, this function continues to send data until -- either all data has been sent or an error occurs. On error, an -- exception is raised, and there is no way to determine how much data, -- if any, was successfully sent. -- -- Sending data to closed socket may lead to undefined behaviour. sendAll :: Socket -> ByteString -> IO () -- | Send data to the socket. The recipient can be specified explicitly, so -- the socket need not be in a connected state. Unlike sendTo, -- this function continues to send data until either all data has been -- sent or an error occurs. On error, an exception is raised, and there -- is no way to determine how much data, if any, was successfully sent. -- -- Sending data to closed socket may lead to undefined behaviour. sendAllTo :: Socket -> ByteString -> SockAddr -> IO () -- | Send data to the socket. The socket must be connected to a remote -- socket. Returns the number of bytes sent. Applications are responsible -- for ensuring that all data has been sent. -- -- Sending data to closed socket may lead to undefined behaviour. sendBuf :: Socket -> Ptr Word8 -> Int -> IO Int -- | Send data to the socket. The recipient can be specified explicitly, so -- the socket need not be in a connected state. Returns the number of -- bytes sent. Applications are responsible for ensuring that all data -- has been sent. sendBufTo :: () => Socket -> Ptr a -> Int -> SockAddr -> IO Int sendFd :: Socket -> CInt -> IO () -- | Send data to the socket. The socket must be in a connected state. The -- data is sent as if the parts have been concatenated. This function -- continues to send data until either all data has been sent or an error -- occurs. On error, an exception is raised, and there is no way to -- determine how much data, if any, was successfully sent. -- -- Sending data to closed socket may lead to undefined behaviour. sendMany :: Socket -> [ByteString] -> IO () -- | Send data to the socket. The recipient can be specified explicitly, so -- the socket need not be in a connected state. The data is sent as if -- the parts have been concatenated. This function continues to send data -- until either all data has been sent or an error occurs. On error, an -- exception is raised, and there is no way to determine how much data, -- if any, was successfully sent. -- -- Sending data to closed socket may lead to undefined behaviour. sendManyTo :: Socket -> [ByteString] -> SockAddr -> IO () -- | Receive data from the socket. The socket must be in a connected state. -- This function may return fewer bytes than specified. If the message is -- longer than the specified length, it may be discarded depending on the -- type of socket. This function may block until a message arrives. -- -- Considering hardware and network realities, the maximum number of -- bytes to receive should be a small power of 2, e.g., 4096. -- -- For TCP sockets, a zero length return value means the peer has closed -- its half side of the connection. -- -- Receiving data from closed socket may lead to undefined behaviour. recv :: Socket -> Int -> IO ByteString -- | Receive data from the socket. The socket need not be in a connected -- state. Returns (bytes, address) where bytes is a -- ByteString representing the data received and address -- is a SockAddr representing the address of the sending socket. -- -- Receiving data from closed socket may lead to undefined behaviour. recvFrom :: Socket -> Int -> IO (ByteString, SockAddr) -- | Receive data from the socket. The socket must be in a connected state. -- This function may return fewer bytes than specified. If the message is -- longer than the specified length, it may be discarded depending on the -- type of socket. This function may block until a message arrives. -- -- Considering hardware and network realities, the maximum number of -- bytes to receive should be a small power of 2, e.g., 4096. -- -- For TCP sockets, a zero length return value means the peer has closed -- its half side of the connection. -- -- Receiving data from closed socket may lead to undefined behaviour. recvBuf :: Socket -> Ptr Word8 -> Int -> IO Int -- | Receive data from the socket, writing it into buffer instead of -- creating a new string. The socket need not be in a connected state. -- Returns (nbytes, address) where nbytes is the number -- of bytes received and address is a SockAddr -- representing the address of the sending socket. -- -- NOTE: blocking on Windows unless you compile with -threaded (see GHC -- ticket #1129) recvBufFrom :: () => Socket -> Ptr a -> Int -> IO (Int, SockAddr) -- | Receive a file descriptor over a domain socket. Note that the -- resulting file descriptor may have to be put into non-blocking mode in -- order to be used safely. See setNonBlockIfNeeded. recvFd :: Socket -> IO CInt inet_addr :: String -> IO HostAddress inet_ntoa :: HostAddress -> IO String -- | Shut down one or both halves of the connection, depending on the -- second argument to the function. If the second argument is -- ShutdownReceive, further receives are disallowed. If it is -- ShutdownSend, further sends are disallowed. If it is -- ShutdownBoth, further sends and receives are disallowed. shutdown :: Socket -> ShutdownCmd -> IO () -- | Close the socket. This function does not throw exceptions even if the -- underlying system call returns errors. -- -- Sending data to or receiving data from closed socket may lead to -- undefined behaviour. -- -- If multiple threads use the same socket and one uses fdSocket -- and the other use close, unexpected behavior may happen. For -- more information, please refer to the documentation of -- fdSocket. close :: Socket -> IO () -- | Determines whether close has been used on the Socket. -- This does not indicate any status about the socket beyond this. -- If the socket has been closed remotely, this function can still return -- True. isConnected :: Socket -> IO Bool isBound :: Socket -> IO Bool isListening :: Socket -> IO Bool isReadable :: Socket -> IO Bool isWritable :: Socket -> IO Bool -- | Socket options for use with setSocketOption and -- getSocketOption. -- -- The existence of a constructor does not imply that the relevant option -- is supported on your system: see isSupportedSocketOption data SocketOption -- | SO_DEBUG Debug :: SocketOption -- | SO_REUSEADDR ReuseAddr :: SocketOption -- | SO_TYPE Type :: SocketOption -- | SO_ERROR SoError :: SocketOption -- | SO_DONTROUTE DontRoute :: SocketOption -- | SO_BROADCAST Broadcast :: SocketOption -- | SO_SNDBUF SendBuffer :: SocketOption -- | SO_RCVBUF RecvBuffer :: SocketOption -- | SO_KEEPALIVE KeepAlive :: SocketOption -- | SO_OOBINLINE OOBInline :: SocketOption -- | IP_TTL TimeToLive :: SocketOption -- | TCP_MAXSEG MaxSegment :: SocketOption -- | TCP_NODELAY NoDelay :: SocketOption -- | TCP_CORK Cork :: SocketOption -- | SO_LINGER Linger :: SocketOption -- | SO_REUSEPORT ReusePort :: SocketOption -- | SO_RCVLOWAT RecvLowWater :: SocketOption -- | SO_SNDLOWAT SendLowWater :: SocketOption -- | SO_RCVTIMEO RecvTimeOut :: SocketOption -- | SO_SNDTIMEO SendTimeOut :: SocketOption -- | SO_USELOOPBACK UseLoopBack :: SocketOption -- | TCP_USER_TIMEOUT UserTimeout :: SocketOption -- | IPV6_V6ONLY IPv6Only :: SocketOption CustomSockOpt :: (CInt, CInt) -> SocketOption -- | Does the SocketOption exist on this system? isSupportedSocketOption :: SocketOption -> Bool -- | Get a socket option that gives an Int value. There is currently no API -- to get e.g. the timeval socket options getSocketOption :: Socket -> SocketOption -> IO Int -- | Set a socket option that expects an Int value. There is currently no -- API to set e.g. the timeval socket options setSocketOption :: Socket -> SocketOption -> Int -> IO () sOMAXCONN :: Int sOL_SOCKET :: Int sCM_RIGHTS :: Int -- | This is the value of SOMAXCONN, typically 128. 128 is good enough for -- normal network servers but is too small for high performance servers. maxListenQueue :: Int -- | With older versions of the network library (version 2.6.0.2 -- or earlier) on Windows operating systems, the networking subsystem -- must be initialised using withSocketsDo before any networking -- operations can be used. eg. -- --
--   main = withSocketsDo $ do {...}
--   
-- -- It is fine to nest calls to withSocketsDo, and to perform -- networking operations after withSocketsDo has returned. -- -- In newer versions of the network library (version v2.6.1.0 or -- later) it is only necessary to call withSocketsDo if you are -- calling the MkSocket constructor directly. However, for -- compatibility with older versions on Windows, it is good practice to -- always call withSocketsDo (it's very cheap). withSocketsDo :: () => IO a -> IO a -- | Obtaining the file descriptor from a socket. -- -- If a Socket is shared with multiple threads and one uses -- fdSocket, unexpected issues may happen. Consider the following -- scenario: -- -- 1) Thread A acquires a Fd from Socket by -- fdSocket. -- -- 2) Thread B close the Socket. -- -- 3) Thread C opens a new Socket. Unfortunately it gets the same -- Fd number which thread A is holding. -- -- In this case, it is safer for Thread A to clone Fd by -- dup. But this would still suffer from a rase condition between -- fdSocket and close. fdSocket :: Socket -> CInt -- | Smart constructor for constructing a Socket. It should only be -- called once for every new file descriptor. The caller must make sure -- that the socket is in non-blocking mode. See -- setNonBlockIfNeeded. mkSocket :: CInt -> Family -> SocketType -> ProtocolNumber -> SocketStatus -> IO Socket -- | Set the nonblocking flag on Unix. On Windows, nothing is done. setNonBlockIfNeeded :: CInt -> IO () module StableName -- | An abstract name for an object, that supports equality and hashing. -- -- Stable names have the following property: -- -- -- -- The reverse is not necessarily true: if two stable names are not -- equal, then the objects they name may still be equal. Note in -- particular that makeStableName may return a different -- StableName after an object is evaluated. -- -- Stable Names are similar to Stable Pointers -- (Foreign.StablePtr), but differ in the following ways: -- -- data StableName a -- | Makes a StableName for an arbitrary object. The object passed -- as the first argument is not evaluated by makeStableName. makeStableName :: () => a -> IO StableName a -- | Convert a StableName to an Int. The Int returned -- is not necessarily unique; several StableNames may map to the -- same Int (in practice however, the chances of this are small, -- so the result of hashStableName makes a good hash key). hashStableName :: () => StableName a -> Int -- | Equality on StableName that does not require that the types of -- the arguments match. eqStableName :: () => StableName a -> StableName b -> Bool module State -- | A state monad parameterized by the type s of the state to -- carry. -- -- The return function leaves the state unchanged, while -- >>= uses the final state of the first computation as -- the initial state of the second. type State s = StateT s Identity -- | Unwrap a state monad computation as a function. (The inverse of -- state.) runState :: () => State s a -> s -> (a, s) -- | Evaluate a state computation with the given initial state and return -- the final value, discarding the final state. -- -- evalState :: () => State s a -> s -> a -- | Evaluate a state computation with the given initial state and return -- the final state, discarding the final value. -- -- execState :: () => State s a -> s -> s -- | Map both the return value and final state of a computation using the -- given function. -- -- mapState :: () => (a, s) -> (b, s) -> State s a -> State s b -- | withState f m executes action m on a state -- modified by applying f. -- -- withState :: () => s -> s -> State s a -> State s 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 :: * -> *) a StateT :: s -> m (a, s) -> StateT s a [runStateT] :: StateT s a -> s -> m (a, 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 state, discarding the final value. -- -- execStateT :: Monad m => StateT s m a -> s -> m s -- | Map both the return value and final state of a computation using the -- given function. -- -- mapStateT :: () => m (a, s) -> n (b, s) -> StateT s m a -> StateT s n b -- | withStateT f m executes action m on a state -- modified by applying f. -- -- withStateT :: () => s -> s -> StateT s m a -> StateT s m a -- | Minimal definition is either both of get and put or -- just state class Monad m => MonadState s (m :: * -> *) | 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 -- | Gets specific component of the state, using a projection function -- supplied. gets :: MonadState s m => s -> 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 () -- | A variant of modify in which the computation is strict in the -- new state. modify' :: MonadState s m => s -> s -> m () -- | This class allows us to use zoom in, changing the State -- supplied by many different Monad transformers, potentially -- quite deep in a Monad transformer stack. class (MonadState s m, MonadState t n) => Zoom (m :: * -> *) (n :: * -> *) s t | m -> s, n -> t, m t -> n, n s -> m -- | Run a monadic action in a larger State than it was defined in, -- using a Lens' or Traversal'. -- -- This is commonly used to lift actions in a simpler State -- Monad into a State Monad with a larger -- State type. -- -- When applied to a Traversal' over multiple values, the actions -- for each target are executed sequentially and the results are -- aggregated. -- -- This can be used to edit pretty much any Monad transformer -- stack with a State in it! -- --
--   >>> flip State.evalState (a,b) $ zoom _1 $ use id
--   a
--   
-- --
--   >>> flip State.execState (a,b) $ zoom _1 $ id .= c
--   (c,b)
--   
-- --
--   >>> flip State.execState [(a,b),(c,d)] $ zoom traverse $ _2 %= f
--   [(a,f b),(c,f d)]
--   
-- --
--   >>> flip State.runState [(a,b),(c,d)] $ zoom traverse $ _2 <%= f
--   (f b <> f d <> mempty,[(a,f b),(c,f d)])
--   
-- --
--   >>> flip State.evalState (a,b) $ zoom both (use id)
--   a <> b
--   
-- --
--   zoom :: Monad m             => Lens' s t      -> StateT t m a -> StateT s m a
--   zoom :: (Monad m, Monoid c) => Traversal' s t -> StateT t m c -> StateT s m c
--   zoom :: (Monad m, Monoid w)             => Lens' s t      -> RWST r w t m c -> RWST r w s m c
--   zoom :: (Monad m, Monoid w, Monoid c) => Traversal' s t -> RWST r w t m c -> RWST r w s m c
--   zoom :: (Monad m, Monoid w, Error e)  => Lens' s t      -> ErrorT e (RWST r w t m) c -> ErrorT e (RWST r w s m) c
--   zoom :: (Monad m, Monoid w, Monoid c, Error e) => Traversal' s t -> ErrorT e (RWST r w t m) c -> ErrorT e (RWST r w s m) c
--   ...
--   
zoom :: Zoom m n s t => LensLike' Zoomed m c t s -> m c -> n c infixr 2 `zoom` -- | This type family is used by Zoom to describe the common effect -- type. module Storable -- | The member functions of this class facilitate writing values of -- primitive types to raw memory (which may have been allocated with the -- above mentioned routines) and reading values from blocks of raw -- memory. The class, furthermore, includes support for computing the -- storage requirements and alignment restrictions of storable types. -- -- Memory addresses are represented as values of type Ptr -- a, for some a which is an instance of class -- Storable. The type argument to Ptr helps provide some -- valuable type safety in FFI code (you can't mix pointers of different -- types without an explicit cast), while helping the Haskell type system -- figure out which marshalling method is needed for a given pointer. -- -- All marshalling between Haskell and a foreign language ultimately -- boils down to translating Haskell data structures into the binary -- representation of a corresponding data structure of the foreign -- language and vice versa. To code this marshalling in Haskell, it is -- necessary to manipulate primitive data types stored in unstructured -- memory blocks. The class Storable facilitates this manipulation -- on all types for which it is instantiated, which are the standard -- basic types of Haskell, the fixed size Int types -- (Int8, Int16, Int32, Int64), the fixed -- size Word types (Word8, Word16, Word32, -- Word64), StablePtr, all types from -- Foreign.C.Types, as well as Ptr. class Storable a -- | Computes the storage requirements (in bytes) of the argument. The -- value of the argument is not used. sizeOf :: Storable a => a -> Int -- | Computes the alignment constraint of the argument. An alignment -- constraint x is fulfilled by any address divisible by -- x. The value of the argument is not used. alignment :: Storable a => a -> Int -- | Read a value from a memory area regarded as an array of values of the -- same kind. The first argument specifies the start address of the array -- and the second the index into the array (the first element of the -- array has index 0). The following equality holds, -- --
--   peekElemOff addr idx = IOExts.fixIO $ \result ->
--     peek (addr `plusPtr` (idx * sizeOf result))
--   
-- -- Note that this is only a specification, not necessarily the concrete -- implementation of the function. peekElemOff :: Storable a => Ptr a -> Int -> IO a -- | Write a value to a memory area regarded as an array of values of the -- same kind. The following equality holds: -- --
--   pokeElemOff addr idx x = 
--     poke (addr `plusPtr` (idx * sizeOf x)) x
--   
pokeElemOff :: Storable a => Ptr a -> Int -> a -> IO () -- | Read a value from a memory location given by a base address and -- offset. The following equality holds: -- --
--   peekByteOff addr off = peek (addr `plusPtr` off)
--   
peekByteOff :: Storable a => Ptr b -> Int -> IO a -- | Write a value to a memory location given by a base address and offset. -- The following equality holds: -- --
--   pokeByteOff addr off x = poke (addr `plusPtr` off) x
--   
pokeByteOff :: Storable a => Ptr b -> Int -> a -> IO () -- | Read a value from the given memory location. -- -- Note that the peek and poke functions might require properly aligned -- addresses to function correctly. This is architecture dependent; thus, -- portable code should ensure that when peeking or poking values of some -- type a, the alignment constraint for a, as given by -- the function alignment is fulfilled. peek :: Storable a => Ptr a -> IO a -- | Write the given value to the given memory location. Alignment -- restrictions might apply; see peek. poke :: Storable a => Ptr a -> a -> IO () module Symbol -- | (Kind) This is the kind of type-level symbols. Declared here because -- class IP needs it data Symbol -- | This class gives the string associated with a type-level symbol. There -- are instances of the class for every concrete literal: "hello", etc. class KnownSymbol (n :: Symbol) symbolVal :: KnownSymbol n => proxy n -> String symbolVal' :: KnownSymbol n => Proxy# n -> String -- | This type represents unknown type-level symbols. data SomeSymbol [SomeSymbol] :: SomeSymbol -- | Convert a string into an unknown type-level symbol. someSymbolVal :: String -> SomeSymbol -- | We either get evidence that this function was instantiated with the -- same type-level symbols, or Nothing. sameSymbol :: (KnownSymbol a, KnownSymbol b) => Proxy a -> Proxy b -> Maybe a :~: b -- | Concatenation of type-level symbols. -- | Comparison of type-level symbols, as a function. appendSymbol :: () => (KnownSymbol a, KnownSymbol b) :- KnownSymbol a ++ b appendUnit1 :: () => Dict "" ++ a ~ a appendUnit2 :: () => Dict a ++ "" ~ a appendAssociates :: () => Dict a ++ b ++ c ~ a ++ b ++ c takeSymbol :: () => (KnownNat n, KnownSymbol a) :- KnownSymbol Take n a dropSymbol :: () => (KnownNat n, KnownSymbol a) :- KnownSymbol Drop n a takeAppendDrop :: () => Dict Take n a ++ Drop n a ~ a lengthSymbol :: () => KnownSymbol a :- KnownNat Length a takeLength :: () => Length a <= n :- Take n a ~ a take0 :: () => Dict Take 0 a ~ "" takeEmpty :: () => Dict Take n "" ~ "" dropLength :: () => Length a <= n :- Drop n a ~ "" drop0 :: () => Dict Drop 0 a ~ a dropEmpty :: () => Dict Drop n "" ~ "" lengthTake :: () => Dict Length Take n a <= n lengthDrop :: () => Dict Length a <= Length Drop n a + n dropDrop :: () => Dict Drop n Drop m a ~ Drop n + m a takeTake :: () => Dict Take n Take m a ~ Take Min n m a module System -- | Byte ordering. data ByteOrder -- | most-significant-byte occurs in lowest address. BigEndian :: ByteOrder -- | least-significant-byte occurs in lowest address. LittleEndian :: ByteOrder -- | The byte ordering of the target machine. targetByteOrder :: ByteOrder -- | The operating system on which the program is running. os :: String -- | Return True on Windows and False otherwise. A runtime -- version of #ifdef minw32_HOST_OS. Equivalent to os == -- "mingw32", but: more efficient; doesn't require typing an easily -- mistypeable string; actually asks about your OS not a library; doesn't -- bake in 32bit assumptions that are already false. </rant> -- --
--   isWindows == (os == "mingw32")
--   
isWindows :: Bool -- | Return True on Mac OS X and False otherwise. isMac :: Bool -- | The machine architecture on which the program is running. arch :: String -- | The Haskell implementation with which the program was compiled or is -- being interpreted. compilerName :: String -- | The version of compilerName with which the program was compiled -- or is being interpreted. compilerVersion :: Version -- | Gets the address information for each of the network interfaces on the -- local computer. getNetworkInterfaces :: IO [NetworkInterface] -- | Describes the basic configuration of a network interface. This -- definition is currently limited to just one address per family. data NetworkInterface NetworkInterface :: String -> IPv4 -> IPv6 -> MAC -> NetworkInterface -- | Interface name (e.g. "eth0", "lo", "Local Area Connection") [name] :: NetworkInterface -> String -- | IPv4 address [ipv4] :: NetworkInterface -> IPv4 -- | IPv6 address [ipv6] :: NetworkInterface -> IPv6 -- | MAC address [mac] :: NetworkInterface -> MAC -- | Represents an IPv4 address (e.g. 172.23.21.1, -- 127.0.0.1) data IPv4 IPv4 :: {-# UNPACK #-} !Word32 -> IPv4 -- | Represents an IPv6 address (e.g. -- 2001:db8:85a3::8a2e:370:7334, ::1) data IPv6 IPv6 :: {-# UNPACK #-} !Word32 -> {-# UNPACK #-} !Word32 -> {-# UNPACK #-} !Word32 -> {-# UNPACK #-} !Word32 -> IPv6 -- | Represents a MAC address (e.g. 01:23:45:67:89:ab) data MAC MAC :: {-# UNPACK #-} !Word8 -> {-# UNPACK #-} !Word8 -> {-# UNPACK #-} !Word8 -> {-# UNPACK #-} !Word8 -> {-# UNPACK #-} !Word8 -> {-# UNPACK #-} !Word8 -> MAC module Tagged module Terminal module Test module Test.Gen module Test.Range module Text -- | A space efficient, packed, unboxed Unicode text type. data Text -- | Read some text. If the read succeeds, return its value and the -- remaining text, otherwise an error message. type Reader a = IReader Text a type IReader t a = t -> Either String (a, t) -- | O(n) all p t determines whether all -- characters in the Text t satisfy the predicate -- p. Subject to fusion. all :: Char -> Bool -> Text -> Bool -- | O(n) any p t determines whether any -- character in the Text t satisfies the predicate -- p. Subject to fusion. any :: Char -> Bool -> Text -> Bool -- | O(n) Appends one Text to the other by copying both of -- them into a new Text. Subject to fusion. append :: Text -> Text -> Text -- | O(n) break is like span, but the prefix returned -- is over elements that fail the predicate p. break :: Char -> Bool -> Text -> (Text, Text) -- | O(n+m) Find the first instance of needle (which must -- be non-null) in haystack. The first element of the -- returned tuple is the prefix of haystack before -- needle is matched. The second is the remainder of -- haystack, starting with the match. -- -- Examples: -- --
--   >>> breakOn "::" "a::b::c"
--   ("a","::b::c")
--   
-- --
--   >>> breakOn "/" "foobar"
--   ("foobar","")
--   
-- -- Laws: -- --
--   append prefix match == haystack
--     where (prefix, match) = breakOn needle haystack
--   
-- -- If you need to break a string by a substring repeatedly (e.g. you want -- to break on every instance of a substring), use breakOnAll -- instead, as it has lower startup overhead. -- -- In (unlikely) bad cases, this function's time complexity degrades -- towards O(n*m). breakOn :: Text -> Text -> (Text, Text) -- | O(n+m) Find all non-overlapping instances of needle in -- haystack. Each element of the returned list consists of a -- pair: -- -- -- -- Examples: -- --
--   >>> breakOnAll "::" ""
--   []
--   
-- --
--   >>> breakOnAll "/" "a/b/c/"
--   [("a","/b/c/"),("a/b","/c/"),("a/b/c","/")]
--   
-- -- In (unlikely) bad cases, this function's time complexity degrades -- towards O(n*m). -- -- The needle parameter may not be empty. breakOnAll :: Text -> Text -> [(Text, Text)] -- | O(n+m) Similar to breakOn, but searches from the end of -- the string. -- -- The first element of the returned tuple is the prefix of -- haystack up to and including the last match of -- needle. The second is the remainder of haystack, -- following the match. -- --
--   >>> breakOnEnd "::" "a::b::c"
--   ("a::b::","c")
--   
breakOnEnd :: Text -> Text -> (Text, Text) -- | O(n) Center a string to the given length, using the specified -- fill character on either side. Performs replacement on invalid scalar -- values. -- -- Examples: -- --
--   >>> center 8 'x' "HS"
--   "xxxHSxxx"
--   
center :: Int -> Char -> Text -> Text -- | O(n) Splits a Text into components of length k. -- The last element may be shorter than the other chunks, depending on -- the length of the input. Examples: -- --
--   >>> chunksOf 3 "foobarbaz"
--   ["foo","bar","baz"]
--   
-- --
--   >>> chunksOf 4 "haskell.org"
--   ["hask","ell.","org"]
--   
chunksOf :: Int -> Text -> [Text] -- | O(n) Find the longest non-empty common prefix of two strings -- and return it, along with the suffixes of each string at which they no -- longer match. -- -- If the strings do not have a common prefix or either one is empty, -- this function returns Nothing. -- -- Examples: -- --
--   >>> commonPrefixes "foobar" "fooquux"
--   Just ("foo","bar","quux")
--   
-- --
--   >>> commonPrefixes "veeble" "fetzer"
--   Nothing
--   
-- --
--   >>> commonPrefixes "" "baz"
--   Nothing
--   
commonPrefixes :: Text -> Text -> Maybe (Text, Text, Text) -- | O(n) Compare the count of characters in a Text to a -- number. Subject to fusion. -- -- This function gives the same answer as comparing against the result of -- length, but can short circuit if the count of characters is -- greater than the number, and hence be more efficient. compareLength :: Text -> Int -> Ordering -- | O(n) Concatenate a list of Texts. concat :: [Text] -> Text -- | O(n) Map a function over a Text that results in a -- Text, and concatenate the results. concatMap :: Char -> Text -> Text -> Text -- | O(n) Adds a character to the front of a Text. This -- function is more costly than its List counterpart because it -- requires copying a new array. Subject to fusion. Performs replacement -- on invalid scalar values. cons :: Char -> Text -> Text infixr 5 `cons` -- | O(n) Make a distinct copy of the given string, sharing no -- storage with the original string. -- -- As an example, suppose you read a large string, of which you need only -- a small portion. If you do not use copy, the entire original -- array will be kept alive in memory by the smaller string. Making a -- copy "breaks the link" to the original array, allowing it to be -- garbage collected if there are no other live references to it. copy :: Text -> Text -- | Read a decimal integer. The input must begin with at least one decimal -- digit, and is consumed until a non-digit or end of string is reached. -- -- This function does not handle leading sign characters. If you need to -- handle signed input, use signed decimal. -- -- Note: For fixed-width integer types, this function does not -- attempt to detect overflow, so a sufficiently long input may give -- incorrect results. If you are worried about overflow, use -- Integer for your result type. decimal :: Integral a => Reader a -- | 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 -- | Read a rational number. -- -- The syntax accepted by this function is the same as for -- rational. -- -- Note: This function is almost ten times faster than -- rational, but is slightly less accurate. -- -- The Double type supports about 16 decimal places of accuracy. -- For 94.2% of numbers, this function and rational give identical -- results, but for the remaining 5.8%, this function loses precision -- around the 15th decimal place. For 0.001% of numbers, this function -- will lose precision at the 13th or 14th decimal place. double :: Reader Double -- | O(n) drop n, applied to a Text, returns -- the suffix of the Text after the first n characters, -- or the empty Text if n is greater than the length of -- the Text. Subject to fusion. drop :: Int -> Text -> Text -- | O(n) dropAround p t returns the -- substring remaining after dropping characters that satisfy the -- predicate p from both the beginning and end of t. -- Subject to fusion. dropAround :: Char -> Bool -> Text -> Text -- | O(n) dropEnd n t returns the prefix -- remaining after dropping n characters from the end of -- t. -- -- Examples: -- --
--   >>> dropEnd 3 "foobar"
--   "foo"
--   
dropEnd :: Int -> Text -> Text -- | O(n) dropWhile p t returns the suffix -- remaining after takeWhile p t. Subject to -- fusion. dropWhile :: Char -> Bool -> Text -> Text -- | O(n) dropWhileEnd p t returns the -- prefix remaining after dropping characters that satisfy the predicate -- p from the end of t. Subject to fusion. -- -- Examples: -- --
--   >>> dropWhileEnd (=='.') "foo..."
--   "foo"
--   
dropWhileEnd :: Char -> Bool -> Text -> Text -- | O(1) The empty Text. empty :: Text -- | Encode text using big endian UTF-16 encoding. encodeUtf16BE :: Text -> ByteString -- | Encode text using little endian UTF-16 encoding. encodeUtf16LE :: Text -> ByteString -- | Encode text using big endian UTF-32 encoding. encodeUtf32BE :: Text -> ByteString -- | Encode text using little endian UTF-32 encoding. encodeUtf32LE :: Text -> ByteString -- | Encode text using UTF-8 encoding. encodeUtf8 :: Text -> ByteString -- | O(n) filter, applied to a predicate and a Text, -- returns a Text containing those characters that satisfy the -- predicate. filter :: Char -> Bool -> Text -> Text -- | O(n) The find function takes a predicate and a -- Text, and returns the first element matching the predicate, or -- Nothing if there is no such element. find :: Char -> Bool -> Text -> Maybe Char -- | O(n) The findIndex function takes a predicate and a -- Text and returns the index of the first element in the -- Text satisfying the predicate. Subject to fusion. findIndex :: Char -> Bool -> Text -> Maybe Int -- | O(n) A strict version of foldl. Subject to fusion. foldl' :: () => a -> Char -> a -> a -> Text -> a -- | O(n) foldr, applied to a binary operator, a starting -- value (typically the right-identity of the operator), and a -- Text, reduces the Text using the binary operator, from -- right to left. Subject to fusion. foldr :: () => Char -> a -> a -> a -> Text -> a -- | O(n) Group characters in a string by equality. group :: Text -> [Text] -- | O(n) Group characters in a string according to a predicate. groupBy :: Char -> Char -> Bool -> Text -> [Text] -- | Read a hexadecimal integer, consisting of an optional leading -- "0x" followed by at least one hexadecimal digit. Input is -- consumed until a non-hex-digit or end of string is reached. This -- function is case insensitive. -- -- This function does not handle leading sign characters. If you need to -- handle signed input, use signed hexadecimal. -- -- Note: For fixed-width integer types, this function does not -- attempt to detect overflow, so a sufficiently long input may give -- incorrect results. If you are worried about overflow, use -- Integer for your result type. hexadecimal :: Integral a => Reader a -- | O(n) Return all initial segments of the given Text, -- shortest first. inits :: Text -> [Text] -- | O(n) The intercalate function takes a Text and a -- list of Texts and concatenates the list after interspersing the -- first argument between each element of the list. -- -- Example: -- --
--   >>> T.intercalate "NI!" ["We", "seek", "the", "Holy", "Grail"]
--   "WeNI!seekNI!theNI!HolyNI!Grail"
--   
intercalate :: Text -> [Text] -> Text -- | O(n) The intersperse function takes a character and -- places it between the characters of a Text. -- -- Example: -- --
--   >>> T.intersperse '.' "SHIELD"
--   "S.H.I.E.L.D"
--   
-- -- Subject to fusion. Performs replacement on invalid scalar values. intersperse :: Char -> Text -> Text -- | O(n+m) The isInfixOf function takes two Texts and -- returns True iff the first is contained, wholly and intact, -- anywhere within the second. -- -- In (unlikely) bad cases, this function's time complexity degrades -- towards O(n*m). isInfixOf :: Text -> Text -> Bool -- | O(n) The isPrefixOf function takes two Texts and -- returns True iff the first is a prefix of the second. Subject -- to fusion. isPrefixOf :: Text -> Text -> Bool -- | O(n) The isSuffixOf function takes two Texts and -- returns True iff the first is a suffix of the second. isSuffixOf :: Text -> Text -> Bool -- | O(n) Left-justify a string to the given length, using the -- specified fill character on the right. Subject to fusion. Performs -- replacement on invalid scalar values. -- -- Examples: -- --
--   >>> justifyLeft 7 'x' "foo"
--   "fooxxxx"
--   
-- --
--   >>> justifyLeft 3 'x' "foobar"
--   "foobar"
--   
justifyLeft :: Int -> Char -> Text -> Text -- | O(n) Right-justify a string to the given length, using the -- specified fill character on the left. Performs replacement on invalid -- scalar values. -- -- Examples: -- --
--   >>> justifyRight 7 'x' "bar"
--   "xxxxbar"
--   
-- --
--   >>> justifyRight 3 'x' "foobar"
--   "foobar"
--   
justifyRight :: Int -> Char -> Text -> Text -- | O(n) Returns the number of characters in a Text. Subject -- to fusion. length :: Text -> Int -- | 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) map f t is the Text -- obtained by applying f to each element of t. -- -- Example: -- --
--   >>> let message = pack "I am not angry. Not at all."
--   
--   >>> T.map (\c -> if c == '.' then '!' else c) message
--   "I am not angry! Not at all!"
--   
-- -- Subject to fusion. Performs replacement on invalid scalar values. map :: Char -> Char -> Text -> Text -- | O(n) Like a combination of map and foldl'. -- Applies a function to each element of a Text, passing an -- accumulating parameter from left to right, and returns a final -- Text. Performs replacement on invalid scalar values. mapAccumL :: () => a -> Char -> (a, Char) -> a -> Text -> (a, Text) -- | The mapAccumR function behaves like a combination of map -- and a strict foldr; it applies a function to each element of a -- Text, passing an accumulating parameter from right to left, and -- returning a final value of this accumulator together with the new -- Text. Performs replacement on invalid scalar values. mapAccumR :: () => a -> Char -> (a, Char) -> a -> Text -> (a, Text) -- | O(1) Tests whether a Text is empty or not. Subject to -- fusion. null :: Text -> Bool -- | O(n) Convert a String into a Text. Subject to -- fusion. Performs replacement on invalid scalar values. pack :: String -> Text -- | O(n) The partition function takes a predicate and a -- Text, and returns the pair of Texts with elements which -- do and do not satisfy the predicate, respectively; i.e. -- --
--   partition p t == (filter p t, filter (not . p) t)
--   
partition :: Char -> Bool -> Text -> (Text, Text) -- | Read a rational number. -- -- This function accepts an optional leading sign character, followed by -- at least one decimal digit. The syntax similar to that accepted by the -- read function, with the exception that a trailing '.' -- or 'e' not followed by a number is not consumed. -- -- Examples (with behaviour identical to read): -- --
--   rational "3"     == Right (3.0, "")
--   rational "3.1"   == Right (3.1, "")
--   rational "3e4"   == Right (30000.0, "")
--   rational "3.1e4" == Right (31000.0, "")
--   rational ".3"    == Left "input does not start with a digit"
--   rational "e3"    == Left "input does not start with a digit"
--   
-- -- Examples of differences from read: -- --
--   rational "3.foo" == Right (3.0, ".foo")
--   rational "3e"    == Right (3.0, "e")
--   
rational :: Fractional a => Reader a -- | O(m+n) Replace every non-overlapping occurrence of -- needle in haystack with replacement. -- -- This function behaves as though it was defined as follows: -- --
--   replace needle replacement haystack =
--     intercalate replacement (splitOn needle haystack)
--   
-- -- As this suggests, each occurrence is replaced exactly once. So if -- needle occurs in replacement, that occurrence will -- not itself be replaced recursively: -- --
--   >>> replace "oo" "foo" "oo"
--   "foo"
--   
-- -- In cases where several instances of needle overlap, only the -- first one will be replaced: -- --
--   >>> replace "ofo" "bar" "ofofo"
--   "barfo"
--   
-- -- In (unlikely) bad cases, this function's time complexity degrades -- towards O(n*m). replace :: Text -> Text -> Text -> Text -- | O(n*m) replicate n t is a Text -- consisting of the input t repeated n times. replicate :: Int -> Text -> Text -- | O(n) Reverse the characters of a string. -- -- Example: -- --
--   >>> T.reverse "desrever"
--   "reversed"
--   
-- -- Subject to fusion. reverse :: Text -> Text -- | O(n) scanl is similar to foldl, but returns a -- list of successive reduced values from the left. Subject to fusion. -- Performs replacement on invalid scalar values. -- --
--   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 :: Char -> Char -> Char -> Char -> Text -> Text -- | O(n) scanl1 is a variant of scanl that has no -- starting value argument. Subject to fusion. Performs replacement on -- invalid scalar values. -- --
--   scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
--   
scanl1 :: Char -> Char -> Char -> Text -> Text -- | O(n) scanr is the right-to-left dual of scanl. -- Performs replacement on invalid scalar values. -- --
--   scanr f v == reverse . scanl (flip f) v . reverse
--   
scanr :: Char -> Char -> Char -> Char -> Text -> Text -- | O(n) scanr1 is a variant of scanr that has no -- starting value argument. Subject to fusion. Performs replacement on -- invalid scalar values. scanr1 :: Char -> Char -> Char -> Text -> Text -- | Read an optional leading sign character ('-' or '+') -- and apply it to the result of applying the given reader. signed :: Num a => Reader a -> Reader a -- | O(1) Convert a character into a Text. Subject to fusion. -- Performs replacement on invalid scalar values. singleton :: Char -> Text -- | O(n) Adds a character to the end of a Text. This copies -- the entire array in the process, unless fused. Subject to fusion. -- Performs replacement on invalid scalar values. snoc :: Text -> Char -> Text -- | O(n) span, applied to a predicate p and text -- t, returns a pair whose first element is the longest prefix -- (possibly empty) of t of elements that satisfy p, -- and whose second is the remainder of the list. span :: Char -> Bool -> Text -> (Text, Text) -- | O(n) Splits a Text into components delimited by -- separators, where the predicate returns True for a separator element. -- The resulting components do not contain the separators. Two adjacent -- separators result in an empty component in the output. eg. -- --
--   >>> split (=='a') "aabbaca"
--   ["","","bb","c",""]
--   
-- --
--   >>> split (=='a') ""
--   [""]
--   
split :: Char -> Bool -> Text -> [Text] -- | O(n) splitAt n t returns a pair whose first -- element is a prefix of t of length n, and whose -- second is the remainder of the string. It is equivalent to -- (take n t, drop n t). splitAt :: Int -> Text -> (Text, Text) -- | O(n) Remove leading and trailing white space from a string. -- Equivalent to: -- --
--   dropAround isSpace
--   
strip :: Text -> Text -- | O(n) Remove trailing white space from a string. Equivalent to: -- --
--   dropWhileEnd isSpace
--   
stripEnd :: Text -> Text -- | O(n) Return the suffix of the second string if its prefix -- matches the entire first string. -- -- Examples: -- --
--   >>> stripPrefix "foo" "foobar"
--   Just "bar"
--   
-- --
--   >>> stripPrefix ""    "baz"
--   Just "baz"
--   
-- --
--   >>> stripPrefix "foo" "quux"
--   Nothing
--   
-- -- This is particularly useful with the ViewPatterns extension -- to GHC, as follows: -- --
--   {-# LANGUAGE ViewPatterns #-}
--   import Data.Text as T
--   
--   fnordLength :: Text -> Int
--   fnordLength (stripPrefix "fnord" -> Just suf) = T.length suf
--   fnordLength _                                 = -1
--   
stripPrefix :: Text -> Text -> Maybe Text -- | O(n) Remove leading white space from a string. Equivalent to: -- --
--   dropWhile isSpace
--   
stripStart :: Text -> Text -- | O(n) Return the prefix of the second string if its suffix -- matches the entire first string. -- -- Examples: -- --
--   >>> stripSuffix "bar" "foobar"
--   Just "foo"
--   
-- --
--   >>> stripSuffix ""    "baz"
--   Just "baz"
--   
-- --
--   >>> stripSuffix "foo" "quux"
--   Nothing
--   
-- -- This is particularly useful with the ViewPatterns extension -- to GHC, as follows: -- --
--   {-# LANGUAGE ViewPatterns #-}
--   import Data.Text as T
--   
--   quuxLength :: Text -> Int
--   quuxLength (stripSuffix "quux" -> Just pre) = T.length pre
--   quuxLength _                                = -1
--   
stripSuffix :: Text -> Text -> Maybe Text -- | O(n) Return all final segments of the given Text, -- longest first. tails :: Text -> [Text] -- | O(n) take n, applied to a Text, returns -- the prefix of the Text of length n, or the Text -- itself if n is greater than the length of the Text. Subject -- to fusion. take :: Int -> Text -> Text -- | O(n) takeEnd n t returns the suffix -- remaining after taking n characters from the end of -- t. -- -- Examples: -- --
--   >>> takeEnd 3 "foobar"
--   "bar"
--   
takeEnd :: Int -> Text -> Text -- | O(n) takeWhile, applied to a predicate p and a -- Text, returns the longest prefix (possibly empty) of elements -- that satisfy p. Subject to fusion. takeWhile :: Char -> Bool -> Text -> Text -- | O(n) takeWhileEnd, applied to a predicate p and -- a Text, returns the longest suffix (possibly empty) of elements -- that satisfy p. Subject to fusion. Examples: -- --
--   >>> takeWhileEnd (=='o') "foo"
--   "oo"
--   
takeWhileEnd :: Char -> Bool -> Text -> Text -- | O(n) Convert a string to folded case. Subject to fusion. -- -- This function is mainly useful for performing caseless (also known as -- case insensitive) string comparisons. -- -- A string x is a caseless match for a string y if and -- only if: -- --
--   toCaseFold x == toCaseFold y
--   
-- -- The result string may be longer than the input string, and may differ -- from applying toLower to the input string. For instance, the -- Armenian small ligature "ﬓ" (men now, U+FB13) is case folded to the -- sequence "մ" (men, U+0574) followed by "ն" (now, U+0576), while the -- Greek "µ" (micro sign, U+00B5) is case folded to "μ" (small letter mu, -- U+03BC) instead of itself. toCaseFold :: Text -> Text -- | O(n) Convert a string to lower case, using simple case -- conversion. Subject to fusion. -- -- The result string may be longer than the input string. For instance, -- "İ" (Latin capital letter I with dot above, U+0130) maps to the -- sequence "i" (Latin small letter i, U+0069) followed by " ̇" -- (combining dot above, U+0307). toLower :: Text -> Text -- | O(n) Convert a string to title case, using simple case -- conversion. Subject to fusion. -- -- The first letter of the input is converted to title case, as is every -- subsequent letter that immediately follows a non-letter. Every letter -- that immediately follows another letter is converted to lower case. -- -- The result string may be longer than the input string. For example, -- the Latin small ligature fl (U+FB02) is converted to the sequence Latin -- capital letter F (U+0046) followed by Latin small letter l (U+006C). -- -- Note: this function does not take language or culture specific -- rules into account. For instance, in English, different style guides -- disagree on whether the book name "The Hill of the Red Fox" is -- correctly title cased—but this function will capitalize every -- word. toTitle :: Text -> Text -- | O(n) Convert a string to upper case, using simple case -- conversion. Subject to fusion. -- -- The result string may be longer than the input string. For instance, -- the German "ß" (eszett, U+00DF) maps to the two-letter sequence "SS". toUpper :: Text -> Text -- | O(n) The transpose function transposes the rows and -- columns of its Text argument. Note that this function uses -- pack, unpack, and the list version of transpose, and is -- thus not very efficient. -- -- Examples: -- --
--   >>> transpose ["green","orange"]
--   ["go","rr","ea","en","ng","e"]
--   
-- --
--   >>> transpose ["blue","red"]
--   ["br","le","ud","e"]
--   
transpose :: [Text] -> [Text] -- | O(1) Returns the first character and rest of a Text, or -- Nothing if empty. Subject to fusion. uncons :: Text -> Maybe (Char, Text) -- | O(n), where n is the length of the result. The -- unfoldr function is analogous to the List unfoldr. -- unfoldr builds a Text from a seed value. The function -- takes the element and returns Nothing if it is done producing -- the Text, otherwise Just (a,b). In this case, -- a is the next Char in the string, and b is -- the seed value for further production. Subject to fusion. Performs -- replacement on invalid scalar values. unfoldr :: () => a -> Maybe (Char, a) -> a -> Text -- | O(n) Like unfoldr, unfoldrN builds a Text -- from a seed value. However, the length of the result should be limited -- by the first argument to unfoldrN. This function is more -- efficient than unfoldr when the maximum length of the result is -- known and correct, otherwise its performance is similar to -- unfoldr. Subject to fusion. Performs replacement on invalid -- scalar values. unfoldrN :: () => Int -> a -> Maybe (Char, a) -> a -> Text -- | O(n) Joins lines, after appending a terminating newline to -- each. unlines :: [Text] -> Text -- | O(n) Convert a Text into a String. Subject to -- fusion. unpack :: Text -> String -- | O(n) Convert a literal string into a Text. Subject to -- fusion. -- -- This is exposed solely for people writing GHC rewrite rules. unpackCString# :: Addr# -> Text -- | O(1) Returns all but the last character and the last character -- of a Text, or Nothing if empty. unsnoc :: Text -> Maybe (Text, Char) -- | 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(n) zip takes two Texts and returns a list of -- corresponding pairs of bytes. If one input Text is short, -- excess elements of the longer Text are discarded. This is -- equivalent to a pair of unpack operations. zip :: Text -> Text -> [(Char, Char)] -- | O(n) zipWith generalises zip by zipping with the -- function given as the first argument, instead of a tupling function. -- Performs replacement on invalid scalar values. zipWith :: Char -> Char -> Char -> Text -> Text -> Text -- | This isomorphism can be used to pack (or unpack) strict -- Text. -- --
--   >>> "hello"^.packed -- :: Text
--   "hello"
--   
-- --
--   pack x ≡ x ^. packed
--   unpack x ≡ x ^. from packed
--   packedfrom unpacked
--   packediso pack unpack
--   
packed :: Iso' String Text -- | This isomorphism can be used to unpack (or pack) lazy -- Text. -- --
--   >>> "hello"^.unpacked -- :: String
--   "hello"
--   
-- -- This Iso is provided for notational convenience rather than out -- of great need, since -- --
--   unpackedfrom packed
--   
-- --
--   pack x ≡ x ^. from unpacked
--   unpack x ≡ x ^. packed
--   unpackediso unpack pack
--   
unpacked :: Iso' Text String -- | Traverse the individual characters in strict Text. -- --
--   >>> anyOf text (=='o') "hello"
--   True
--   
-- -- When the type is unambiguous, you can also use the more general -- each. -- --
--   textunpacked . traversed
--   texteach
--   
-- -- Note that when just using this as a Setter, setting -- map can be more efficient. text :: IndexedTraversal' Int Text Char -- | Convert between strict Text and Builder . -- --
--   fromText x ≡ x ^. builder
--   toStrict (toLazyText x) ≡ x ^. from builder
--   
builder :: Iso' Text Builder module Text.Lazy -- | This isomorphism can be used to pack (or unpack) lazy -- Text. -- --
--   >>> "hello"^.packed -- :: Text
--   "hello"
--   
-- --
--   pack x ≡ x ^. packed
--   unpack x ≡ x ^. from packed
--   packedfrom unpacked
--   
packed :: Iso' String Text -- | This isomorphism can be used to unpack (or pack) lazy -- Text. -- --
--   >>> "hello"^.unpacked -- :: String
--   "hello"
--   
-- --
--   pack x ≡ x ^. from unpacked
--   unpack x ≡ x ^. packed
--   
-- -- This Iso is provided for notational convenience rather than out -- of great need, since -- --
--   unpackedfrom packed
--   
unpacked :: Iso' Text String -- | Traverse the individual characters in a Text. -- --
--   >>> anyOf text (=='c') "chello"
--   True
--   
-- --
--   text = unpacked . traversed
--   
-- -- When the type is unambiguous, you can also use the more general -- each. -- --
--   texteach
--   
-- -- Note that when just using this as a Setter, setting -- map can be more efficient. text :: IndexedTraversal' Int Text Char -- | Convert between lazy Text and Builder . -- --
--   fromLazyText x ≡ x ^. builder
--   toLazyText x ≡ x ^. from builder
--   
builder :: Iso' Text Builder module Text.Lazy.Builder -- | A Builder is an efficient way to build lazy Text -- values. There are several functions for constructing builders, but -- only one to inspect them: to extract any data, you have to turn them -- into lazy Text values using toLazyText. -- -- Internally, a builder constructs a lazy Text by filling -- arrays piece by piece. As each buffer is filled, it is 'popped' off, -- to become a new chunk of the resulting lazy Text. All this is -- hidden from the user of the Builder. data Builder -- | O(n). Extract a lazy Text from a Builder with -- a default buffer size. The construction work takes place if and when -- the relevant part of the lazy Text is demanded. toLazyText :: Builder -> Text -- | O(n). Extract a lazy Text from a Builder, -- using the given size for the initial buffer. The construction work -- takes place if and when the relevant part of the lazy Text is -- demanded. -- -- If the initial buffer is too small to hold all data, subsequent -- buffers will be the default buffer size. toLazyTextWith :: Int -> Builder -> Text -- | O(1). A Builder taking a single character, satisfying -- -- singleton :: Char -> Builder -- | O(1). A Builder taking a Text, satisfying -- -- fromText :: Text -> Builder -- | O(1). A Builder taking a lazy Text, -- satisfying -- -- fromLazyText :: Text -> Builder -- | O(1). A Builder taking a String, satisfying -- -- fromString :: String -> Builder -- | O(1). Pop the strict Text we have constructed so far, -- if any, yielding a new chunk in the result lazy Text. flush :: Builder decimal :: Integral a => a -> Builder hexadecimal :: Integral a => a -> Builder -- | Control the rendering of floating point numbers. data FPFormat -- | Scientific notation (e.g. 2.3e123). Exponent :: FPFormat -- | Standard decimal notation. Fixed :: FPFormat -- | Use decimal notation for values between 0.1 and -- 9,999,999, and scientific notation otherwise. Generic :: FPFormat -- | Show a signed RealFloat value to full precision, using standard -- decimal notation for arguments whose absolute value lies between -- 0.1 and 9,999,999, and scientific notation -- otherwise. realFloat :: RealFloat a => a -> Builder formatRealFloat :: RealFloat a => FPFormat -> Maybe Int -> a -> Builder module Text.Partial -- | O(n+m) The count function returns the number of times -- the query string appears in the given Text. An empty query -- string is invalid, and will cause an error to be raised. -- -- In (unlikely) bad cases, this function's time complexity degrades -- towards O(n*m). count :: Text -> Text -> Int -- | Decode a ByteString containing Latin-1 (aka ISO-8859-1) encoded -- text. -- -- decodeLatin1 is semantically equivalent to Data.Text.pack . -- Data.ByteString.Char8.unpack decodeLatin1 :: ByteString -> Text -- | Decode text from big endian UTF-16 encoding. -- -- If the input contains any invalid big endian UTF-16 data, an exception -- will be thrown. For more control over the handling of invalid data, -- use decodeUtf16BEWith. decodeUtf16BE :: ByteString -> Text -- | Decode text from little endian UTF-16 encoding. -- -- If the input contains any invalid little endian UTF-16 data, an -- exception will be thrown. For more control over the handling of -- invalid data, use decodeUtf16LEWith. decodeUtf16LE :: ByteString -> Text -- | Decode text from big endian UTF-32 encoding. -- -- If the input contains any invalid big endian UTF-32 data, an exception -- will be thrown. For more control over the handling of invalid data, -- use decodeUtf32BEWith. decodeUtf32BE :: ByteString -> Text -- | Decode text from little endian UTF-32 encoding. -- -- If the input contains any invalid little endian UTF-32 data, an -- exception will be thrown. For more control over the handling of -- invalid data, use decodeUtf32LEWith. decodeUtf32LE :: ByteString -> Text -- | Decode a ByteString containing UTF-8 encoded text that is known -- to be valid. -- -- If the input contains any invalid UTF-8 data, an exception will be -- thrown that cannot be caught in pure code. For more control over the -- handling of invalid data, use decodeUtf8' or -- decodeUtf8With. decodeUtf8 :: ByteString -> Text -- | O(n) A strict version of foldl1. Subject to fusion. foldl1' :: Char -> Char -> Char -> Text -> Char -- | O(n) A variant of foldr that has no starting value -- argument, and thus must be applied to a non-empty Text. Subject -- to fusion. foldr1 :: Char -> Char -> Char -> Text -> Char -- | O(1) Returns the first character of a Text, which must -- be non-empty. Subject to fusion. head :: Text -> Char -- | O(n) Text index (subscript) operator, starting from 0. index :: Text -> Int -> Char -- | O(1) Returns all but the last character of a Text, which -- must be non-empty. Subject to fusion. init :: Text -> Text -- | O(1) Returns the last character of a Text, which must be -- non-empty. Subject to fusion. last :: Text -> Char -- | O(n) maximum returns the maximum value from a -- Text, which must be non-empty. Subject to fusion. maximum :: Text -> Char -- | O(n) minimum returns the minimum value from a -- Text, which must be non-empty. Subject to fusion. minimum :: Text -> Char -- | O(m+n) Break a Text into pieces separated by the first -- Text argument (which cannot be empty), consuming the delimiter. -- An empty delimiter is invalid, and will cause an error to be raised. -- -- Examples: -- --
--   >>> splitOn "\r\n" "a\r\nb\r\nd\r\ne"
--   ["a","b","d","e"]
--   
-- --
--   >>> splitOn "aaa"  "aaaXaaaXaaaXaaa"
--   ["","X","X","X",""]
--   
-- --
--   >>> splitOn "x"    "x"
--   ["",""]
--   
-- -- and -- --
--   intercalate s . splitOn s         == id
--   splitOn (singleton c)             == split (==c)
--   
-- -- (Note: the string s to split on above cannot be empty.) -- -- In (unlikely) bad cases, this function's time complexity degrades -- towards O(n*m). splitOn :: Text -> Text -> [Text] -- | O(1) Returns all characters after the head of a Text, -- which must be non-empty. Subject to fusion. tail :: Text -> Text module Text.Short module Text.Short.Partial module Text.Short.Unsafe module Time module Traversable -- | Functors representing data structures that can be traversed from left -- to right. -- -- A definition of traverse must satisfy the following laws: -- -- -- -- A definition of sequenceA must satisfy the following laws: -- -- -- -- where an applicative transformation is a function -- --
--   t :: (Applicative f, Applicative g) => f a -> g a
--   
-- -- preserving the Applicative operations, i.e. -- -- -- -- and the identity functor Identity and composition of functors -- Compose are defined as -- --
--   newtype Identity a = Identity a
--   
--   instance Functor Identity where
--     fmap f (Identity x) = Identity (f x)
--   
--   instance Applicative Identity where
--     pure x = Identity x
--     Identity f <*> Identity x = Identity (f x)
--   
--   newtype Compose f g a = Compose (f (g a))
--   
--   instance (Functor f, Functor g) => Functor (Compose f g) where
--     fmap f (Compose x) = Compose (fmap (fmap f) x)
--   
--   instance (Applicative f, Applicative g) => Applicative (Compose f g) where
--     pure x = Compose (pure (pure x))
--     Compose f <*> Compose x = Compose ((<*>) <$> f <*> x)
--   
-- -- (The naturality law is implied by parametricity.) -- -- Instances are similar to Functor, e.g. given a data type -- --
--   data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
--   
-- -- a suitable instance would be -- --
--   instance Traversable Tree where
--      traverse f Empty = pure Empty
--      traverse f (Leaf x) = Leaf <$> f x
--      traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r
--   
-- -- This is suitable even for abstract types, as the laws for -- <*> imply a form of associativity. -- -- The superclass instances should satisfy the following: -- -- class (Functor t, Foldable t) => Traversable (t :: * -> *) -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and collect the results. For a version that -- ignores the results see traverse_. traverse :: (Traversable t, Applicative f) => a -> f b -> t a -> f t b -- | Evaluate each action in the structure from left to right, and and -- collect the results. For a version that ignores the results see -- sequenceA_. sequenceA :: (Traversable t, Applicative f) => t f a -> f t 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 -- | The mapAccumL function behaves like a combination of -- fmap and foldl; it applies a function to each element -- of a structure, passing an accumulating parameter from left to right, -- and returning a final value of this accumulator together with the new -- structure. mapAccumL :: Traversable t => a -> b -> (a, c) -> a -> t b -> (a, t c) -- | The mapAccumR function behaves like a combination of -- fmap and foldr; it applies a function to each element -- of a structure, passing an accumulating parameter from right to left, -- and returning a final value of this accumulator together with the new -- structure. mapAccumR :: Traversable t => a -> b -> (a, c) -> a -> t b -> (a, t c) -- | Traverse a container using its Traversable instance using -- explicitly provided Applicative operations. This is like -- traverse where the Applicative instance can be manually -- specified. traverseBy :: Traversable t => forall x. () => x -> f x -> forall x y. () => f x -> y -> f x -> f y -> a -> f b -> t a -> f t b -- | Sequence a container using its Traversable instance using -- explicitly provided Applicative operations. This is like -- sequence where the Applicative instance can be manually -- specified. sequenceBy :: Traversable t => forall x. () => x -> f x -> forall x y. () => f x -> y -> f x -> f y -> t f a -> f t a -- | 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 -- | 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 class (Foldable1 t, Traversable t) => Traversable1 (t :: * -> *) traverse1 :: (Traversable1 t, Apply f) => a -> f b -> t a -> f t b sequence1 :: (Traversable1 t, Apply f) => t f b -> f t b module Tree -- | Flatten a Tree, returning the elements in post-order. postorder :: () => Tree a -> [a] -- | Flatten multiple Trees in post-order. postorderF :: () => [Tree a] -> [a] -- | Flatten a Tree, returning the elements in pre-order. Equivalent -- to flatten in Tree. preorder :: () => Tree a -> [a] -- | Flatten multiple Trees in pre-order. preorderF :: () => [Tree a] -> [a] -- | A Lens that focuses on the root of a Tree. -- --
--   >>> view root $ Node 42 []
--   42
--   
root :: Functor f => a -> f a -> Tree a -> f Tree a -- | A Lens returning the direct descendants of the root of a -- Tree -- --
--   view branchessubForest
--   
branches :: Functor f => [Tree a] -> f [Tree a] -> Tree a -> f Tree a module Tuple -- | Extract the first component of a pair. fst :: () => (a, b) -> a -- | Extract the second component of a pair. snd :: () => (a, b) -> b -- | 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 -- | Swap the components of a pair. swap :: () => (a, b) -> (b, a) -- | Duplicate a single value into a pair. -- --
--   dupe 12 == (12, 12)
--   
dupe :: () => a -> (a, a) -- | Provides access to 1st field of a tuple. class Field1 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | 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 -- | Strict version of _1 _1' :: Field1 s t a b => Lens s t a b -- | Provides access to the 2nd field of a tuple. class Field2 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | 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 -- | Strict version of _2 _2' :: Field2 s t a b => Lens s t a b -- | Provides access to the 3rd field of a tuple. class Field3 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 3rd field of a tuple. _3 :: Field3 s t a b => Lens s t a b -- | Strict version of _3 _3' :: Field3 s t a b => Lens s t a b -- | Provide access to the 4th field of a tuple. class Field4 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 4th field of a tuple. _4 :: Field4 s t a b => Lens s t a b -- | Strict version of _4 _4' :: Field4 s t a b => Lens s t a b -- | Provides access to the 5th field of a tuple. class Field5 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 5th field of a tuple. _5 :: Field5 s t a b => Lens s t a b -- | Strict version of _5 _5' :: Field5 s t a b => Lens s t a b -- | Provides access to the 6th element of a tuple. class Field6 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 6th field of a tuple. _6 :: Field6 s t a b => Lens s t a b -- | Strict version of _6 _6' :: Field6 s t a b => Lens s t a b -- | Provide access to the 7th field of a tuple. class Field7 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 7th field of a tuple. _7 :: Field7 s t a b => Lens s t a b -- | Strict version of _7 _7' :: Field7 s t a b => Lens s t a b -- | Provide access to the 8th field of a tuple. class Field8 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 8th field of a tuple. _8 :: Field8 s t a b => Lens s t a b -- | Strict version of _8 _8' :: Field8 s t a b => Lens s t a b -- | Provides access to the 9th field of a tuple. class Field9 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 9th field of a tuple. _9 :: Field9 s t a b => Lens s t a b -- | Strict version of _9 _9' :: Field9 s t a b => Lens s t a b -- | Provides access to the 10th field of a tuple. class Field10 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 10th field of a tuple. _10 :: Field10 s t a b => Lens s t a b -- | Strict version of _10 _10' :: Field10 s t a b => Lens s t a b -- | Provides access to the 11th field of a tuple. class Field11 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 11th field of a tuple. _11 :: Field11 s t a b => Lens s t a b -- | Strict version of _11 _11' :: Field11 s t a b => Lens s t a b -- | Provides access to the 12th field of a tuple. class Field12 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 12th field of a tuple. _12 :: Field12 s t a b => Lens s t a b -- | Strict version of _12 _12' :: Field12 s t a b => Lens s t a b -- | Provides access to the 13th field of a tuple. class Field13 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 13th field of a tuple. _13 :: Field13 s t a b => Lens s t a b -- | Strict version of _13 _13' :: Field13 s t a b => Lens s t a b -- | Provides access to the 14th field of a tuple. class Field14 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 14th field of a tuple. _14 :: Field14 s t a b => Lens s t a b -- | Strict version of _14 _14' :: Field14 s t a b => Lens s t a b -- | Provides access to the 15th field of a tuple. class Field15 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 15th field of a tuple. _15 :: Field15 s t a b => Lens s t a b -- | Strict version of _15 _15' :: Field15 s t a b => Lens s t a b -- | Provides access to the 16th field of a tuple. class Field16 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 16th field of a tuple. _16 :: Field16 s t a b => Lens s t a b -- | Strict version of _16 _16' :: Field16 s t a b => Lens s t a b -- | Provides access to the 17th field of a tuple. class Field17 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 17th field of a tuple. _17 :: Field17 s t a b => Lens s t a b -- | Strict version of _17 _17' :: Field17 s t a b => Lens s t a b -- | Provides access to the 18th field of a tuple. class Field18 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 18th field of a tuple. _18 :: Field18 s t a b => Lens s t a b -- | Strict version of _18 _18' :: Field18 s t a b => Lens s t a b -- | Provides access to the 19th field of a tuple. class Field19 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 19th field of a tuple. _19 :: Field19 s t a b => Lens s t a b -- | Strict version of _19 _19' :: Field19 s t a b => Lens s t a b module Type -- | The kind of types with values. For example Int :: Type. type Type = * -- | The type-level equivalent of error. -- -- The polymorphic kind of this type allows it to be used in several -- settings. For instance, it can be used as a constraint, e.g. to -- provide a better error message for a non-existent instance, -- --
--   -- in a context
--   instance TypeError (Text "Cannot Show functions." :$$:
--                       Text "Perhaps there is a missing argument?")
--         => Show (a -> b) where
--       showsPrec = error "unreachable"
--   
-- -- It can also be placed on the right-hand side of a type-level function -- to provide an error for an invalid case, -- --
--   type family ByteSize x where
--      ByteSize Word16   = 2
--      ByteSize Word8    = 1
--      ByteSize a        = TypeError (Text "The type " :<>: ShowType a :<>:
--                                     Text " is not exportable.")
--   
-- | A description of a custom type error. data ErrorMessage -- | Show the text as is. [Text] :: ErrorMessage -- | Pretty print the type. ShowType :: k -> ErrorMessage [ShowType] :: ErrorMessage -- | Put two pieces of error message next to each other. [:<>:] :: ErrorMessage -- | Stack two pieces of error message on top of each other. [:$$:] :: ErrorMessage module Typeable -- | The class Typeable allows a concrete representation of a type -- to be calculated. class Typeable (a :: k) -- | The type-safe cast operation cast :: (Typeable a, Typeable b) => a -> Maybe b -- | Extract a witness of equality of two types eqT :: (Typeable a, Typeable b) => Maybe a :~: b -- | A flexible variation parameterised in a type constructor gcast :: (Typeable a, Typeable b) => c a -> Maybe c b -- | Cast over k1 -> k2 gcast1 :: (Typeable t, Typeable t') => c t a -> Maybe c t' a -- | Cast over k1 -> k2 -> k3 gcast2 :: (Typeable t, Typeable t') => c t a b -> Maybe c t' a b -- | A concrete representation of a (monomorphic) type. TypeRep -- supports reasonably efficient equality. data TypeRep (a :: k) :: forall k. () => k -> * typeRep :: Typeable a => TypeRep a typeOf :: Typeable a => a -> TypeRep a -- | Use a TypeRep as Typeable evidence. withTypeable :: () => TypeRep a -> Typeable a -> r -> r -- | A type application. -- -- For instance, -- --
--   typeRep @(Maybe Int) === App (typeRep @Maybe) (typeRep @Int)
--   
-- -- Note that this will also match a function type, -- --
--   typeRep @(Int# -> Char)
--     ===
--   App (App arrow (typeRep @Int#)) (typeRep @Char)
--   
-- -- where arrow :: TypeRep ((->) :: TYPE IntRep -> Type -> -- Type). -- | Pattern match on a type constructor -- | Pattern match on a type constructor including its instantiated kind -- variables. -- -- For instance, -- --
--   App (Con' proxyTyCon ks) intRep = typeRep @(Proxy @Int)
--   
-- -- will bring into scope, -- --
--   proxyTyCon :: TyCon
--   ks         == [someTypeRep Type] :: [SomeTypeRep]
--   intRep     == typeRep Int
--   
-- | The function type constructor. -- -- For instance, -- --
--   typeRep @(Int -> Char) === Fun (typeRep @Int) (typeRep @Char)
--   
-- | Observe the type constructor of a type representation typeRepTyCon :: () => TypeRep a -> TyCon -- | Helper to fully evaluate TypeRep for use as -- NFData(rnf) implementation rnfTypeRep :: () => TypeRep a -> () -- | Type equality eqTypeRep :: () => TypeRep a -> TypeRep b -> Maybe a :~~: b -- | Observe the kind of a type. typeRepKind :: () => TypeRep a -> TypeRep k splitApps :: () => TypeRep a -> (TyCon, [SomeTypeRep]) -- | A non-indexed type representation. data SomeTypeRep [SomeTypeRep] :: SomeTypeRep -- | Takes a value of type a and returns a concrete representation -- of that type. someTypeRep :: Typeable a => proxy a -> SomeTypeRep -- | Observe the type constructor of a quantified type representation. someTypeRepTyCon :: SomeTypeRep -> TyCon -- | Helper to fully evaluate SomeTypeRep for use as -- NFData(rnf) implementation rnfSomeTypeRep :: SomeTypeRep -> () data TyCon tyConPackage :: TyCon -> String tyConModule :: TyCon -> String tyConName :: TyCon -> String rnfTyCon :: TyCon -> () data Module moduleName :: Module -> String modulePackage :: Module -> String -- | Helper to fully evaluate TyCon for use as NFData(rnf) -- implementation rnfModule :: Module -> () -- | A Traversal' for working with a cast of a -- Typeable value. _cast :: (Typeable s, Typeable a) => Traversal' s a -- | A Traversal' for working with a gcast of a -- Typeable value. _gcast :: (Typeable s, Typeable a) => Traversal' c s c a module URI module UUID -- | The UUID type. A Random instance is provided which produces -- version 4 UUIDs as specified in RFC 4122. The Storable and -- Binary instances are compatible with RFC 4122, storing the -- fields in network order as 16 bytes. data UUID -- | Convert a UUID into a hyphentated string using lower-case letters. toText :: UUID -> Text -- | If the passed in Text can be parsed as an ASCII representation -- of a UUID, it will be. The hyphens may not be omitted. fromText :: Text -> Maybe UUID -- | Encode a UUID into a ByteString in network order. toByteString :: UUID -> ByteString -- | Extract a UUID from a ByteString in network byte order. The -- argument must be 16 bytes long, otherwise Nothing is returned. fromByteString :: ByteString -> Maybe UUID -- | Covert a UUID into a sequence of Word32 values. Useful -- for when you need to serialize a UUID and neither Storable nor -- Binary are appropriate. Introduced in version 1.2.2. toWords :: UUID -> (Word32, Word32, Word32, Word32) -- | Create a UUID from a sequence of Word32. The opposite of -- toWords. Useful when you need a total function for constructing -- UUID values. Introduced in version 1.2.2. fromWords :: Word32 -> Word32 -> Word32 -> Word32 -> UUID -- | Returns true if the passed-in UUID is the nil UUID. null :: UUID -> Bool -- | The nil UUID, as defined in RFC 4122. It is a UUID of all zeros. -- null u iff u == nil. nil :: UUID -- | Generate a UUID within the specified namespace out of the given -- object. -- -- Uses a SHA1 hash. The UUID is built from first 128 bits of the hash of -- the namespace UUID and the name (as a series of Word8). generateNamed :: UUID -> [Word8] -> UUID -- | The namespace for DNS addresses namespaceDNS :: UUID -- | The namespace for URLs namespaceURL :: UUID -- | The namespace for ISO OIDs namespaceOID :: UUID -- | The namespace for X.500 DNs namespaceX500 :: UUID module Unique -- | An abstract unique object. Objects of type Unique may be -- compared for equality and ordering and hashed into Int. -- --
--   >>> :{
--   do x <- newUnique
--      print (x == x)
--      y <- newUnique
--      print (x == y)
--   :}
--   True
--   False
--   
data Unique -- | Creates a new object of type Unique. The value returned will -- not compare equal to any other value of type Unique returned by -- previous calls to newUnique. There is no limit on the number of -- times newUnique may be called. newUnique :: IO Unique -- | Hashes a Unique into an Int. Two Uniques may hash -- to the same value, although in practice this is unlikely. The -- Int returned makes a good hash key. hashUnique :: Unique -> Int module Vault module Vault.Lazy module Vector -- | Similar to toListOf, but returning a Vector. -- --
--   >>> toVectorOf both (8,15) == Vector.fromList [8,15]
--   True
--   
toVectorOf :: () => Getting Endo [a] s a -> s -> Vector a -- | Convert a list to a Vector (or back) -- --
--   >>> [1,2,3] ^. vector == Vector.fromList [1,2,3]
--   True
--   
-- --
--   >>> [1,2,3] ^. vector . from vector
--   [1,2,3]
--   
-- --
--   >>> Vector.fromList [0,8,15] ^. from vector . vector == Vector.fromList [0,8,15]
--   True
--   
vector :: (Profunctor p, Functor f) => p Vector a f Vector b -> p [a] f [b] -- | Convert a Vector to a version that doesn't retain any extra -- memory. forced :: (Profunctor p, Functor f) => p Vector a f Vector b -> p Vector a f Vector b -- | sliced i n provides a Lens that edits the n -- elements starting at index i from a Lens. -- -- This is only a valid Lens if you do not change the length of -- the resulting Vector. -- -- Attempting to return a longer or shorter vector will result in -- violations of the Lens laws. -- --
--   >>> Vector.fromList [1..10] ^. sliced 2 5 == Vector.fromList [3,4,5,6,7]
--   True
--   
-- --
--   >>> (Vector.fromList [1..10] & sliced 2 5 . mapped .~ 0) == Vector.fromList [1,2,0,0,0,0,0,8,9,10]
--   True
--   
sliced :: () => Int -> Int -> Lens' Vector a Vector a module Vector.Builder -- | An abstraction over the size of a vector for the process of its -- construction. -- -- It postpones the actual construction of a vector until the execution -- of the builder. data Builder element -- | Empty builder. empty :: () => Builder element -- | Builder of a single element. singleton :: () => element -> Builder element -- | Builder from an immutable vector of elements. -- -- Supports all kinds of vectors: boxed, unboxed, primitive, storable. vector :: Vector vector element => vector element -> Builder element module Vector.Generic -- | Construct an immutable vector from a builder. -- -- Supports all kinds of vectors: boxed, unboxed, primitive, storable. build :: Vector vector element => Builder element -> vector element module Vector.Generic.Mutable -- | Construct a mutable vector from a builder. -- -- Supports all kinds of vectors: boxed, unboxed, primitive, storable. build :: MVector vector element => Builder element -> ST s vector s element module Vector.Mutable module Vector.Primitive module Vector.Storable module Vector.Unboxed module Void -- | Uninhabited data type data Void -- | 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. vacuous :: Functor f => f Void -> f a module Mitchell.Prelude -- | Identity functor and monad. (a non-strict monad) newtype Identity a Identity :: a -> Identity a [runIdentity] :: Identity a -> 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 :: * -> *) -- | Lift a value. pure :: Applicative f => a -> f a -- | Sequential application. -- -- A few functors support an implementation of <*> that is -- more efficient than the default one. (<*>) :: Applicative f => f a -> b -> f a -> f b -- | Lift a binary function to actions. -- -- Some functors support an implementation of liftA2 that is more -- efficient than the default one. In particular, if fmap is an -- expensive operation, it is likely better to use liftA2 than to -- fmap over the structure and then use <*>. liftA2 :: Applicative f => a -> b -> c -> f a -> f b -> f c -- | Sequence actions, discarding the value of the first argument. (*>) :: Applicative f => f a -> f b -> f b -- | Sequence actions, discarding the value of the second argument. (<*) :: Applicative f => f a -> f b -> f a -- | This generalizes the list-based filter function. filterM :: Applicative m => a -> m Bool -> [a] -> m [a] -- | forever act repeats the action infinitely. forever :: Applicative f => f a -> f b -- | Lift a ternary function to actions. liftA3 :: Applicative f => a -> b -> c -> d -> f a -> f b -> f c -> f d -- | replicateM n act performs the action n times, -- gathering the results. replicateM :: Applicative m => Int -> m a -> m [a] -- | Like replicateM, but discards the result. replicateM_ :: Applicative m => Int -> m a -> m () -- | The reverse of when. unless :: Applicative f => Bool -> f () -> f () -- | 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 () -- | 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 () -- | A monoid on applicative functors. -- -- If defined, some and many should be the least solutions -- of the equations: -- -- class Applicative f => Alternative (f :: * -> *) -- | The identity of <|> empty :: Alternative f => f a -- | An associative binary operation (<|>) :: Alternative f => f a -> f a -> f a -- | 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 () -- | One or none. optional :: (Alt f, Applicative f) => f a -> f Maybe a data Bool False :: Bool True :: Bool -- | Boolean "and" (&&) :: Bool -> Bool -> Bool infixr 3 && -- | Boolean "or" (||) :: Bool -> Bool -> Bool infixr 2 || -- | Boolean "not" not :: Bool -> Bool -- | otherwise is defined as the value True. It helps to make -- guards more readable. eg. -- --
--   f x | x < 0     = ...
--       | otherwise = ...
--   
otherwise :: Bool -- | 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 -- | 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 class for categories. Instances should satisfy the laws -- --
--   f . id  =  f  -- (right identity)
--   id . f  =  f  -- (left identity)
--   f . (g . h)  =  (f . g) . h  -- (associativity)
--   
class Category (cat :: k -> k -> *) -- | the identity morphism id :: Category cat => cat a a -- | morphism composition (.) :: Category cat => cat b c -> cat a b -> cat a c -- | Left-to-right composition (>>>) :: Category cat => cat a b -> cat b c -> cat a c infixr 1 >>> -- | Right-to-left composition (<<<) :: Category cat => cat b c -> cat a b -> cat a c infixr 1 <<< -- | 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 -- | Return monotonic time in seconds, since some unspecified starting -- point getMonotonicTime :: IO Double -- | Return monotonic time in nanoseconds, since some unspecified starting -- point getMonotonicTimeNSec :: IO Word64 -- | Coercible is a two-parameter class that has instances for -- types a and b if the compiler can infer that they -- have the same representation. This class does not have regular -- instances; instead they are created on-the-fly during type-checking. -- Trying to manually declare an instance of Coercible is an -- error. -- -- Nevertheless one can pretend that the following three kinds of -- instances exist. First, as a trivial base-case: -- --
--   instance Coercible a a
--   
-- -- Furthermore, for every type constructor there is an instance that -- allows to coerce under the type constructor. For example, let -- D be a prototypical type constructor (data or -- newtype) with three type arguments, which have roles -- nominal, representational resp. phantom. -- Then there is an instance of the form -- --
--   instance Coercible b b' => Coercible (D a b c) (D a b' c')
--   
-- -- Note that the nominal type arguments are equal, the -- representational type arguments can differ, but need to have -- a Coercible instance themself, and the phantom type -- arguments can be changed arbitrarily. -- -- The third kind of instance exists for every newtype NT = MkNT -- T and comes in two variants, namely -- --
--   instance Coercible a T => Coercible a NT
--   
-- --
--   instance Coercible T b => Coercible NT b
--   
-- -- This instance is only usable if the constructor MkNT is in -- scope. -- -- If, as a library author of a type constructor like Set a, you -- want to prevent a user of your module to write coerce :: Set T -- -> Set NT, you need to set the role of Set's type -- parameter to nominal, by writing -- --
--   type role Set nominal
--   
-- -- For more details about this feature, please refer to Safe -- Coercions by Joachim Breitner, Richard A. Eisenberg, Simon Peyton -- Jones and Stephanie Weirich. class a ~R# b => Coercible (a :: k0) (b :: k0) -- | The function coerce allows you to safely convert between -- values of types that have the same representation with no run-time -- overhead. In the simplest case you can use it instead of a newtype -- constructor, to go from the newtype's concrete type to the abstract -- type. But it also works in more complicated settings, e.g. converting -- a list of newtypes to a list of concrete types. coerce :: Coercible a b => a -> b -- | The trace function outputs the trace message given as its first -- argument, before returning the second argument as its result. -- -- For example, this returns the value of f x but first outputs -- the message. -- --
--   >>> let x = 123; f = show
--   
--   >>> trace ("calling f with x = " ++ show x) (f x)
--   "calling f with x = 123
--   123"
--   
-- -- The trace function should only be used for debugging, or -- for monitoring execution. The function is not referentially -- transparent: its type indicates that it is a pure function but it has -- the side effect of outputting the trace message. trace :: () => String -> a -> a -- | Like trace but returns the message instead of a third value. -- --
--   >>> traceId "hello"
--   "hello
--   hello"
--   
traceId :: String -> String -- | Like trace, but uses show on the argument to convert it -- to a String. -- -- This makes it convenient for printing the values of interesting -- variables or expressions inside a function. For example here we print -- the value of the variables x and y: -- --
--   >>> let f x y = traceShow (x,y) (x + y) in f (1+2) 5
--   (3,5)
--   8
--   
traceShow :: Show a => a -> b -> b -- | Like traceShow but returns the shown value instead of a third -- value. -- --
--   >>> traceShowId (1+2+3, "hello" ++ "world")
--   (6,"helloworld")
--   (6,"helloworld")
--   
traceShowId :: Show a => a -> a -- | like trace, but additionally prints a call stack if one is -- available. -- -- In the current GHC implementation, the call stack is only available if -- the program was compiled with -prof; otherwise -- traceStack behaves exactly like trace. Entries in the -- call stack correspond to SCC annotations, so it is a good -- idea to use -fprof-auto or -fprof-auto-calls to add -- SCC annotations automatically. traceStack :: () => String -> a -> a -- | Like trace but returning unit in an arbitrary -- Applicative context. Allows for convenient use in do-notation. -- -- Note that the application of traceM is not an action in the -- Applicative context, as traceIO is in the IO -- type. While the fresh bindings in the following example will force the -- traceM expressions to be reduced every time the -- do-block is executed, traceM "not crashed" would -- only be reduced once, and the message would only be printed once. If -- your monad is in MonadIO, liftIO . traceIO may be a -- better option. -- --
--   >>> :{
--   do
--       x <- Just 3
--       traceM ("x: " ++ show x)
--       y <- pure 12
--       traceM ("y: " ++ show y)
--       pure (x*2 + y)
--   :}
--   x: 3
--   y: 12
--   Just 18
--   
traceM :: Applicative f => String -> f () -- | Like traceM, but uses show on the argument to convert it -- to a String. -- --
--   >>> :{
--   do
--       x <- Just 3
--       traceShowM x
--       y <- pure 12
--       traceShowM y
--       pure (x*2 + y)
--   :}
--   3
--   12
--   Just 18
--   
traceShowM :: (Show a, Applicative f) => a -> f () -- | 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 -- | 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 -- | Monadic generalisation of either. eitherM :: Monad m => a -> m c -> b -> m c -> m Either a b -> m c -- | This Prism provides a Traversal for tweaking the -- Left half of an Either: -- --
--   >>> over _Left (+1) (Left 2)
--   Left 3
--   
-- --
--   >>> over _Left (+1) (Right 2)
--   Right 2
--   
-- --
--   >>> Right 42 ^._Left :: String
--   ""
--   
-- --
--   >>> Left "hello" ^._Left
--   "hello"
--   
-- -- It also can be turned around to obtain the embedding into the -- Left half of an Either: -- --
--   >>> _Left # 5
--   Left 5
--   
-- --
--   >>> 5^.re _Left
--   Left 5
--   
_Left :: (Choice p, Applicative f) => p a f b -> p Either a c f Either b c -- | This Prism provides a Traversal for tweaking the -- Right half of an Either: -- --
--   >>> over _Right (+1) (Left 2)
--   Left 2
--   
-- --
--   >>> over _Right (+1) (Right 2)
--   Right 3
--   
-- --
--   >>> Right "hello" ^._Right
--   "hello"
--   
-- --
--   >>> Left "hello" ^._Right :: [Double]
--   []
--   
-- -- It also can be turned around to obtain the embedding into the -- Right half of an Either: -- --
--   >>> _Right # 5
--   Right 5
--   
-- --
--   >>> 5^.re _Right
--   Right 5
--   
_Right :: (Choice p, Applicative f) => p a f b -> p Either c a f Either c b -- | 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..]. enumFrom :: Enum a => a -> [a] -- | Used in Haskell's translation of [n,n'..]. enumFromThen :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n..m]. enumFromTo :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n,n'..m]. 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. -- -- Minimal complete definition: either == or /=. class Eq a (==) :: Eq a => a -> a -> Bool (/=) :: Eq a => a -> a -> Bool -- | If the first argument evaluates to True, then the result is the -- second argument. Otherwise an AssertionFailed exception is -- raised, containing a String with the source file and line -- number of the call to assert. -- -- Assertions can normally be turned on or off with a compiler flag (for -- GHC, assertions are normally on unless optimisation is turned on with -- -O or the -fignore-asserts option is given). When -- assertions are turned off, the first argument to assert is -- ignored, and the second argument is returned as the result. assert :: () => Bool -> a -> a -- | error stops execution and displays an error message. error :: HasCallStack => [Char] -> a -- | A special case of error. It is expected that compilers will -- recognize this and insert error messages which are more appropriate to -- the context in which undefined appears. undefined :: HasCallStack => a -- | 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 -- | 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] :: SomeException -- | Superclass for asynchronous exceptions. data SomeAsyncException [SomeAsyncException] :: SomeAsyncException -- | Synchronously throw the given exception. throwIO :: (MonadIO m, Exception e) => e -> m a -- | A handle managing input from the Haskell program's standard input -- channel. stdin :: Handle -- | A handle managing output to the Haskell program's standard output -- channel. stdout :: Handle -- | A handle managing output to the Haskell program's standard error -- channel. stderr :: Handle -- | Computation hGetChar hdl reads a character from the -- file or channel managed by hdl, blocking until a character is -- available. -- -- This operation may fail with: -- -- hGetChar :: Handle -> IO Char -- | Read a single line from a handle. hGetLine :: Handle -> IO Text -- | Read the remaining contents of a Handle as a string. The -- Handle is closed once the contents have been read, or if an -- exception is thrown. -- -- Internally, this function reads a chunk at a time from the lower-level -- buffering abstraction, and concatenates the chunks into a single -- string once the entire file has been read. -- -- As a result, it requires approximately twice as much memory as its -- result to construct its result. For files more than a half of -- available RAM in size, this may result in memory exhaustion. hGetContents :: Handle -> IO Text -- | Write a string to stdout. putStr :: Text -> IO () -- | Write a string to stdout, followed by a newline. putStrLn :: Text -> IO () -- | The print function outputs a value of any printable type to the -- standard output device. Printable types are those that are instances -- of class Show; print converts values to strings for -- output using the show operation and adds a newline. -- -- For example, a program to print the first 20 integers and their powers -- of 2 could be written as: -- --
--   main = print ([(n, 2^n) | n <- [0..19]])
--   
print :: Show a => a -> IO () -- | Write a string to a handle. hPutStr :: Handle -> Text -> IO () -- | Write a string to a handle, followed by a newline. hPutStrLn :: Handle -> Text -> IO () -- | Computation hPrint hdl t writes the string -- representation of t given by the shows function to the -- file or channel managed by hdl and appends a newline. -- -- This operation may fail with: -- -- hPrint :: Show a => Handle -> a -> IO () -- | Data structures that can be folded. -- -- For example, given a data type -- --
--   data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
--   
-- -- a suitable instance would be -- --
--   instance Foldable Tree where
--      foldMap f Empty = mempty
--      foldMap f (Leaf x) = f x
--      foldMap f (Node l k r) = foldMap f l `mappend` f k `mappend` foldMap f r
--   
-- -- This is suitable even for abstract types, as the monoid is assumed to -- satisfy the monoid laws. Alternatively, one could define -- foldr: -- --
--   instance Foldable Tree where
--      foldr f z Empty = z
--      foldr f z (Leaf x) = f x z
--      foldr f z (Node l k r) = foldr f (f k (foldr f z r)) l
--   
-- -- Foldable instances are expected to satisfy the following -- laws: -- --
--   foldr f z t = appEndo (foldMap (Endo . f) t ) z
--   
-- --
--   foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z
--   
-- --
--   fold = foldMap id
--   
-- --
--   length = getSum . foldMap (Sum . const  1)
--   
-- -- sum, product, maximum, and minimum -- should all be essentially equivalent to foldMap forms, such -- as -- --
--   sum = getSum . foldMap Sum
--   
-- -- but may be less defined. -- -- If the type is also a Functor instance, it should satisfy -- --
--   foldMap f = fold . fmap f
--   
-- -- which implies that -- --
--   foldMap f . fmap g = foldMap (f . g)
--   
class Foldable (t :: * -> *) -- | Combine the elements of a structure using a monoid. fold :: (Foldable t, Monoid m) => t m -> m -- | Map each element of the structure to a monoid, and combine the -- results. foldMap :: (Foldable t, Monoid m) => a -> m -> t a -> m -- | Right-associative fold of a structure. -- -- In the case of lists, foldr, when applied to a binary operator, -- a starting value (typically the right-identity of the operator), and a -- list, reduces the list using the binary operator, from right to left: -- --
--   foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)
--   
-- -- Note that, since the head of the resulting expression is produced by -- an application of the operator to the first element of the list, -- foldr can produce a terminating expression from an infinite -- list. -- -- For a general Foldable structure this should be semantically -- identical to, -- --
--   foldr f z = foldr f z . toList
--   
foldr :: Foldable t => a -> b -> b -> b -> t a -> b -- | Right-associative fold of a structure, but with strict application of -- the operator. foldr' :: Foldable t => a -> b -> b -> b -> t a -> b -- | Left-associative fold of a structure but with strict application of -- the operator. -- -- This ensures that each step of the fold is forced to weak head normal -- form before being applied, avoiding the collection of thunks that -- would otherwise occur. This is often what you want to strictly reduce -- a finite list to a single, monolithic result (e.g. length). -- -- For a general Foldable structure this should be semantically -- identical to, -- --
--   foldl f z = foldl' f z . toList
--   
foldl' :: Foldable t => b -> a -> b -> b -> t a -> b -- | List of elements of a structure, from left to right. toList :: Foldable t => t a -> [a] -- | Test whether the structure is empty. The default implementation is -- optimized for structures that are similar to cons-lists, because there -- is no general way to do better. null :: Foldable t => t a -> Bool -- | Returns the size/length of a finite structure as an Int. The -- default implementation is optimized for structures that are similar to -- cons-lists, because there is no general way to do better. length :: Foldable t => t a -> Int -- | Does the element occur in the structure? elem :: (Foldable t, Eq a) => a -> t a -> Bool -- | The sum function computes the sum of the numbers of a -- structure. sum :: (Foldable t, Num a) => t a -> a -- | The product function computes the product of the numbers of a -- structure. product :: (Foldable t, Num a) => t a -> a -- | Monadic fold over the elements of a structure, associating to the -- right, i.e. from right to left. foldrM :: (Foldable t, Monad m) => a -> b -> m b -> b -> t a -> m b -- | Monadic fold over the elements of a structure, associating to the -- left, i.e. from left to right. foldlM :: (Foldable t, Monad m) => b -> a -> m b -> b -> t a -> m b -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and ignore the results. For a version that doesn't -- ignore the results see traverse. traverse_ :: (Foldable t, Applicative f) => a -> f b -> t a -> f () -- | for_ is traverse_ with its arguments flipped. For a -- version that doesn't ignore the results see for. -- --
--   >>> for_ [1..4] print
--   1
--   2
--   3
--   4
--   
for_ :: (Foldable t, Applicative f) => t a -> a -> f b -> f () -- | Evaluate each action in the structure from left to right, and ignore -- the results. For a version that doesn't ignore the results see -- sequenceA. sequenceA_ :: (Foldable t, Applicative f) => t f a -> f () -- | The sum of a collection of actions, generalizing concat. -- -- asum [Just Hello, Nothing, Just World] Just Hello asum :: (Foldable t, Alternative f) => t f a -> f a -- | The sum of a collection of actions, generalizing concat. As of -- base 4.8.0.0, msum is just asum, specialized to -- MonadPlus. msum :: (Foldable t, MonadPlus m) => t m a -> m a -- | Map a function over all the elements of a container and concatenate -- the resulting lists. concatMap :: Foldable t => a -> [b] -> t a -> [b] -- | and returns the conjunction of a container of Bools. For the -- result to be True, the container must be finite; False, -- however, results from a False value finitely far from the left -- end. and :: Foldable t => t Bool -> Bool -- | or returns the disjunction of a container of Bools. For the -- result to be False, the container must be finite; True, -- however, results from a True value finitely far from the left -- end. or :: Foldable t => t Bool -> Bool -- | Determines whether all elements of the structure satisfy the -- predicate. all :: Foldable t => a -> Bool -> t a -> Bool -- | notElem is the negation of elem. notElem :: (Foldable t, Eq a) => a -> t a -> Bool infix 4 `notElem` -- | The find function takes a predicate and a structure and returns -- the leftmost element of the structure matching the predicate, or -- Nothing if there is no such element. find :: Foldable t => a -> Bool -> t a -> Maybe a -- | 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 -- | Like foldM, but discards the result. foldM_ :: (Foldable t, Monad m) => b -> a -> m b -> b -> t a -> m () -- | Fold a value using its Foldable instance using explicitly -- provided Monoid operations. This is like foldMap where -- the Monoid instance can be manually specified. -- --
--   foldMapBy mappend memptyfoldMap
--   
-- --
--   >>> foldMapBy (+) 0 length ["hello","world"]
--   10
--   
foldMapBy :: Foldable t => r -> r -> r -> r -> a -> r -> t a -> r -- | Fold a value using its Foldable instance using explicitly -- provided Monoid operations. This is like fold where -- the Monoid instance can be manually specified. -- --
--   foldBy mappend memptyfold
--   
-- --
--   >>> foldBy (++) [] ["hello","world"]
--   "helloworld"
--   
foldBy :: Foldable t => a -> a -> a -> a -> t a -> a -- | Application operator. This operator is redundant, since ordinary -- application (f x) means the same as (f $ x). -- However, $ has low, right-associative binding precedence, so it -- sometimes allows parentheses to be omitted; for example: -- --
--   f $ g $ h x  =  f (g (h x))
--   
-- -- It is also useful in higher-order situations, such as map -- ($ 0) xs, or zipWith ($) fs xs. ($) :: () => a -> b -> a -> b infixr 0 $ -- | Strict (call-by-value) application operator. It takes a function and -- an argument, evaluates the argument to weak head normal form (WHNF), -- then calls the function with that value. ($!) :: () => a -> b -> a -> b infixr 0 $! -- | & 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 & -- | 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 -- | fix f is the least fixed point of the function -- f, i.e. the least defined x such that f x = -- x. -- -- For example, we can write the factorial function using direct -- recursion as -- --
--   >>> let fac n = if n <= 1 then 1 else n * fac (n-1) in fac 5
--   120
--   
-- -- This uses the fact that Haskell’s let introduces recursive -- bindings. We can rewrite this definition using fix, -- --
--   >>> fix (\rec n -> if n <= 1 then 1 else n * rec (n-1)) 5
--   120
--   
-- -- Instead of making a recursive call, we introduce a dummy parameter -- rec; when used within fix, this parameter then refers -- to fix' argument, hence the recursion is reintroduced. fix :: () => a -> a -> a -- | flip f takes its (first) two arguments in the reverse -- order of f. -- --
--   >>> flip (++) "hello" "world"
--   "worldhello"
--   
flip :: () => a -> b -> c -> b -> a -> c -- | until p f yields the result of applying f -- until p holds. until :: () => a -> Bool -> a -> a -> 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 Functor class is used for types that can be mapped over. -- Instances of Functor should satisfy the following laws: -- --
--   fmap id  ==  id
--   fmap (f . g)  ==  fmap f . fmap g
--   
-- -- The instances of Functor for lists, Maybe and IO -- satisfy these laws. class Functor (f :: * -> *) 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 -- | An infix synonym for fmap. -- -- The name of this operator is an allusion to $. Note the -- similarities between their types: -- --
--    ($)  ::              (a -> b) ->   a ->   b
--   (<$>) :: Functor f => (a -> b) -> f a -> f b
--   
-- -- Whereas $ is function application, <$> is -- function application lifted over a Functor. -- --

Examples

-- -- Convert from a Maybe Int to a -- Maybe String using show: -- --
--   >>> show <$> Nothing
--   Nothing
--   
--   >>> show <$> Just 3
--   Just "3"
--   
-- -- Convert from an Either Int Int to -- an Either Int String using -- show: -- --
--   >>> show <$> Left 17
--   Left 17
--   
--   >>> show <$> Right 17
--   Right "17"
--   
-- -- Double each element of a list: -- --
--   >>> (*2) <$> [1,2,3]
--   [2,4,6]
--   
-- -- Apply even to the second element of a pair: -- --
--   >>> even <$> (2,2)
--   (2,True)
--   
(<$>) :: Functor f => a -> b -> f a -> f b infixl 4 <$> -- | Flipped version of <$. -- --

Examples

-- -- Replace the contents of a Maybe Int with a -- constant String: -- --
--   >>> Nothing $> "foo"
--   Nothing
--   
--   >>> Just 90210 $> "foo"
--   Just "foo"
--   
-- -- Replace the contents of an Either Int -- Int with a constant String, resulting in an -- Either Int String: -- --
--   >>> Left 8675309 $> "foo"
--   Left 8675309
--   
--   >>> Right 8675309 $> "foo"
--   Right "foo"
--   
-- -- Replace each element of a list with a constant String: -- --
--   >>> [1,2,3] $> "foo"
--   ["foo","foo","foo"]
--   
-- -- Replace the second element of a pair with a constant String: -- --
--   >>> (1,2) $> "foo"
--   (1,"foo")
--   
($>) :: Functor f => f a -> b -> f b infixl 4 $> -- | 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 <&> -- | 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 () -- | Representable types of kind *. This class is derivable in GHC -- with the DeriveGeneric flag on. -- -- A Generic instance must satisfy the following laws: -- --
--   from . toid
--   to . fromid
--   
class Generic a -- | The class of types that can be converted to a hash value. -- -- Minimal implementation: hashWithSalt. class Hashable a -- | A value of type IO a is a computation which, when -- performed, does some I/O before returning a value of type a. -- -- There is really only one way to "perform" an I/O action: bind it to -- Main.main in your program. When your program is run, the I/O -- will be performed. It isn't possible to perform I/O from an arbitrary -- function, unless that function is itself in the IO monad and -- called at some point, directly or indirectly, from Main.main. -- -- IO is a monad, so IO actions can be combined using -- either the do-notation or the >> and >>= -- operations from the Monad class. data IO a -- | 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 :: * -> *) -- | Lift a computation from the IO monad. liftIO :: MonadIO m => IO a -> m a -- | 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 ++ -- | cycle ties a finite list into a circular one, or equivalently, -- the infinite repetition of the original list. It is the identity on -- infinite lists. cycle :: () => [a] -> [a] -- | iterate f x returns an infinite list of repeated -- applications of f to x: -- --
--   iterate f x == [x, f x, f (f x), ...]
--   
-- -- Note that iterate is lazy, potentially leading to thunk -- build-up if the consumer doesn't force each iterate. See 'iterate\'' -- for a strict variant of this function. iterate :: () => a -> a -> a -> [a] -- | 'iterate\'' is the strict version of iterate. -- -- It ensures that the result of each application of force to weak head -- normal form before proceeding. iterate' :: () => a -> a -> a -> [a] -- | map f xs is the list obtained by applying f -- to each element of xs, i.e., -- --
--   map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn]
--   map f [x1, x2, ...] == [f x1, f x2, ...]
--   
map :: () => a -> b -> [a] -> [b] -- | repeat x is an infinite list, with x the -- value of every element. 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 :: () => Int -> a -> [a] -- | scanl is similar to foldl, but returns a list of -- successive reduced values from the left: -- --
--   scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
--   
-- -- Note that -- --
--   last (scanl f z xs) == foldl f z xs.
--   
scanl :: () => b -> a -> b -> b -> [a] -> [b] -- | A strictly accumulating version of scanl scanl' :: () => b -> a -> b -> b -> [a] -> [b] -- | scanl1 is a variant of scanl that has no starting value -- argument: -- --
--   scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
--   
scanl1 :: () => a -> a -> a -> [a] -> [a] -- | scanr is the right-to-left dual of scanl. Note that -- --
--   head (scanr f z xs) == foldr f z xs.
--   
scanr :: () => a -> b -> b -> b -> [a] -> [b] -- | scanr1 is a variant of scanr that has no starting value -- argument. scanr1 :: () => a -> a -> a -> [a] -> [a] -- | The unfoldr function is a `dual' to foldr: while -- foldr reduces a list to a summary value, unfoldr builds -- a list from a seed value. The function takes the element and returns -- Nothing if it is done producing the list or returns Just -- (a,b), in which case, a is a prepended to the list -- and b is used as the next element in a recursive call. For -- example, -- --
--   iterate f == unfoldr (\x -> Just (x, f x))
--   
-- -- In some cases, unfoldr can undo a foldr operation: -- --
--   unfoldr f' (foldr f z xs) == xs
--   
-- -- if the following holds: -- --
--   f' (f x y) = Just (x,y)
--   f' z       = Nothing
--   
-- -- A simple use of unfoldr: -- --
--   >>> unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10
--   [10,9,8,7,6,5,4,3,2,1]
--   
unfoldr :: () => b -> Maybe (a, b) -> b -> [a] -- | A Map from keys k to values a. data Map k a -- | A map from keys to values. A map cannot contain duplicate keys; each -- key can map to at most one value. data HashMap k v -- | A map of integers to values a. data IntMap a -- | 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 -- | 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 -- | Monadic generalisation of maybe. maybeM :: Monad m => m b -> a -> m b -> m Maybe a -> m b -- | The fromMaybe function takes a default value and and -- Maybe value. If the Maybe is Nothing, it returns -- the default values; otherwise, it returns the value contained in the -- Maybe. -- --

Examples

-- -- Basic usage: -- --
--   >>> fromMaybe "" (Just "Hello, World!")
--   "Hello, World!"
--   
-- --
--   >>> fromMaybe "" Nothing
--   ""
--   
-- -- Read an integer from a string using readMaybe. If we fail to -- parse an integer, we want to return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> fromMaybe 0 (readMaybe "5")
--   5
--   
--   >>> fromMaybe 0 (readMaybe "")
--   0
--   
fromMaybe :: () => a -> Maybe a -> a -- | The 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 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] -- | This Prism provides the Traversal of a Nothing in -- a Maybe. -- --
--   >>> Nothing ^? _Nothing
--   Just ()
--   
-- --
--   >>> Just () ^? _Nothing
--   Nothing
--   
-- -- But you can turn it around and use it to construct Nothing as -- well: -- --
--   >>> _Nothing # ()
--   Nothing
--   
_Nothing :: (Choice p, Applicative f) => p () f () -> p Maybe a f Maybe a -- | This Prism provides a Traversal for tweaking the target -- of the value of Just in a Maybe. -- --
--   >>> over _Just (+1) (Just 2)
--   Just 3
--   
-- -- Unlike traverse this is a Prism, and so you can use it -- to inject as well: -- --
--   >>> _Just # 5
--   Just 5
--   
-- --
--   >>> 5^.re _Just
--   Just 5
--   
-- -- Interestingly, -- --
--   m ^? _Just ≡ m
--   
-- --
--   >>> Just x ^? _Just
--   Just x
--   
-- --
--   >>> Nothing ^? _Just
--   Nothing
--   
_Just :: (Choice p, Applicative f) => p a f b -> p Maybe a f Maybe b -- | The Monad class defines the basic operations over a -- monad, a concept from a branch of mathematics known as -- category theory. From the perspective of a Haskell programmer, -- however, it is best to think of a monad as an abstract datatype -- of actions. Haskell's do expressions provide a convenient -- syntax for writing monadic expressions. -- -- Instances of Monad should satisfy the following laws: -- -- -- -- Furthermore, the Monad and Applicative operations should -- relate as follows: -- -- -- -- The above laws imply: -- -- -- -- and that pure and (<*>) satisfy the applicative -- functor laws. -- -- The instances of Monad for lists, Maybe and IO -- defined in the Prelude satisfy these laws. class Applicative m => Monad (m :: * -> *) -- | Sequentially compose two actions, passing any value produced by the -- first as an argument to the second. (>>=) :: Monad m => m a -> a -> m b -> m b -- | Same as >>=, but with the arguments interchanged. (=<<) :: Monad m => a -> m b -> m a -> m b infixr 1 =<< -- | Left-to-right Kleisli composition of monads. (>=>) :: Monad m => a -> m b -> b -> m c -> a -> m c infixr 1 >=> -- | Right-to-left Kleisli composition of monads. -- (>=>), 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 <=< -- | Like unless, but where the test can be monadic. unlessM :: Monad m => m Bool -> m () -> m () -- | Like whenJust, but where the test can be monadic. whenJustM :: Monad m => m Maybe a -> a -> m () -> m () -- | Like when, but where the test can be monadic. whenM :: Monad m => m Bool -> m () -> m () -- | Keep running an operation until it becomes False. As an -- example: -- --
--   whileM $ do sleep 0.1; notM $ doesFileExist "foo.txt"
--   readFile "foo.txt"
--   
-- -- If you need some state persisted between each test, use loopM. whileM :: Monad m => m Bool -> m () -- | The class of monad transformers. Instances should satisfy the -- following laws, which state that lift is a monad -- transformation: -- -- class MonadTrans (t :: * -> * -> * -> *) -- | Lift a computation from the argument monad to the constructed monad. lift :: (MonadTrans t, Monad m) => m a -> t m a -- | The class of monoids (types with an associative binary operation that -- has an identity). Instances should satisfy the following laws: -- -- -- -- The method names refer to the monoid of lists under concatenation, but -- there are many other instances. -- -- Some types can be viewed as a monoid in more than one way, e.g. both -- addition and multiplication on numbers. In such cases we often define -- newtypes and make those instances of Monoid, e.g. -- Sum and Product. -- -- NOTE: Semigroup is a superclass of Monoid since -- base-4.11.0.0. class Semigroup a => Monoid a -- | Fold a list using the monoid. -- -- For most types, the default definition for mconcat will be -- used, but the function is included in the class definition so that an -- optimized version can be provided for specific types. mconcat :: Monoid a => [a] -> a -- | Identity of mappend mempty :: Monoid a => a -- | Double-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- double-precision type. data Double -- | Single-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- single-precision type. data Float -- | Trigonometric and hyperbolic functions and related functions. class Fractional a => Floating a pi :: Floating a => a exp :: Floating a => a -> a log :: Floating a => a -> a sqrt :: Floating a => a -> a (**) :: Floating a => a -> a -> a logBase :: Floating a => a -> a -> a sin :: Floating a => a -> a cos :: Floating a => a -> a tan :: Floating a => a -> a asin :: Floating a => a -> a acos :: Floating a => a -> a atan :: Floating a => a -> a sinh :: Floating a => a -> a cosh :: Floating a => a -> a tanh :: Floating a => a -> a asinh :: Floating a => a -> a acosh :: Floating a => a -> a atanh :: Floating a => a -> a -- | log1p x computes log (1 + x), but -- provides more precise results for small (absolute) values of -- x if possible. log1p :: Floating a => a -> a -- | expm1 x computes exp x - 1, but -- provides more precise results for small (absolute) values of -- x if possible. expm1 :: Floating a => a -> a -- | log1pexp x computes log (1 + exp -- x), but provides more precise results if possible. -- -- Examples: -- -- log1pexp :: Floating a => a -> a -- | log1mexp x computes log (1 - exp -- x), but provides more precise results if possible. -- -- Examples: -- -- log1mexp :: Floating a => a -> a -- | Fractional numbers, supporting real division. 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 -- | A fixed-precision integer type with at least the range [-2^29 .. -- 2^29-1]. The exact range for a given implementation can be -- determined by using minBound and maxBound from the -- Bounded class. data Int -- | 8-bit signed integer type data Int8 -- | 16-bit signed integer type data Int16 -- | 32-bit signed integer type data Int32 -- | 64-bit signed integer type data Int64 -- | Invariant: Jn# and Jp# are used iff value doesn't fit in -- S# -- -- Useful properties resulting from the invariants: -- -- data Integer -- | Integral numbers, supporting integer division. 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 even :: Integral a => a -> Bool odd :: 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 -- | general coercion from integral types fromIntegral :: (Integral a, Num b) => a -> b -- | (Kind) This is the kind of type-level natural numbers. data Nat -- | 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) natVal :: KnownNat n => proxy n -> Integer natVal' :: KnownNat n => Proxy# n -> Integer -- | This type represents unknown type-level natural numbers. data SomeNat [SomeNat] :: SomeNat -- | Convert an integer into an unknown type-level natural. someNatVal :: Integer -> Maybe SomeNat -- | Basic numeric class. class Num a (+) :: Num a => a -> a -> a (-) :: Num a => a -> a -> a (*) :: Num a => a -> a -> a -- | Unary negation. negate :: Num a => a -> a -- | Absolute value. abs :: Num a => a -> a -- | Sign of a number. The functions abs and signum should -- satisfy the law: -- --
--   abs x * signum x == x
--   
-- -- For real numbers, the signum is either -1 (negative), -- 0 (zero) or 1 (positive). signum :: Num a => a -> a -- | Conversion from an Integer. An integer literal represents the -- application of the function fromInteger to the appropriate -- value of type Integer, so such literals have type -- (Num a) => a. fromInteger :: Num a => Integer -> a -- | 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 class (Num a, Ord a) => Real a -- | the rational equivalent of its real argument with full precision toRational :: Real a => a -> Rational -- | generalisation of div to any instance of Real div' :: (Real a, Integral b) => a -> a -> b -- | generalisation of mod to any instance of Real mod' :: Real a => a -> a -> a -- | generalisation of divMod to any instance of Real divMod' :: (Real a, Integral b) => a -> a -> (b, a) -- | general coercion to fractional types realToFrac :: (Real a, Fractional b) => a -> b -- | Efficient, machine-independent access to the components of a -- floating-point number. class (RealFrac a, Floating a) => RealFloat a -- | a constant function, returning the radix of the representation (often -- 2) floatRadix :: RealFloat a => a -> Integer -- | a constant function, returning the number of digits of -- floatRadix in the significand floatDigits :: RealFloat a => a -> Int -- | a constant function, returning the lowest and highest values the -- exponent may assume floatRange :: RealFloat a => a -> (Int, Int) -- | The function decodeFloat applied to a real floating-point -- number returns the significand expressed as an Integer and an -- appropriately scaled exponent (an Int). If -- decodeFloat x yields (m,n), then x -- is equal in value to m*b^^n, where b is the -- floating-point radix, and furthermore, either m and -- n are both zero or else b^(d-1) <= abs m < -- b^d, where d is the value of floatDigits -- x. In particular, decodeFloat 0 = (0,0). If the -- type contains a negative zero, also decodeFloat (-0.0) = -- (0,0). The result of decodeFloat x is -- unspecified if either of isNaN x or -- isInfinite x is True. decodeFloat :: RealFloat a => a -> (Integer, Int) -- | encodeFloat performs the inverse of decodeFloat in the -- sense that for finite x with the exception of -0.0, -- uncurry encodeFloat (decodeFloat x) = -- x. encodeFloat m n is one of the two closest -- representable floating-point numbers to m*b^^n (or -- ±Infinity if overflow occurs); usually the closer, but if -- m contains too many bits, the result may be rounded in the -- wrong direction. encodeFloat :: RealFloat a => Integer -> Int -> a -- | exponent corresponds to the second component of -- decodeFloat. exponent 0 = 0 and for finite -- nonzero x, exponent x = snd (decodeFloat x) -- + floatDigits x. If x is a finite floating-point -- number, it is equal in value to significand x * b ^^ -- exponent x, where b is the floating-point radix. -- The behaviour is unspecified on infinite or NaN values. exponent :: RealFloat a => a -> Int -- | The first component of decodeFloat, scaled to lie in the open -- interval (-1,1), either 0.0 or of absolute -- value >= 1/b, where b is the floating-point -- radix. The behaviour is unspecified on infinite or NaN -- values. significand :: RealFloat a => a -> a -- | multiplies a floating-point number by an integer power of the radix scaleFloat :: RealFloat a => Int -> a -> a -- | True if the argument is an IEEE "not-a-number" (NaN) value isNaN :: RealFloat a => a -> Bool -- | True if the argument is an IEEE infinity or negative infinity isInfinite :: RealFloat a => a -> Bool -- | True if the argument is too small to be represented in -- normalized format isDenormalized :: RealFloat a => a -> Bool -- | True if the argument is an IEEE negative zero isNegativeZero :: RealFloat a => a -> Bool -- | True if the argument is an IEEE floating point number isIEEE :: RealFloat a => a -> Bool -- | a version of arctangent taking two real floating-point arguments. For -- real floating x and y, atan2 y x -- computes the angle (from the positive x-axis) of the vector from the -- origin to the point (x,y). atan2 y x returns -- a value in the range [-pi, pi]. It follows the -- Common Lisp semantics for the origin when signed zeroes are supported. -- atan2 y 1, with y in a type that is -- RealFloat, should return the same value as atan -- y. A default definition of atan2 is provided, but -- implementors can provide a more accurate implementation. atan2 :: RealFloat a => a -> a -> a -- | Extracting components of fractions. class (Real a, Fractional a) => RealFrac a -- | The function properFraction takes a real fractional number -- x and returns a pair (n,f) such that x = -- n+f, and: -- -- -- -- The default definitions of the ceiling, floor, -- truncate and round functions are in terms of -- properFraction. properFraction :: (RealFrac a, Integral b) => a -> (b, a) -- | truncate x returns the integer nearest x -- between zero and x truncate :: (RealFrac a, Integral b) => a -> b -- | round x returns the nearest integer to x; the -- even integer if x is equidistant between two integers round :: (RealFrac a, Integral b) => a -> b -- | ceiling x returns the least integer not less than -- x ceiling :: (RealFrac a, Integral b) => a -> b -- | floor x returns the greatest integer not greater than -- x floor :: (RealFrac a, Integral b) => a -> b -- | 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 -- | 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. -- --
--   >>> Left 4 ^?_Left
--   Just 4
--   
-- --
--   >>> Right 4 ^?_Left
--   Nothing
--   
-- --
--   >>> "world" ^? ix 3
--   Just 'l'
--   
-- --
--   >>> "world" ^? ix 20
--   Nothing
--   
-- --
--   (^?) ≡ flip preview
--   
-- --
--   (^?) :: 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 ^? -- | Retrieve the first value targeted by a Fold or Traversal -- (or Just the result from a Getter or Lens). See -- also (^?). -- --
--   listToMaybe . toListpreview folded
--   
-- -- This is usually applied in the Reader Monad (->) -- s. -- --
--   preview = view . pre
--   
-- --
--   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
--   
-- -- However, it may be useful to think of its full generality when working -- with a Monad transformer stack: -- --
--   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 -- | Check to see if this Fold or Traversal matches 1 or more -- entries. -- --
--   >>> has (element 0) []
--   False
--   
-- --
--   >>> has _Left (Left 12)
--   True
--   
-- --
--   >>> has _Right (Left 12)
--   False
--   
-- -- This will always return True for a Lens or -- Getter. -- --
--   >>> has _1 ("hello","world")
--   True
--   
-- --
--   has :: Getter s a     -> s -> Bool
--   has :: Fold s a       -> s -> Bool
--   has :: Iso' s a       -> s -> Bool
--   has :: Lens' s a      -> s -> Bool
--   has :: Traversal' s a -> s -> Bool
--   
has :: () => Getting Any s a -> s -> Bool -- | Obtain a Fold from any Foldable indexed by ordinal -- position. -- --
--   >>> Just 3^..folded
--   [3]
--   
-- --
--   >>> Nothing^..folded
--   []
--   
-- --
--   >>> [(1,2),(3,4)]^..folded.both
--   [1,2,3,4]
--   
folded :: Foldable f => IndexedFold Int f a 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 -- | 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 :: * -> *). Functor f => a -> f b -> s -> f t -- |
--   type Lens' = Simple Lens
--   
type Lens' s a = Lens s s a a -- | Build a Lens from a getter and a setter. -- --
--   lens :: Functor f => (s -> a) -> (s -> b -> t) -> (a -> f b) -> s -> f t
--   
-- --
--   >>> s ^. lens getter setter
--   getter s
--   
-- --
--   >>> s & lens getter setter .~ b
--   setter s b
--   
-- --
--   >>> s & lens getter setter %~ f
--   setter s (f (getter s))
--   
-- --
--   lens :: (s -> a) -> (s -> a -> s) -> Lens' s a
--   
lens :: () => s -> a -> s -> b -> t -> Lens s t a b -- | At provides a Lens that can be used to read, write or -- delete the value associated with a key in a Map-like container -- on an ad hoc basis. -- -- An instance of At should satisfy: -- --
--   ix k ≡ at k . traverse
--   
class Ixed m => At m -- |
--   >>> Map.fromList [(1,"world")] ^.at 1
--   Just "world"
--   
-- --
--   >>> at 1 ?~ "hello" $ Map.empty
--   fromList [(1,"hello")]
--   
-- -- Note: Map-like containers form a reasonable instance, -- but not Array-like ones, where you cannot satisfy the -- Lens laws. at :: At m => Index m -> Lens' m Maybe IxValue m -- | A Prism l is a Traversal that can also be -- turned around with re to obtain a Getter in the opposite -- direction. -- -- There are two laws that a Prism should satisfy: -- -- First, if I re or review a value with a Prism and -- then preview or use (^?), I will get it back: -- --
--   preview l (review l b) ≡ Just b
--   
-- -- Second, if you can extract a value a using a Prism -- l from a value s, then the value s is -- completely described by l and a: -- -- If preview l s ≡ Just a then -- review l a ≡ s -- -- These two laws imply that the Traversal laws hold for every -- Prism and that we traverse at most 1 element: -- --
--   lengthOf l x <= 1
--   
-- -- It may help to think of this as a Iso that can be partial in -- one direction. -- -- Every Prism is a valid Traversal. -- -- Every Iso is a valid Prism. -- -- For example, you might have a Prism' Integer -- Natural allows you to always go from a Natural to -- an Integer, and provide you with tools to check if an -- Integer is a Natural and/or to edit one if it is. -- --
--   nat :: Prism' Integer Natural
--   nat = prism toInteger $ \ i ->
--      if i < 0
--      then Left i
--      else Right (fromInteger i)
--   
-- -- Now we can ask if an Integer is a Natural. -- --
--   >>> 5^?nat
--   Just 5
--   
-- --
--   >>> (-5)^?nat
--   Nothing
--   
-- -- We can update the ones that are: -- --
--   >>> (-3,4) & both.nat *~ 2
--   (-3,8)
--   
-- -- And we can then convert from a Natural to an Integer. -- --
--   >>> 5 ^. re nat -- :: Natural
--   5
--   
-- -- Similarly we can use a Prism to traverse the -- Left half of an Either: -- --
--   >>> Left "hello" & _Left %~ length
--   Left 5
--   
-- -- or to construct an Either: -- --
--   >>> 5^.re _Left
--   Left 5
--   
-- -- such that if you query it with the Prism, you will get your -- original input back. -- --
--   >>> 5^.re _Left ^? _Left
--   Just 5
--   
-- -- Another interesting way to think of a Prism is as the -- categorical dual of a Lens -- a co-Lens, so to speak. -- This is what permits the construction of outside. -- -- Note: Composition with a Prism is index-preserving. type Prism s t a b = forall (p :: * -> * -> *) (f :: * -> *). (Choice p, Applicative f) => p a f b -> p s f t -- | Build a Prism. -- -- Either t a is used instead of Maybe a -- to permit the types of s and t to differ. prism :: () => b -> t -> s -> Either t a -> Prism s t a b -- | Check to see if this Prism matches. -- --
--   >>> is _Left (Right 12)
--   False
--   
-- --
--   >>> is hex "3f79"
--   True
--   
is :: () => APrism s t a b -> s -> Bool -- | 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 %~ -- | 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 -- | 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 -- | 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 :: * -> *). Applicative f => a -> f b -> s -> f t -- | Provides a simple Traversal lets you traverse the value -- at a given key in a Map or element at an ordinal position in a -- list or Seq. class Ixed m -- | NB: Setting the value of this Traversal will only set -- the value in at if it is already present. -- -- If you want to be able to insert missing values, you want -- at. -- --
--   >>> Seq.fromList [a,b,c,d] & ix 2 %~ f
--   fromList [a,b,f c,d]
--   
-- --
--   >>> Seq.fromList [a,b,c,d] & ix 2 .~ e
--   fromList [a,b,e,d]
--   
-- --
--   >>> Seq.fromList [a,b,c,d] ^? ix 2
--   Just c
--   
-- --
--   >>> Seq.fromList [] ^? ix 2
--   Nothing
--   
ix :: Ixed m => Index m -> Traversal' m IxValue m -- | This provides a common notion of a value at an index that is shared by -- both Ixed and At. -- | 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. -- -- 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 data Ordering LT :: Ordering EQ :: Ordering GT :: Ordering -- | The class of semigroups (types with an associative binary operation). -- -- Instances should satisfy the associativity law: -- -- class Semigroup a -- | An associative operation. (<>) :: Semigroup a => a -> a -> a -- | General-purpose finite sequences. data Seq a -- | A set of values a. data Set a -- | A set of values. A set cannot contain duplicate values. data HashSet a -- | A set of integers. data IntSet -- | 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 -- | A specialised variant of showsPrec, using precedence context -- zero, and returning an ordinary String. show :: Show a => a -> String -- | A space efficient, packed, unboxed Unicode text type. data Text -- | Functors representing data structures that can be traversed from left -- to right. -- -- A definition of traverse must satisfy the following laws: -- -- -- -- A definition of sequenceA must satisfy the following laws: -- -- -- -- where an applicative transformation is a function -- --
--   t :: (Applicative f, Applicative g) => f a -> g a
--   
-- -- preserving the Applicative operations, i.e. -- -- -- -- and the identity functor Identity and composition of functors -- Compose are defined as -- --
--   newtype Identity a = Identity a
--   
--   instance Functor Identity where
--     fmap f (Identity x) = Identity (f x)
--   
--   instance Applicative Identity where
--     pure x = Identity x
--     Identity f <*> Identity x = Identity (f x)
--   
--   newtype Compose f g a = Compose (f (g a))
--   
--   instance (Functor f, Functor g) => Functor (Compose f g) where
--     fmap f (Compose x) = Compose (fmap (fmap f) x)
--   
--   instance (Applicative f, Applicative g) => Applicative (Compose f g) where
--     pure x = Compose (pure (pure x))
--     Compose f <*> Compose x = Compose ((<*>) <$> f <*> x)
--   
-- -- (The naturality law is implied by parametricity.) -- -- Instances are similar to Functor, e.g. given a data type -- --
--   data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
--   
-- -- a suitable instance would be -- --
--   instance Traversable Tree where
--      traverse f Empty = pure Empty
--      traverse f (Leaf x) = Leaf <$> f x
--      traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r
--   
-- -- This is suitable even for abstract types, as the laws for -- <*> imply a form of associativity. -- -- The superclass instances should satisfy the following: -- -- class (Functor t, Foldable t) => Traversable (t :: * -> *) -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and collect the results. For a version that -- ignores the results see traverse_. traverse :: (Traversable t, Applicative f) => a -> f b -> t a -> f t b -- | Evaluate each action in the structure from left to right, and and -- collect the results. For a version that ignores the results see -- sequenceA_. sequenceA :: (Traversable t, Applicative f) => t f a -> f t 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 -- | Extract the first component of a pair. fst :: () => (a, b) -> a -- | Extract the second component of a pair. snd :: () => (a, b) -> b -- | Provides access to 1st field of a tuple. class Field1 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | 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 -- | Provides access to the 2nd field of a tuple. class Field2 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | 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 -- | Provides access to the 3rd field of a tuple. class Field3 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 3rd field of a tuple. _3 :: Field3 s t a b => Lens s t a b -- | Provide access to the 4th field of a tuple. class Field4 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 4th field of a tuple. _4 :: Field4 s t a b => Lens s t a b -- | Provides access to the 5th field of a tuple. class Field5 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 5th field of a tuple. _5 :: Field5 s t a b => Lens s t a b -- | Provides access to the 6th element of a tuple. class Field6 s t a b | s -> a, t -> b, s b -> t, t a -> s -- | Access the 6th field of a tuple. _6 :: Field6 s t a b => Lens s t a b -- | Uninhabited data type data Void module Weigh module Writer -- | A writer monad parameterized by the type w of output to -- accumulate. -- -- The return function produces the output mempty, while -- >>= combines the outputs of the subcomputations using -- mappend. type Writer w = WriterT w Identity -- | Unwrap a writer computation as a (result, output) pair. (The inverse -- of writer.) runWriter :: Monoid w => Writer w a -> (a, w) -- | Extract the output from a writer computation. -- -- execWriter :: Monoid w => Writer w a -> w -- | Map both the return value and output of a computation using the given -- function. -- -- mapWriter :: (Monoid w, Monoid w') => (a, w) -> (b, w') -> Writer w a -> Writer w' b -- | A writer monad parameterized by: -- -- -- -- The return function produces the output mempty, while -- >>= combines the outputs of the subcomputations using -- mappend. data WriterT w (m :: * -> *) a -- | The WriterT constructor is deliberately not exported in the CPS module -- to avoid exposing the hidden state w. writerT provides a safe way to -- construct a WriterT with the same api as the original WriterT. writerT :: (Functor m, Monoid w) => m (a, w) -> WriterT w m a -- | Unwrap a writer computation. runWriterT :: Monoid w => WriterT w m a -> m (a, w) -- | Extract the output from a writer computation. -- -- execWriterT :: (Monad m, Monoid w) => WriterT w m a -> m w -- | Map both the return value and output of a computation using the given -- function. -- -- mapWriterT :: (Monad n, Monoid w, Monoid w') => m (a, w) -> n (b, w') -> WriterT w m a -> WriterT w' n b class (Monoid w, Monad m) => MonadWriter w (m :: * -> *) | m -> w -- | writer (a,w) embeds a simple writer action. writer :: MonadWriter w m => (a, w) -> m a -- | tell w is an action that produces the output -- w. tell :: MonadWriter w m => w -> m () -- | listen m is an action that executes the action -- m and adds its output to the value of the computation. listen :: MonadWriter w m => m a -> m (a, w) -- | pass m is an action that executes the action -- m, which returns a value and a function, and returns the -- value, applying the function to the output. pass :: MonadWriter w m => m (a, w -> w) -> m a -- | listens f m is an action that executes the action -- m and adds the result of applying f to the output to -- the value of the computation. -- -- listens :: MonadWriter w m => w -> b -> m a -> m (a, b) -- | censor f m is an action that executes the action -- m and applies the function f to its output, leaving -- the return value unchanged. -- -- censor :: MonadWriter w m => w -> w -> m a -> m a