-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | bioinformatics support library -- -- This is a collection of modules I separated from various -- bioinformatics tools. @package biohazard @version 2.0 module Bio.Util.MMap unsafeMMapFile :: FilePath -> IO ByteString module Bio.Util.Nub nubHash :: (Hashable a, Eq a) => [a] -> [a] nubHashBy :: (Hashable b, Eq b) => (a -> b) -> [a] -> [a] -- | Random useful stuff I didn't know where to put. module Bio.Util.Numeric -- | Calculates the Wilson Score interval. If (l,m,h) = wilson c x -- n, then m is the binary proportion and (l,h) -- it's c-confidence interval for x positive examples -- out of n observations. c is typically something like -- 0.05. wilson :: Double -> Int -> Int -> (Double, Double, Double) invnormcdf :: (Ord a, Floating a) => a -> a -- | Binomial coefficient: <math> choose :: Integral a => a -> a -> a -- | Try to estimate complexity of a whole from a sample. Suppose we -- sampled total things and among those singles occured -- only once. How many different things are there? -- -- Let the total number be m. The copy number follows a Poisson -- distribution with paramter lambda. Let <math>, then we -- have: -- -- <math> <math> <math> -- -- To get z, we solve using Newton iteration and then substitute -- to get m: -- -- <math> -- -- It converges as long as the initial z is large enough, and -- 10D (in the line for zz below) appears to work well. estimateComplexity :: (Integral a, Floating b, Ord b) => a -> a -> Maybe b showNum :: Show a => a -> String showOOM :: Double -> String -- | Computes log (1+x) to a relative precision of 10^-8 -- even for very small x. Stolen from -- http://www.johndcook.com/cpp_log_one_plus_x.html log1p :: (Floating a, Ord a) => a -> a -- | Computes <math> to a relative precision of 10^-10 even -- for very small x. Stolen from -- http://www.johndcook.com/cpp_expm1.html expm1 :: (Floating a, Ord a) => a -> a -- | Computes <math> without leaving the log domain and hence without -- losing precision. (<#>) :: (Floating a, Ord a) => a -> a -> a infixl 5 <#> -- | Computes <math>, following Martin Mächler. log1mexp :: (Floating a, Ord a) => a -> a -- | Computes <math>, following Martin Mächler. log1pexp :: (Floating a, Ord a) => a -> a -- | Computes <math> sensibly. The list must be sorted in -- descending(!) order. lsum :: (Floating a, Ord a) => [a] -> a -- | Computes <math>. llerp :: (Floating a, Ord a) => a -> a -> a -> a -- | Common data types used everywhere. This module is a collection of very -- basic "bioinformatics" data types that are simple, but don't make -- sense to define over and over. module Bio.Base -- | A nucleotide base. We only represent A,C,G,T. The contained -- Word8 ist guaranteed to be 0..3. newtype Nucleotide N :: Word8 -> Nucleotide [unN] :: Nucleotide -> Word8 -- | A nucleotide base in an alignment. Experience says we're dealing with -- Ns and gaps all the type, so purity be damned, they are included as if -- they were real bases. -- -- To allow Nucleotidess to be unpacked and incorporated into -- containers, we choose to represent them the same way as the BAM file -- format: as a 4 bit wide field. Gaps are encoded as 0 where they make -- sense, N is 15. The contained Word8 is guaranteed to be 0..15. newtype Nucleotides Ns :: Word8 -> Nucleotides [unNs] :: Nucleotides -> Word8 -- | Qualities are stored in deciban, also known as the Phred scale. To -- represent a value p, we store -10 * log_10 p. -- Operations work directly on the "Phred" value, as the name suggests. -- The same goes for the Ord instance: greater quality means -- higher "Phred" score, meand lower error probability. newtype Qual Q :: Word8 -> Qual [unQ] :: Qual -> Word8 toQual :: (Floating a, RealFrac a) => a -> Qual fromQual :: Qual -> Double fromQualRaised :: Double -> Qual -> Double probToQual :: (Floating a, RealFrac a) => Prob' a -> Qual -- | A positive floating point value stored in log domain. We store the -- natural logarithm (makes computation easier), but allow conversions to -- the familiar "Phred" scale used for Qual values. newtype Prob' a Pr :: a -> Prob' a [unPr] :: Prob' a -> a -- | Common way of using Prob'. type Prob = Prob' Double toProb :: Floating a => a -> Prob' a fromProb :: Floating a => Prob' a -> a qualToProb :: Floating a => Qual -> Prob' a pow :: Num a => Prob' a -> a -> Prob' a infixr 8 `pow` -- | A strict pair. data Pair a b (:!:) :: !a -> !b -> Pair a b infixl 2 :!: -- | 8-bit unsigned integer type data Word8 nucA :: Nucleotide nucC :: Nucleotide nucG :: Nucleotide nucT :: Nucleotide nucsA :: Nucleotides nucsC :: Nucleotides nucsG :: Nucleotides nucsT :: Nucleotides nucsN :: Nucleotides gap :: Nucleotides -- | Converts a character into a Nucleotides. The usual codes for -- A,C,G,T and U are understood, - and . become gaps and -- everything else is an N. toNucleotide :: Char -> Nucleotide -- | Converts a character into a Nucleotides. The usual codes for -- A,C,G,T and U are understood, - and . become gaps and -- everything else is an N. toNucleotides :: Char -> Nucleotides nucToNucs :: Nucleotide -> Nucleotides showNucleotide :: Nucleotide -> Char showNucleotides :: Nucleotides -> Char -- | Tests if a Nucleotides is a gap. Returns true only for the gap. isGap :: Nucleotides -> Bool -- | Tests if a Nucleotides is a base. Returns True for -- everything but gaps. isBase :: Nucleotides -> Bool -- | Tests if a Nucleotides is a proper base. Returns True -- for A,C,G,T only. isProperBase :: Nucleotides -> Bool properBases :: [Nucleotides] -- | Complements a Nucleotides. compl :: Nucleotide -> Nucleotide -- | Complements a Nucleotides. compls :: Nucleotides -> Nucleotides -- | Coordinates in a genome. The position is zero-based, no questions -- about it. Think of the position as pointing to the crack between two -- bases: looking forward you see the next base to the right, looking in -- the reverse direction you see the complement of the first base to the -- left. -- -- To encode the strand, we (virtually) reverse-complement any sequence -- and prepend it to the normal one. That way, reversed coordinates have -- a negative sign and automatically make sense. Position 0 could either -- be the beginning of the sequence or the end on the reverse strand... -- that ambiguity shouldn't really matter. data Position Pos :: {-# UNPACK #-} !ByteString -> {-# UNPACK #-} !Int -> Position -- | sequence (e.g. some chromosome) [p_seq] :: Position -> {-# UNPACK #-} !ByteString -- | offset, zero-based [p_start] :: Position -> {-# UNPACK #-} !Int -- | Moves a Position. The position is moved forward according to -- the strand, negative indexes move backward accordingly. shiftPosition :: Int -> Position -> Position p_is_reverse :: Position -> Bool -- | Ranges in genomes We combine a position with a length. In 'Range pos -- len', pos is always the start of a stretch of length -- len. Positions therefore move in the opposite direction on -- the reverse strand. To get the same stretch on the reverse strand, -- shift r_pos by r_length, then reverse direction (or call -- reverseRange). data Range Range :: {-# UNPACK #-} !Position -> {-# UNPACK #-} !Int -> Range [r_pos] :: Range -> {-# UNPACK #-} !Position [r_length] :: Range -> {-# UNPACK #-} !Int -- | Moves a Range. This is just shiftPosition lifted. shiftRange :: Int -> Range -> Range -- | Reverses a Range to give the same Range on the -- opposite strand. reverseRange :: Range -> Range -- | Extends a range. The length of the range is simply increased. extendRange :: Int -> Range -> Range -- | Expands a subrange. (range1 insideRange range2) -- interprets range1 as a subrange of range2 and -- computes its absolute coordinates. The sequence name of -- range1 is ignored. insideRange :: Range -> Range -> Range -- | Wraps a range to a region. This simply normalizes the start position -- to be in the interval '[0,n)', which only makes sense if the -- Range is to be mapped onto a circular genome. This works on -- both strands and the strand information is retained. wrapRange :: Int -> Range -> Range instance (GHC.Arr.Ix a, GHC.Arr.Ix b) => GHC.Arr.Ix (Bio.Base.Pair a b) instance (GHC.Enum.Bounded a, GHC.Enum.Bounded b) => GHC.Enum.Bounded (Bio.Base.Pair a b) instance (GHC.Read.Read a, GHC.Read.Read b) => GHC.Read.Read (Bio.Base.Pair a b) instance (GHC.Show.Show a, GHC.Show.Show b) => GHC.Show.Show (Bio.Base.Pair a b) instance (GHC.Classes.Ord a, GHC.Classes.Ord b) => GHC.Classes.Ord (Bio.Base.Pair a b) instance (GHC.Classes.Eq a, GHC.Classes.Eq b) => GHC.Classes.Eq (Bio.Base.Pair a b) instance GHC.Classes.Ord Bio.Base.Range instance GHC.Classes.Eq Bio.Base.Range instance GHC.Show.Show Bio.Base.Range instance GHC.Classes.Ord Bio.Base.Position instance GHC.Classes.Eq Bio.Base.Position instance GHC.Show.Show Bio.Base.Position instance Foreign.Storable.Storable a => Foreign.Storable.Storable (Bio.Base.Prob' a) instance GHC.Classes.Ord a => GHC.Classes.Ord (Bio.Base.Prob' a) instance GHC.Classes.Eq a => GHC.Classes.Eq (Bio.Base.Prob' a) instance GHC.Enum.Bounded Bio.Base.Qual instance Foreign.Storable.Storable Bio.Base.Qual instance GHC.Classes.Ord Bio.Base.Qual instance GHC.Classes.Eq Bio.Base.Qual instance Foreign.Storable.Storable Bio.Base.Nucleotides instance GHC.Arr.Ix Bio.Base.Nucleotides instance GHC.Enum.Enum Bio.Base.Nucleotides instance GHC.Classes.Ord Bio.Base.Nucleotides instance GHC.Classes.Eq Bio.Base.Nucleotides instance Foreign.Storable.Storable Bio.Base.Nucleotide instance GHC.Arr.Ix Bio.Base.Nucleotide instance GHC.Enum.Enum Bio.Base.Nucleotide instance GHC.Classes.Ord Bio.Base.Nucleotide instance GHC.Classes.Eq Bio.Base.Nucleotide instance GHC.Float.RealFloat a => GHC.Show.Show (Bio.Base.Prob' a) instance (GHC.Float.Floating a, GHC.Classes.Ord a) => GHC.Num.Num (Bio.Base.Prob' a) instance (GHC.Float.Floating a, GHC.Real.Fractional a, GHC.Classes.Ord a) => GHC.Real.Fractional (Bio.Base.Prob' a) instance GHC.Show.Show Bio.Base.Qual instance GHC.Enum.Bounded Bio.Base.Nucleotides instance GHC.Show.Show Bio.Base.Nucleotides instance GHC.Read.Read Bio.Base.Nucleotides instance GHC.Enum.Bounded Bio.Base.Nucleotide instance GHC.Show.Show Bio.Base.Nucleotide instance GHC.Read.Read Bio.Base.Nucleotide -- | Utilities to read multibyte quantities from arbitrary positions. module Bio.Util.Storable peekWord8 :: Ptr a -> IO Word8 peekUnalnWord16LE :: Ptr a -> IO Word16 peekUnalnWord16BE :: Ptr a -> IO Word16 peekUnalnWord32LE :: Ptr a -> IO Word32 peekUnalnWord32BE :: Ptr a -> IO Word32 pokeUnalnWord32LE :: Ptr a -> Word32 -> IO () module Bio.Util.Text -- | Class of things that can be unpacked into Strings. Kind of the -- opposite of IsString. class Unpack s unpack :: Unpack s => s -> String -- | Conversion between Word8 and Char. Should compile to a -- no-op. w2c :: Word8 -> Char -- | Unsafe conversion between Char and Word8. This is a -- no-op and silently truncates to 8 bits Chars > '\255'. It is -- provided as convenience for ByteString construction. c2w :: Char -> Word8 -- | Converts Bytes into Text. This uses UTF8, but if -- there is an error, it pretends it was Latin1. Evil as this is, it -- tends to Just Work on files where nobody ever wasted a thought on -- encodings. decodeBytes :: ByteString -> Text -- | Converts Text into Bytes. This uses UTF8. encodeBytes :: Text -> ByteString -- | Decompresses Gzip or Bgzf and passes everything else on. In reality, -- it simply decompresses Gzip, and when done, looks for another Gzip -- stream. Since there is a small chance to attempt decompression of an -- uncompressed stream, the original data is returned in case of an -- error. decompressGzip :: ByteString -> ByteString instance Bio.Util.Text.Unpack Data.ByteString.Internal.ByteString instance Bio.Util.Text.Unpack Data.Text.Internal.Text instance Bio.Util.Text.Unpack GHC.Base.String module Bio.Prelude -- | Append two lists, i.e., -- --
-- [x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn] -- [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...] ---- -- If the first list is not finite, the result is the first list. (++) :: () => [a] -> [a] -> [a] infixr 5 ++ -- | The value of seq a b is bottom if a is bottom, and -- otherwise equal to b. In other words, it evaluates the first -- argument a to weak head normal form (WHNF). seq is -- usually introduced to improve performance by avoiding unneeded -- laziness. -- -- A note on evaluation order: the expression seq a b does -- not guarantee that a will be evaluated before -- b. The only guarantee given by seq is that the both -- a and b will be evaluated before seq -- returns a value. In particular, this means that b may be -- evaluated before a. If you need to guarantee a specific order -- of evaluation, you must use the function pseq from the -- "parallel" package. seq :: () => a -> b -> b -- | filter, applied to a predicate and a list, returns the list of -- those elements that satisfy the predicate; i.e., -- --
-- filter p xs = [ x | x <- xs, p x] --filter :: () => (a -> Bool) -> [a] -> [a] -- | zip takes two lists and returns a list of corresponding pairs. -- --
-- zip [1, 2] ['a', 'b'] = [(1, 'a'), (2, 'b')] ---- -- If one input list is short, excess elements of the longer list are -- discarded: -- --
-- zip [1] ['a', 'b'] = [(1, 'a')] -- zip [1, 2] ['a'] = [(1, 'a')] ---- -- zip is right-lazy: -- --
-- zip [] _|_ = [] -- zip _|_ [] = _|_ --zip :: () => [a] -> [b] -> [(a, b)] -- | Create a stable pointer referring to the given Haskell value. newStablePtr :: () => a -> IO (StablePtr a) -- | The print function outputs a value of any printable type to the -- standard output device. Printable types are those that are instances -- of class Show; print converts values to strings for -- output using the show operation and adds a newline. -- -- For example, a program to print the first 20 integers and their powers -- of 2 could be written as: -- --
-- main = print ([(n, 2^n) | n <- [0..19]]) --print :: Show a => a -> IO () -- | Extract the first component of a pair. fst :: () => (a, b) -> a -- | Extract the second component of a pair. snd :: () => (a, b) -> b -- | otherwise is defined as the value True. It helps to make -- guards more readable. eg. -- --
-- f x | x < 0 = ... -- | otherwise = ... --otherwise :: Bool -- | If the first argument evaluates to True, then the result is the -- second argument. Otherwise an AssertionFailed exception is -- raised, containing a String with the source file and line -- number of the call to assert. -- -- Assertions can normally be turned on or off with a compiler flag (for -- GHC, assertions are normally on unless optimisation is turned on with -- -O or the -fignore-asserts option is given). When -- assertions are turned off, the first argument to assert is -- ignored, and the second argument is returned as the result. assert :: () => Bool -> a -> a -- | The lazy function restrains strictness analysis a little. The -- call lazy e means the same as e, but lazy has -- a magical property so far as strictness analysis is concerned: it is -- lazy in its first argument, even though its semantics is strict. After -- strictness analysis has run, calls to lazy are inlined to be -- the identity function. -- -- This behaviour is occasionally useful when controlling evaluation -- order. Notably, lazy is used in the library definition of -- par: -- --
-- par :: a -> b -> b -- par x y = case (par# x) of _ -> lazy y ---- -- If lazy were not lazy, par would look strict in -- y which would defeat the whole purpose of par. -- -- Like seq, the argument of lazy can have an unboxed type. lazy :: () => a -> a assertError :: ?callStack :: CallStack => Bool -> a -> a -- | The trace function outputs the trace message given as its first -- argument, before returning the second argument as its result. -- -- For example, this returns the value of f x but first outputs -- the message. -- --
-- >>> let x = 123; f = show
--
-- >>> trace ("calling f with x = " ++ show x) (f x)
-- "calling f with x = 123
-- 123"
--
--
-- The trace function should only be used for debugging, or
-- for monitoring execution. The function is not referentially
-- transparent: its type indicates that it is a pure function but it has
-- the side effect of outputting the trace message.
trace :: () => String -> a -> a
-- | The call inline f arranges that f is inlined,
-- regardless of its size. More precisely, the call inline f
-- rewrites to the right-hand side of f's definition. This
-- allows the programmer to control inlining from a particular call site
-- rather than the definition site of the function (c.f. INLINE
-- pragmas).
--
-- This inlining occurs regardless of the argument to the call or the
-- size of f's definition; it is unconditional. The main caveat
-- is that f's definition must be visible to the compiler; it is
-- therefore recommended to mark the function with an INLINABLE
-- pragma at its definition so that GHC guarantees to record its
-- unfolding regardless of size.
--
-- If no inlining takes place, the inline function expands to the
-- identity function in Phase zero, so its use imposes no overhead.
inline :: () => a -> a
-- | map f xs is the list obtained by applying f
-- to each element of xs, i.e.,
--
-- -- map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn] -- map f [x1, x2, ...] == [f x1, f x2, ...] --map :: () => (a -> b) -> [a] -> [b] -- | The groupWith function uses the user supplied function which -- projects an element out of every list element in order to first sort -- the input list and then to form groups by equality on these projected -- elements groupWith :: Ord b => (a -> b) -> [a] -> [[a]] -- | Application operator. This operator is redundant, since ordinary -- application (f x) means the same as (f $ x). -- However, $ has low, right-associative binding precedence, so it -- sometimes allows parentheses to be omitted; for example: -- --
-- f $ g $ h x = f (g (h x)) ---- -- It is also useful in higher-order situations, such as map -- ($ 0) xs, or zipWith ($) fs xs. -- -- Note that ($) is levity-polymorphic in its result type, so -- that foo $ True where foo :: Bool -> Int# is well-typed ($) :: () => (a -> b) -> a -> b infixr 0 $ -- | general coercion from integral types fromIntegral :: (Integral a, Num b) => a -> b -- | general coercion to fractional types realToFrac :: (Real a, Fractional b) => a -> b -- | Conditional failure of Alternative computations. Defined by -- --
-- guard True = pure () -- guard False = empty ---- --
-- >>> safeDiv 4 0 -- Nothing -- >>> safeDiv 4 2 -- Just 2 ---- -- A definition of safeDiv using guards, but not guard: -- --
-- safeDiv :: Int -> Int -> Maybe Int -- safeDiv x y | y /= 0 = Just (x `div` y) -- | otherwise = Nothing ---- -- A definition of safeDiv using guard and Monad -- do-notation: -- --
-- safeDiv :: Int -> Int -> Maybe Int -- safeDiv x y = do -- guard (y /= 0) -- return (x `div` y) --guard :: Alternative f => Bool -> f () -- | Converts an arbitrary value into an object of type Dynamic. -- -- The type of the object must be an instance of Typeable, which -- ensures that only monomorphically-typed objects may be converted to -- Dynamic. To convert a polymorphic object into Dynamic, -- give it a monomorphic type signature. For example: -- --
-- toDyn (id :: Int -> Int) --toDyn :: Typeable a => a -> Dynamic -- | The join function is the conventional monad join operator. It -- is used to remove one level of monadic structure, projecting its bound -- argument into the outer level. -- --
-- atomically :: STM a -> IO a ---- -- is used to run STM transactions atomically. So, by specializing -- the types of atomically and join to -- --
-- atomically :: STM (IO b) -> IO (IO b) -- join :: IO (IO b) -> IO b ---- -- we can compose them as -- --
-- join . atomically :: STM (IO b) -> IO b ---- -- to run an STM transaction and the IO action it returns. join :: Monad m => m (m a) -> m a -- | The Bounded class is used to name the upper and lower limits of -- a type. Ord is not a superclass of Bounded since types -- that are not totally ordered may also have upper and lower bounds. -- -- The Bounded class may be derived for any enumeration type; -- minBound is the first constructor listed in the data -- declaration and maxBound is the last. Bounded may also -- be derived for single-constructor datatypes whose constituent types -- are in Bounded. class Bounded a minBound :: Bounded a => a maxBound :: Bounded a => a -- | Class Enum defines operations on sequentially ordered types. -- -- The enumFrom... methods are used in Haskell's translation of -- arithmetic sequences. -- -- Instances of Enum may be derived for any enumeration type -- (types whose constructors have no fields). The nullary constructors -- are assumed to be numbered left-to-right by fromEnum from -- 0 through n-1. See Chapter 10 of the Haskell -- Report for more details. -- -- For any type that is an instance of class Bounded as well as -- Enum, the following should hold: -- --
-- enumFrom x = enumFromTo x maxBound -- enumFromThen x y = enumFromThenTo x y bound -- where -- bound | fromEnum y >= fromEnum x = maxBound -- | otherwise = minBound --class Enum a -- | the successor of a value. For numeric types, succ adds 1. succ :: Enum a => a -> a -- | the predecessor of a value. For numeric types, pred subtracts -- 1. pred :: Enum a => a -> a -- | Convert from an Int. toEnum :: Enum a => Int -> a -- | Convert to an Int. It is implementation-dependent what -- fromEnum returns when applied to a value that is too large to -- fit in an Int. fromEnum :: Enum a => a -> Int -- | Used in Haskell's translation of [n..] with [n..] = -- enumFrom n, a possible implementation being enumFrom n = n : -- enumFrom (succ n). For example: -- --
enumFrom 4 :: [Integer] = [4,5,6,7,...]
enumFrom 6 :: [Int] = [6,7,8,9,...,maxBound :: -- Int]
enumFromThen 4 6 :: [Integer] = [4,6,8,10...]
enumFromThen 6 2 :: [Int] = [6,2,-2,-6,...,minBound :: -- Int]
enumFromTo 6 10 :: [Int] = [6,7,8,9,10]
enumFromTo 42 1 :: [Integer] = []
enumFromThenTo 4 2 -6 :: [Integer] = -- [4,2,0,-2,-4,-6]
enumFromThenTo 6 8 2 :: [Int] = []
-- (x `quot` y)*y + (x `rem` y) == x --rem :: Integral a => a -> a -> a -- | integer division truncated toward negative infinity div :: Integral a => a -> a -> a -- | integer modulus, satisfying -- --
-- (x `div` y)*y + (x `mod` y) == x --mod :: Integral a => a -> a -> a -- | simultaneous quot and rem quotRem :: Integral a => a -> a -> (a, a) -- | simultaneous div and mod divMod :: Integral a => a -> a -> (a, a) -- | conversion to Integer toInteger :: Integral a => a -> Integer infixl 7 `quot` infixl 7 `rem` infixl 7 `div` infixl 7 `mod` -- | The Monad class defines the basic operations over a -- monad, a concept from a branch of mathematics known as -- category theory. From the perspective of a Haskell programmer, -- however, it is best to think of a monad as an abstract datatype -- of actions. Haskell's do expressions provide a convenient -- syntax for writing monadic expressions. -- -- Instances of Monad should satisfy the following laws: -- -- -- -- Furthermore, the Monad and Applicative operations should -- relate as follows: -- -- -- -- The above laws imply: -- -- -- -- and that pure and (<*>) satisfy the applicative -- functor laws. -- -- The instances of Monad for lists, Maybe and IO -- defined in the Prelude satisfy these laws. class Applicative m => Monad (m :: Type -> Type) -- | Sequentially compose two actions, passing any value produced by the -- first as an argument to the second. (>>=) :: Monad m => m a -> (a -> m b) -> m b -- | Sequentially compose two actions, discarding any value produced by the -- first, like sequencing operators (such as the semicolon) in imperative -- languages. (>>) :: Monad m => m a -> m b -> m b -- | Inject a value into the monadic type. return :: Monad m => a -> m a -- | Fail with a message. This operation is not part of the mathematical -- definition of a monad, but is invoked on pattern-match failure in a -- do expression. -- -- As part of the MonadFail proposal (MFP), this function is moved to its -- own class MonadFail (see Control.Monad.Fail for more -- details). The definition here will be removed in a future release. fail :: Monad m => String -> m a infixl 1 >>= infixl 1 >> -- | The Data class comprehends a fundamental primitive -- gfoldl for folding over constructor applications, say terms. -- This primitive can be instantiated in several ways to map over the -- immediate subterms of a term; see the gmap combinators later -- in this class. Indeed, a generic programmer does not necessarily need -- to use the ingenious gfoldl primitive but rather the intuitive -- gmap combinators. The gfoldl primitive is completed by -- means to query top-level constructors, to turn constructor -- representations into proper terms, and to list all possible datatype -- constructors. This completion allows us to serve generic programming -- scenarios like read, show, equality, term generation. -- -- The combinators gmapT, gmapQ, gmapM, etc are all -- provided with default definitions in terms of gfoldl, leaving -- open the opportunity to provide datatype-specific definitions. (The -- inclusion of the gmap combinators as members of class -- Data allows the programmer or the compiler to derive -- specialised, and maybe more efficient code per datatype. Note: -- gfoldl is more higher-order than the gmap combinators. -- This is subject to ongoing benchmarking experiments. It might turn out -- that the gmap combinators will be moved out of the class -- Data.) -- -- Conceptually, the definition of the gmap combinators in terms -- of the primitive gfoldl requires the identification of the -- gfoldl function arguments. Technically, we also need to -- identify the type constructor c for the construction of the -- result type from the folded term type. -- -- In the definition of gmapQx combinators, we use -- phantom type constructors for the c in the type of -- gfoldl because the result type of a query does not involve the -- (polymorphic) type of the term argument. In the definition of -- gmapQl we simply use the plain constant type constructor -- because gfoldl is left-associative anyway and so it is readily -- suited to fold a left-associative binary operation over the immediate -- subterms. In the definition of gmapQr, extra effort is needed. We use -- a higher-order accumulation trick to mediate between left-associative -- constructor application vs. right-associative binary operation (e.g., -- (:)). When the query is meant to compute a value of type -- r, then the result type withing generic folding is r -- -> r. So the result of folding is a function to which we -- finally pass the right unit. -- -- With the -XDeriveDataTypeable option, GHC can generate -- instances of the Data class automatically. For example, given -- the declaration -- --
-- data T a b = C1 a b | C2 deriving (Typeable, Data) ---- -- GHC will generate an instance that is equivalent to -- --
-- instance (Data a, Data b) => Data (T a b) where -- gfoldl k z (C1 a b) = z C1 `k` a `k` b -- gfoldl k z C2 = z C2 -- -- gunfold k z c = case constrIndex c of -- 1 -> k (k (z C1)) -- 2 -> z C2 -- -- toConstr (C1 _ _) = con_C1 -- toConstr C2 = con_C2 -- -- dataTypeOf _ = ty_T -- -- con_C1 = mkConstr ty_T "C1" [] Prefix -- con_C2 = mkConstr ty_T "C2" [] Prefix -- ty_T = mkDataType "Module.T" [con_C1, con_C2] ---- -- This is suitable for datatypes that are exported transparently. class Typeable a => Data a -- | Left-associative fold operation for constructor applications. -- -- The type of gfoldl is a headache, but operationally it is a -- simple generalisation of a list fold. -- -- The default definition for gfoldl is const -- id, which is suitable for abstract datatypes with no -- substructures. gfoldl :: Data a => (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. () => g -> c g) -> a -> c a -- | Unfolding constructor applications gunfold :: Data a => (forall b r. Data b => c (b -> r) -> c r) -> (forall r. () => r -> c r) -> Constr -> c a -- | Obtaining the constructor from a given datum. For proper terms, this -- is meant to be the top-level constructor. Primitive datatypes are here -- viewed as potentially infinite sets of values (i.e., constructors). toConstr :: Data a => a -> Constr -- | The outer type constructor of the type dataTypeOf :: Data a => a -> DataType -- | Mediate types and unary type constructors. -- -- In Data instances of the form -- --
-- instance (Data a, ...) => Data (T a) ---- -- dataCast1 should be defined as gcast1. -- -- The default definition is const Nothing, which -- is appropriate for instances of other forms. dataCast1 :: (Data a, Typeable t) => (forall d. Data d => c (t d)) -> Maybe (c a) -- | Mediate types and binary type constructors. -- -- In Data instances of the form -- --
-- instance (Data a, Data b, ...) => Data (T a b) ---- -- dataCast2 should be defined as gcast2. -- -- The default definition is const Nothing, which -- is appropriate for instances of other forms. dataCast2 :: (Data a, Typeable t) => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c a) -- | A generic transformation that maps over the immediate subterms -- -- The default definition instantiates the type constructor c in -- the type of gfoldl to an identity datatype constructor, using -- the isomorphism pair as injection and projection. gmapT :: Data a => (forall b. Data b => b -> b) -> a -> a -- | A generic query with a left-associative binary operator gmapQl :: Data a => (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> a -> r -- | A generic query with a right-associative binary operator gmapQr :: Data a => (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> a -> r -- | A generic query that processes the immediate subterms and returns a -- list of results. The list is given in the same order as originally -- specified in the declaration of the data constructors. gmapQ :: Data a => (forall d. Data d => d -> u) -> a -> [u] -- | A generic query that processes one child by index (zero-based) gmapQi :: Data a => Int -> (forall d. Data d => d -> u) -> a -> u -- | A generic monadic transformation that maps over the immediate subterms -- -- The default definition instantiates the type constructor c in -- the type of gfoldl to the monad datatype constructor, defining -- injection and projection using return and >>=. gmapM :: (Data a, Monad m) => (forall d. Data d => d -> m d) -> a -> m a -- | Transformation of at least one immediate subterm does not fail gmapMp :: (Data a, MonadPlus m) => (forall d. Data d => d -> m d) -> a -> m a -- | Transformation of one immediate subterm with success gmapMo :: (Data a, MonadPlus m) => (forall d. Data d => d -> m d) -> a -> m a -- | The Functor class is used for types that can be mapped over. -- Instances of Functor should satisfy the following laws: -- --
-- fmap id == id -- fmap (f . g) == fmap f . fmap g ---- -- The instances of Functor for lists, Maybe and IO -- satisfy these laws. class Functor (f :: Type -> Type) fmap :: Functor f => (a -> b) -> f a -> f b -- | Replace all locations in the input with the same value. The default -- definition is fmap . const, but this may be -- overridden with a more efficient version. (<$) :: Functor f => a -> f b -> f a infixl 4 <$ -- | Basic numeric class. -- -- The Haskell Report defines no laws for Num. However, '(+)' and -- '(*)' are customarily expected to define a ring and have the following -- properties: -- --
-- abs x * signum x == x ---- -- For real numbers, the signum is either -1 (negative), -- 0 (zero) or 1 (positive). signum :: Num a => a -> a -- | Conversion from an Integer. An integer literal represents the -- application of the function fromInteger to the appropriate -- value of type Integer, so such literals have type -- (Num a) => a. fromInteger :: Num a => Integer -> a infixl 6 + infixl 7 * infixl 6 - -- | The Ord class is used for totally ordered datatypes. -- -- Instances of Ord can be derived for any user-defined datatype -- whose constituent types are in Ord. The declared order of the -- constructors in the data declaration determines the ordering in -- derived Ord instances. The Ordering datatype allows a -- single comparison to determine the precise ordering of two objects. -- -- The Haskell Report defines no laws for Ord. However, -- <= is customarily expected to implement a non-strict partial -- order and have the following properties: -- --
-- infixr 5 :^: -- data Tree a = Leaf a | Tree a :^: Tree a ---- -- the derived instance of Read in Haskell 2010 is equivalent to -- --
-- instance (Read a) => Read (Tree a) where
--
-- readsPrec d r = readParen (d > app_prec)
-- (\r -> [(Leaf m,t) |
-- ("Leaf",s) <- lex r,
-- (m,t) <- readsPrec (app_prec+1) s]) r
--
-- ++ readParen (d > up_prec)
-- (\r -> [(u:^:v,w) |
-- (u,s) <- readsPrec (up_prec+1) r,
-- (":^:",t) <- lex s,
-- (v,w) <- readsPrec (up_prec+1) t]) r
--
-- where app_prec = 10
-- up_prec = 5
--
--
-- Note that right-associativity of :^: is unused.
--
-- The derived instance in GHC is equivalent to
--
-- -- instance (Read a) => Read (Tree a) where -- -- readPrec = parens $ (prec app_prec $ do -- Ident "Leaf" <- lexP -- m <- step readPrec -- return (Leaf m)) -- -- +++ (prec up_prec $ do -- u <- step readPrec -- Symbol ":^:" <- lexP -- v <- step readPrec -- return (u :^: v)) -- -- where app_prec = 10 -- up_prec = 5 -- -- readListPrec = readListPrecDefault ---- -- Why do both readsPrec and readPrec exist, and why does -- GHC opt to implement readPrec in derived Read instances -- instead of readsPrec? The reason is that readsPrec is -- based on the ReadS type, and although ReadS is mentioned -- in the Haskell 2010 Report, it is not a very efficient parser data -- structure. -- -- readPrec, on the other hand, is based on a much more efficient -- ReadPrec datatype (a.k.a "new-style parsers"), but its -- definition relies on the use of the RankNTypes language -- extension. Therefore, readPrec (and its cousin, -- readListPrec) are marked as GHC-only. Nevertheless, it is -- recommended to use readPrec instead of readsPrec -- whenever possible for the efficiency improvements it brings. -- -- As mentioned above, derived Read instances in GHC will -- implement readPrec instead of readsPrec. The default -- implementations of readsPrec (and its cousin, readList) -- will simply use readPrec under the hood. If you are writing a -- Read instance by hand, it is recommended to write it like so: -- --
-- instance Read T where -- readPrec = ... -- readListPrec = readListPrecDefault --class Read a -- | attempts to parse a value from the front of the string, returning a -- list of (parsed value, remaining string) pairs. If there is no -- successful parse, the returned list is empty. -- -- Derived instances of Read and Show satisfy the -- following: -- -- -- -- That is, readsPrec parses the string produced by -- showsPrec, and delivers the value that showsPrec started -- with. readsPrec :: Read a => Int -> ReadS a -- | The method readList is provided to allow the programmer to give -- a specialised way of parsing lists of values. For example, this is -- used by the predefined Read instance of the Char type, -- where values of type String should be are expected to use -- double quotes, rather than square brackets. readList :: Read a => ReadS [a] -- | Proposed replacement for readsPrec using new-style parsers (GHC -- only). readPrec :: Read a => ReadPrec a -- | Proposed replacement for readList using new-style parsers (GHC -- only). The default definition uses readList. Instances that -- define readPrec should also define readListPrec as -- readListPrecDefault. readListPrec :: Read a => ReadPrec [a] class (Num a, Ord a) => Real a -- | the rational equivalent of its real argument with full precision toRational :: Real a => a -> Rational -- | Efficient, machine-independent access to the components of a -- floating-point number. class (RealFrac a, Floating a) => RealFloat a -- | a constant function, returning the radix of the representation (often -- 2) floatRadix :: RealFloat a => a -> Integer -- | a constant function, returning the number of digits of -- floatRadix in the significand floatDigits :: RealFloat a => a -> Int -- | a constant function, returning the lowest and highest values the -- exponent may assume floatRange :: RealFloat a => a -> (Int, Int) -- | The function decodeFloat applied to a real floating-point -- number returns the significand expressed as an Integer and an -- appropriately scaled exponent (an Int). If -- decodeFloat x yields (m,n), then x -- is equal in value to m*b^^n, where b is the -- floating-point radix, and furthermore, either m and -- n are both zero or else b^(d-1) <= abs m < -- b^d, where d is the value of floatDigits -- x. In particular, decodeFloat 0 = (0,0). If the -- type contains a negative zero, also decodeFloat (-0.0) = -- (0,0). The result of decodeFloat x is -- unspecified if either of isNaN x or -- isInfinite x is True. decodeFloat :: RealFloat a => a -> (Integer, Int) -- | encodeFloat performs the inverse of decodeFloat in the -- sense that for finite x with the exception of -0.0, -- uncurry encodeFloat (decodeFloat x) = -- x. encodeFloat m n is one of the two closest -- representable floating-point numbers to m*b^^n (or -- ±Infinity if overflow occurs); usually the closer, but if -- m contains too many bits, the result may be rounded in the -- wrong direction. encodeFloat :: RealFloat a => Integer -> Int -> a -- | exponent corresponds to the second component of -- decodeFloat. exponent 0 = 0 and for finite -- nonzero x, exponent x = snd (decodeFloat x) -- + floatDigits x. If x is a finite floating-point -- number, it is equal in value to significand x * b ^^ -- exponent x, where b is the floating-point radix. -- The behaviour is unspecified on infinite or NaN values. exponent :: RealFloat a => a -> Int -- | The first component of decodeFloat, scaled to lie in the open -- interval (-1,1), either 0.0 or of absolute -- value >= 1/b, where b is the floating-point -- radix. The behaviour is unspecified on infinite or NaN -- values. significand :: RealFloat a => a -> a -- | multiplies a floating-point number by an integer power of the radix scaleFloat :: RealFloat a => Int -> a -> a -- | True if the argument is an IEEE "not-a-number" (NaN) value isNaN :: RealFloat a => a -> Bool -- | True if the argument is an IEEE infinity or negative infinity isInfinite :: RealFloat a => a -> Bool -- | True if the argument is too small to be represented in -- normalized format isDenormalized :: RealFloat a => a -> Bool -- | True if the argument is an IEEE negative zero isNegativeZero :: RealFloat a => a -> Bool -- | True if the argument is an IEEE floating point number isIEEE :: RealFloat a => a -> Bool -- | a version of arctangent taking two real floating-point arguments. For -- real floating x and y, atan2 y x -- computes the angle (from the positive x-axis) of the vector from the -- origin to the point (x,y). atan2 y x returns -- a value in the range [-pi, pi]. It follows the -- Common Lisp semantics for the origin when signed zeroes are supported. -- atan2 y 1, with y in a type that is -- RealFloat, should return the same value as atan -- y. A default definition of atan2 is provided, but -- implementors can provide a more accurate implementation. atan2 :: RealFloat a => a -> a -> a -- | Extracting components of fractions. class (Real a, Fractional a) => RealFrac a -- | The function properFraction takes a real fractional number -- x and returns a pair (n,f) such that x = -- n+f, and: -- --
-- infixr 5 :^: -- data Tree a = Leaf a | Tree a :^: Tree a ---- -- the derived instance of Show is equivalent to -- --
-- instance (Show a) => Show (Tree a) where -- -- showsPrec d (Leaf m) = showParen (d > app_prec) $ -- showString "Leaf " . showsPrec (app_prec+1) m -- where app_prec = 10 -- -- showsPrec d (u :^: v) = showParen (d > up_prec) $ -- showsPrec (up_prec+1) u . -- showString " :^: " . -- showsPrec (up_prec+1) v -- where up_prec = 5 ---- -- Note that right-associativity of :^: is ignored. For example, -- --
-- showsPrec d x r ++ s == showsPrec d x (r ++ s) ---- -- Derived instances of Read and Show satisfy the -- following: -- -- -- -- That is, readsPrec parses the string produced by -- showsPrec, and delivers the value that showsPrec started -- with. showsPrec :: Show a => Int -> a -> ShowS -- | A specialised variant of showsPrec, using precedence context -- zero, and returning an ordinary String. show :: Show a => a -> String -- | The method showList is provided to allow the programmer to give -- a specialised way of showing lists of values. For example, this is -- used by the predefined Show instance of the Char type, -- where values of type String should be shown in double quotes, -- rather than between square brackets. showList :: Show a => [a] -> ShowS -- | The Ix class is used to map a contiguous subrange of values in -- a type onto integers. It is used primarily for array indexing (see the -- array package). -- -- The first argument (l,u) of each of these operations is a -- pair specifying the lower and upper bounds of a contiguous subrange of -- values. -- -- An implementation is entitled to assume the following laws about these -- operations: -- --
-- (<*>) = liftA2 id ---- --
-- liftA2 f x y = f <$> x <*> y ---- -- Further, any definition must satisfy the following: -- --
pure id <*> -- v = v
pure (.) <*> u -- <*> v <*> w = u <*> (v -- <*> w)
pure f <*> -- pure x = pure (f x)
u <*> pure y = -- pure ($ y) <*> u
-- forall x y. p (q x y) = f x . g y ---- -- it follows from the above that -- --
-- liftA2 p (liftA2 q u v) = liftA2 f u . liftA2 g v ---- -- If f is also a Monad, it should satisfy -- -- -- -- (which implies that pure and <*> satisfy the -- applicative functor laws). class Functor f => Applicative (f :: Type -> Type) -- | Lift a value. pure :: Applicative f => a -> f a -- | Sequential application. -- -- A few functors support an implementation of <*> that is -- more efficient than the default one. (<*>) :: Applicative f => f (a -> b) -> f a -> f b -- | Lift a binary function to actions. -- -- Some functors support an implementation of liftA2 that is more -- efficient than the default one. In particular, if fmap is an -- expensive operation, it is likely better to use liftA2 than to -- fmap over the structure and then use <*>. liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c -- | Sequence actions, discarding the value of the first argument. (*>) :: Applicative f => f a -> f b -> f b -- | Sequence actions, discarding the value of the second argument. (<*) :: Applicative f => f a -> f b -> f a infixl 4 <*> infixl 4 *> infixl 4 <* -- | Data structures that can be folded. -- -- For example, given a data type -- --
-- data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a) ---- -- a suitable instance would be -- --
-- instance Foldable Tree where -- foldMap f Empty = mempty -- foldMap f (Leaf x) = f x -- foldMap f (Node l k r) = foldMap f l `mappend` f k `mappend` foldMap f r ---- -- This is suitable even for abstract types, as the monoid is assumed to -- satisfy the monoid laws. Alternatively, one could define -- foldr: -- --
-- instance Foldable Tree where -- foldr f z Empty = z -- foldr f z (Leaf x) = f x z -- foldr f z (Node l k r) = foldr f (f k (foldr f z r)) l ---- -- Foldable instances are expected to satisfy the following -- laws: -- --
-- foldr f z t = appEndo (foldMap (Endo . f) t ) z ---- --
-- foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z ---- --
-- fold = foldMap id ---- --
-- length = getSum . foldMap (Sum . const 1) ---- -- sum, product, maximum, and minimum -- should all be essentially equivalent to foldMap forms, such -- as -- --
-- sum = getSum . foldMap Sum ---- -- but may be less defined. -- -- If the type is also a Functor instance, it should satisfy -- --
-- foldMap f = fold . fmap f ---- -- which implies that -- --
-- foldMap f . fmap g = foldMap (f . g) --class Foldable (t :: Type -> Type) -- | Combine the elements of a structure using a monoid. fold :: (Foldable t, Monoid m) => t m -> m -- | Map each element of the structure to a monoid, and combine the -- results. foldMap :: (Foldable t, Monoid m) => (a -> m) -> t a -> m -- | Right-associative fold of a structure. -- -- In the case of lists, foldr, when applied to a binary operator, -- a starting value (typically the right-identity of the operator), and a -- list, reduces the list using the binary operator, from right to left: -- --
-- foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...) ---- -- Note that, since the head of the resulting expression is produced by -- an application of the operator to the first element of the list, -- foldr can produce a terminating expression from an infinite -- list. -- -- For a general Foldable structure this should be semantically -- identical to, -- --
-- foldr f z = foldr f z . toList --foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b -- | Right-associative fold of a structure, but with strict application of -- the operator. foldr' :: Foldable t => (a -> b -> b) -> b -> t a -> b -- | Left-associative fold of a structure. -- -- In the case of lists, foldl, when applied to a binary operator, -- a starting value (typically the left-identity of the operator), and a -- list, reduces the list using the binary operator, from left to right: -- --
-- foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn ---- -- Note that to produce the outermost application of the operator the -- entire input list must be traversed. This means that foldl' -- will diverge if given an infinite list. -- -- Also note that if you want an efficient left-fold, you probably want -- to use foldl' instead of foldl. The reason for this is -- that latter does not force the "inner" results (e.g. z f -- x1 in the above example) before applying them to the operator -- (e.g. to (f x2)). This results in a thunk chain -- O(n) elements long, which then must be evaluated from the -- outside-in. -- -- For a general Foldable structure this should be semantically -- identical to, -- --
-- foldl f z = foldl f z . toList --foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b -- | Left-associative fold of a structure but with strict application of -- the operator. -- -- This ensures that each step of the fold is forced to weak head normal -- form before being applied, avoiding the collection of thunks that -- would otherwise occur. This is often what you want to strictly reduce -- a finite list to a single, monolithic result (e.g. length). -- -- For a general Foldable structure this should be semantically -- identical to, -- --
-- foldl f z = foldl' f z . toList --foldl' :: Foldable t => (b -> a -> b) -> b -> t a -> b -- | A variant of foldr that has no base case, and thus may only be -- applied to non-empty structures. -- --
-- foldr1 f = foldr1 f . toList --foldr1 :: Foldable t => (a -> a -> a) -> t a -> a -- | A variant of foldl that has no base case, and thus may only be -- applied to non-empty structures. -- --
-- foldl1 f = foldl1 f . toList --foldl1 :: Foldable t => (a -> a -> a) -> t a -> a -- | List of elements of a structure, from left to right. toList :: Foldable t => t a -> [a] -- | Test whether the structure is empty. The default implementation is -- optimized for structures that are similar to cons-lists, because there -- is no general way to do better. null :: Foldable t => t a -> Bool -- | Returns the size/length of a finite structure as an Int. The -- default implementation is optimized for structures that are similar to -- cons-lists, because there is no general way to do better. length :: Foldable t => t a -> Int -- | Does the element occur in the structure? elem :: (Foldable t, Eq a) => a -> t a -> Bool -- | The largest element of a non-empty structure. maximum :: (Foldable t, Ord a) => t a -> a -- | The least element of a non-empty structure. minimum :: (Foldable t, Ord a) => t a -> a -- | The sum function computes the sum of the numbers of a -- structure. sum :: (Foldable t, Num a) => t a -> a -- | The product function computes the product of the numbers of a -- structure. product :: (Foldable t, Num a) => t a -> a infix 4 `elem` -- | Functors representing data structures that can be traversed from left -- to right. -- -- A definition of traverse must satisfy the following laws: -- --
-- t :: (Applicative f, Applicative g) => f a -> g a ---- -- preserving the Applicative operations, i.e. -- -- -- -- and the identity functor Identity and composition of functors -- Compose are defined as -- --
-- newtype Identity a = Identity a -- -- instance Functor Identity where -- fmap f (Identity x) = Identity (f x) -- -- instance Applicative Identity where -- pure x = Identity x -- Identity f <*> Identity x = Identity (f x) -- -- newtype Compose f g a = Compose (f (g a)) -- -- instance (Functor f, Functor g) => Functor (Compose f g) where -- fmap f (Compose x) = Compose (fmap (fmap f) x) -- -- instance (Applicative f, Applicative g) => Applicative (Compose f g) where -- pure x = Compose (pure (pure x)) -- Compose f <*> Compose x = Compose ((<*>) <$> f <*> x) ---- -- (The naturality law is implied by parametricity.) -- -- Instances are similar to Functor, e.g. given a data type -- --
-- data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a) ---- -- a suitable instance would be -- --
-- instance Traversable Tree where -- traverse f Empty = pure Empty -- traverse f (Leaf x) = Leaf <$> f x -- traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r ---- -- This is suitable even for abstract types, as the laws for -- <*> imply a form of associativity. -- -- The superclass instances should satisfy the following: -- --
-- from . to ≡ id -- to . from ≡ id --class Generic a -- | The class of semigroups (types with an associative binary operation). -- -- Instances should satisfy the associativity law: -- -- class Semigroup a -- | The class of monoids (types with an associative binary operation that -- has an identity). Instances should satisfy the following laws: -- --
x <> mempty = x
mempty <> x = x
mconcat = foldr '(<>)' -- mempty
-- foreign import ccall "stdlib.h &free" -- p_free :: FunPtr (Ptr a -> IO ()) ---- -- or a pointer to a Haskell function created using a wrapper stub -- declared to produce a FunPtr of the correct type. For example: -- --
-- type Compare = Int -> Int -> Bool -- foreign import ccall "wrapper" -- mkCompare :: Compare -> IO (FunPtr Compare) ---- -- Calls to wrapper stubs like mkCompare allocate storage, which -- should be released with freeHaskellFunPtr when no longer -- required. -- -- To convert FunPtr values to corresponding Haskell functions, -- one can define a dynamic stub for the specific foreign type, -- e.g. -- --
-- type IntFunction = CInt -> IO () -- foreign import ccall "dynamic" -- mkFun :: FunPtr IntFunction -> IntFunction --data FunPtr a -- | The Either type represents values with two possibilities: a -- value of type Either a b is either Left -- a or Right b. -- -- The Either type is sometimes used to represent a value which is -- either correct or an error; by convention, the Left constructor -- is used to hold an error value and the Right constructor is -- used to hold a correct value (mnemonic: "right" also means "correct"). -- --
-- >>> let s = Left "foo" :: Either String Int -- -- >>> s -- Left "foo" -- -- >>> let n = Right 3 :: Either String Int -- -- >>> n -- Right 3 -- -- >>> :type s -- s :: Either String Int -- -- >>> :type n -- n :: Either String Int ---- -- The fmap from our Functor instance will ignore -- Left values, but will apply the supplied function to values -- contained in a Right: -- --
-- >>> let s = Left "foo" :: Either String Int -- -- >>> let n = Right 3 :: Either String Int -- -- >>> fmap (*2) s -- Left "foo" -- -- >>> fmap (*2) n -- Right 6 ---- -- The Monad instance for Either allows us to chain -- together multiple actions which may fail, and fail overall if any of -- the individual steps failed. First we'll write a function that can -- either parse an Int from a Char, or fail. -- --
-- >>> import Data.Char ( digitToInt, isDigit )
--
-- >>> :{
-- let parseEither :: Char -> Either String Int
-- parseEither c
-- | isDigit c = Right (digitToInt c)
-- | otherwise = Left "parse error"
--
-- >>> :}
--
--
-- The following should work, since both '1' and '2'
-- can be parsed as Ints.
--
--
-- >>> :{
-- let parseMultiple :: Either String Int
-- parseMultiple = do
-- x <- parseEither '1'
-- y <- parseEither '2'
-- return (x + y)
--
-- >>> :}
--
--
-- -- >>> parseMultiple -- Right 3 ---- -- But the following should fail overall, since the first operation where -- we attempt to parse 'm' as an Int will fail: -- --
-- >>> :{
-- let parseMultiple :: Either String Int
-- parseMultiple = do
-- x <- parseEither 'm'
-- y <- parseEither '2'
-- return (x + y)
--
-- >>> :}
--
--
-- -- >>> parseMultiple -- Left "parse error" --data Either a b Left :: a -> Either a b Right :: b -> Either a b data TyCon -- | The type ForeignPtr represents references to objects that are -- maintained in a foreign language, i.e., that are not part of the data -- structures usually managed by the Haskell storage manager. The -- essential difference between ForeignPtrs and vanilla memory -- references of type Ptr a is that the former may be associated -- with finalizers. A finalizer is a routine that is invoked when -- the Haskell storage manager detects that - within the Haskell heap and -- stack - there are no more references left that are pointing to the -- ForeignPtr. Typically, the finalizer will, then, invoke -- routines in the foreign language that free the resources bound by the -- foreign object. -- -- The ForeignPtr is parameterised in the same way as Ptr. -- The type argument of ForeignPtr should normally be an instance -- of class Storable. data ForeignPtr a -- | Haskell defines operations to read and write characters from and to -- files, represented by values of type Handle. Each value of -- this type is a handle: a record used by the Haskell run-time -- system to manage I/O with file system objects. A handle has at -- least the following properties: -- --
-- runST (writeSTRef _|_ v >>= f) = _|_ --data ST s a untangle :: Addr# -> String -> String ioException :: () => IOException -> IO a heapOverflow :: SomeException stackOverflow :: SomeException cannotCompactMutable :: SomeException cannotCompactPinned :: SomeException cannotCompactFunction :: SomeException allocationLimitExceeded :: SomeException blockedIndefinitelyOnSTM :: SomeException blockedIndefinitelyOnMVar :: SomeException unsupportedOperation :: IOError -- | The phase of a complex number, in the range (-pi, -- pi]. If the magnitude is zero, then so is the phase. phase :: RealFloat a => Complex a -> a -- | The nonnegative magnitude of a complex number. magnitude :: RealFloat a => Complex a -> a -- | The function polar takes a complex number and returns a -- (magnitude, phase) pair in canonical form: the magnitude is -- nonnegative, and the phase in the range (-pi, -- pi]; if the magnitude is zero, then so is the phase. polar :: RealFloat a => Complex a -> (a, a) -- | cis t is a complex value with magnitude 1 and -- phase t (modulo 2*pi). cis :: Floating a => a -> Complex a -- | Form a complex number from polar components of magnitude and phase. mkPolar :: Floating a => a -> a -> Complex a -- | The conjugate of a complex number. conjugate :: Num a => Complex a -> Complex a -- | Extracts the imaginary part of a complex number. imagPart :: () => Complex a -> a -- | Extracts the real part of a complex number. realPart :: () => Complex a -> a -- | Complex numbers are an algebraic type. -- -- For a complex number z, abs z is a number -- with the magnitude of z, but oriented in the positive real -- direction, whereas signum z has the phase of -- z, but unit magnitude. -- -- The Foldable and Traversable instances traverse the real -- part first. -- -- Note that Complex's instances inherit the deficiencies from the -- type parameter's. For example, Complex Float's Ord -- instance has similar problems to Float's. data Complex a -- | forms a complex number from its real and imaginary rectangular -- components. (:+) :: !a -> !a -> Complex a infix 6 :+ -- | First arg is whether to chop off trailing zeros showFixed :: HasResolution a => Bool -> Fixed a -> String -- | generalisation of mod to any instance of Real mod' :: Real a => a -> a -> a -- | generalisation of divMod to any instance of Real divMod' :: (Real a, Integral b) => a -> a -> (b, a) -- | generalisation of div to any instance of Real div' :: (Real a, Integral b) => a -> a -> b -- | The type parameter should be an instance of HasResolution. newtype Fixed a MkFixed :: Integer -> Fixed a class HasResolution a resolution :: HasResolution a => p a -> Integer data E0 -- | resolution of 1, this works the same as Integer type Uni = Fixed E0 data E1 -- | resolution of 10^-1 = .1 type Deci = Fixed E1 data E2 -- | resolution of 10^-2 = .01, useful for many monetary currencies type Centi = Fixed E2 data E3 -- | resolution of 10^-3 = .001 type Milli = Fixed E3 data E6 -- | resolution of 10^-6 = .000001 type Micro = Fixed E6 data E9 -- | resolution of 10^-9 = .000000001 type Nano = Fixed E9 data E12 -- | resolution of 10^-12 = .000000000001 type Pico = Fixed E12 -- | The sortWith function sorts a list of elements using the user -- supplied function to project something out of each element sortWith :: Ord b => (a -> b) -> [a] -> [a] -- | Gets the module of a type constructor: take *.*.*... before name tyconModule :: String -> String -- | Gets the unqualified type constructor: drop *.*.*... before name tyconUQname :: String -> String -- | Test for a non-representable type isNorepType :: DataType -> Bool -- | Constructs a non-representation for a non-representable type mkNoRepType :: String -> DataType -- | Makes a constructor for Char. mkCharConstr :: DataType -> Char -> Constr mkRealConstr :: (Real a, Show a) => DataType -> a -> Constr mkIntegralConstr :: (Integral a, Show a) => DataType -> a -> Constr -- | Constructs the Char type mkCharType :: String -> DataType -- | Constructs the Float type mkFloatType :: String -> DataType -- | Constructs the Int type mkIntType :: String -> DataType -- | Gets the maximum constructor index of an algebraic datatype maxConstrIndex :: DataType -> ConIndex -- | Gets the index of a constructor (algebraic datatypes only) constrIndex :: Constr -> ConIndex -- | Gets the constructor for an index (algebraic datatypes only) indexConstr :: DataType -> ConIndex -> Constr -- | Test for an algebraic type isAlgType :: DataType -> Bool -- | Lookup a constructor via a string readConstr :: DataType -> String -> Maybe Constr -- | Gets the string for a constructor showConstr :: Constr -> String -- | Gets the fixity of a constructor constrFixity :: Constr -> Fixity -- | Gets the field labels of a constructor. The list of labels is returned -- in the same order as they were given in the original constructor -- declaration. constrFields :: Constr -> [String] -- | Gets the constructors of an algebraic datatype dataTypeConstrs :: DataType -> [Constr] -- | Constructs a constructor mkConstr :: DataType -> String -> [String] -> Fixity -> Constr -- | Constructs an algebraic datatype mkDataType :: String -> [Constr] -> DataType -- | Look up a constructor by its representation repConstr :: DataType -> ConstrRep -> Constr -- | Gets the public presentation of constructors constrRep :: Constr -> ConstrRep -- | Gets the datatype of a constructor constrType :: Constr -> DataType -- | Gets the public presentation of a datatype dataTypeRep :: DataType -> DataRep -- | Gets the type constructor including the module dataTypeName :: DataType -> String -- | Monadic variation on fromConstrB fromConstrM :: (Monad m, Data a) => (forall d. Data d => m d) -> Constr -> m a -- | Build a term and use a generic function for subterms fromConstrB :: Data a => (forall d. Data d => d) -> Constr -> a -- | Build a term skeleton fromConstr :: Data a => Constr -> a -- | Representation of datatypes. A package of constructor representations -- with names of type and module. data DataType -- | Representation of constructors. Note that equality on constructors -- with different types may not work -- i.e. the constructors for -- False and Nothing may compare equal. data Constr -- | Public representation of datatypes data DataRep AlgRep :: [Constr] -> DataRep IntRep :: DataRep FloatRep :: DataRep CharRep :: DataRep NoRep :: DataRep -- | Public representation of constructors data ConstrRep AlgConstr :: ConIndex -> ConstrRep IntConstr :: Integer -> ConstrRep FloatConstr :: Rational -> ConstrRep CharConstr :: Char -> ConstrRep -- | Unique index for datatype constructors, counting from 1 in the order -- they are given in the program text. type ConIndex = Int -- | Fixity of constructors data Fixity Prefix :: Fixity Infix :: Fixity -- | Wrap an IO computation to time out and return Nothing -- in case no result is available within n microseconds -- (1/10^6 seconds). In case a result is available before the -- timeout expires, Just a is returned. A negative timeout -- interval means "wait indefinitely". When specifying long timeouts, be -- careful not to exceed maxBound :: Int. -- --
-- >>> timeout 1000000 (threadDelay 1000 *> pure "finished on time") -- Just "finished on time" ---- --
-- >>> timeout 10000 (threadDelay 100000 *> pure "finished on time") -- Nothing ---- -- The design of this combinator was guided by the objective that -- timeout n f should behave exactly the same as f as -- long as f doesn't time out. This means that f has -- the same myThreadId it would have without the timeout wrapper. -- Any exceptions f might throw cancel the timeout and propagate -- further up. It also possible for f to receive exceptions -- thrown to it by another thread. -- -- A tricky implementation detail is the question of how to abort an -- IO computation. This combinator relies on asynchronous -- exceptions internally. The technique works very well for computations -- executing inside of the Haskell runtime system, but it doesn't work at -- all for non-Haskell code. Foreign function calls, for example, cannot -- be timed out with this combinator simply because an arbitrary C -- function cannot receive asynchronous exceptions. When timeout -- is used to wrap an FFI call that blocks, no timeout event can be -- delivered until the FFI call returns, which pretty much negates the -- purpose of the combinator. In practice, however, this limitation is -- less severe than it may sound. Standard I/O functions like -- hGetBuf, hPutBuf, Network.Socket.accept, or -- hWaitForInput appear to be blocking, but they really don't -- because the runtime system uses scheduling mechanisms like -- select(2) to perform asynchronous I/O, so it is possible to -- interrupt standard socket I/O or file I/O using this combinator. timeout :: () => Int -> IO a -> IO (Maybe a) -- | Returns an STM action that can be used to wait until data can be -- written to a file descriptor. The second returned value is an IO -- action that can be used to deregister interest in the file descriptor. threadWaitWriteSTM :: Fd -> IO (STM (), IO ()) -- | Returns an STM action that can be used to wait for data to read from a -- file descriptor. The second returned value is an IO action that can be -- used to deregister interest in the file descriptor. threadWaitReadSTM :: Fd -> IO (STM (), IO ()) -- | Block the current thread until data can be written to the given file -- descriptor (GHC only). -- -- This will throw an IOError if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor that -- has been used with threadWaitWrite, use closeFdWith. threadWaitWrite :: Fd -> IO () -- | Block the current thread until data is available to read on the given -- file descriptor (GHC only). -- -- This will throw an IOError if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor that -- has been used with threadWaitRead, use closeFdWith. threadWaitRead :: Fd -> IO () -- | Run the IO computation passed as the first argument. If the -- calling thread is bound, an unbound thread is created -- temporarily using forkIO. runInBoundThread doesn't -- finish until the IO computation finishes. -- -- Use this function only in the rare case that you have actually -- observed a performance loss due to the use of bound threads. A program -- that doesn't need its main thread to be bound and makes heavy -- use of concurrency (e.g. a web server), might want to wrap its -- main action in runInUnboundThread. -- -- Note that exceptions which are thrown to the current thread are thrown -- in turn to the thread that is executing the given computation. This -- ensures there's always a way of killing the forked thread. runInUnboundThread :: () => IO a -> IO a -- | Run the IO computation passed as the first argument. If the -- calling thread is not bound, a bound thread is created -- temporarily. runInBoundThread doesn't finish until the -- IO computation finishes. -- -- You can wrap a series of foreign function calls that rely on -- thread-local state with runInBoundThread so that you can use -- them without knowing whether the current thread is bound. runInBoundThread :: () => IO a -> IO a -- | Returns True if the calling thread is bound, that is, if -- it is safe to use foreign libraries that rely on thread-local state -- from the calling thread. isCurrentThreadBound :: IO Bool -- | Like forkIOWithUnmask, but the child thread is a bound thread, -- as with forkOS. forkOSWithUnmask :: ((forall a. () => IO a -> IO a) -> IO ()) -> IO ThreadId -- | Like forkIO, this sparks off a new thread to run the IO -- computation passed as the first argument, and returns the -- ThreadId of the newly created thread. -- -- However, forkOS creates a bound thread, which is -- necessary if you need to call foreign (non-Haskell) libraries that -- make use of thread-local state, such as OpenGL (see -- Control.Concurrent#boundthreads). -- -- Using forkOS instead of forkIO makes no difference at -- all to the scheduling behaviour of the Haskell runtime system. It is a -- common misconception that you need to use forkOS instead of -- forkIO to avoid blocking all the Haskell threads when making a -- foreign call; this isn't the case. To allow foreign calls to be made -- without blocking all the Haskell threads (with GHC), it is only -- necessary to use the -threaded option when linking your -- program, and to make sure the foreign import is not marked -- unsafe. forkOS :: IO () -> IO ThreadId -- | Fork a thread and call the supplied function when the thread is about -- to terminate, with an exception or a returned value. The function is -- called with asynchronous exceptions masked. -- --
-- forkFinally action and_then = -- mask $ \restore -> -- forkIO $ try (restore action) >>= and_then ---- -- This function is useful for informing the parent when a child -- terminates, for example. forkFinally :: () => IO a -> (Either SomeException a -> IO ()) -> IO ThreadId -- | True if bound threads are supported. If -- rtsSupportsBoundThreads is False, -- isCurrentThreadBound will always return False and both -- forkOS and runInBoundThread will fail. rtsSupportsBoundThreads :: Bool -- | Write an entire list of items to a Chan. writeList2Chan :: () => Chan a -> [a] -> IO () -- | Return a lazy list representing the contents of the supplied -- Chan, much like hGetContents. getChanContents :: () => Chan a -> IO [a] -- | Duplicate a Chan: the duplicate channel begins empty, but data -- written to either channel from then on will be available from both. -- Hence this creates a kind of broadcast channel, where data written by -- anyone is seen by everyone else. -- -- (Note that a duplicated channel is not equal to its original. So: -- fmap (c /=) $ dupChan c returns True for all -- c.) dupChan :: () => Chan a -> IO (Chan a) -- | Read the next value from the Chan. Blocks when the channel is -- empty. Since the read end of a channel is an MVar, this -- operation inherits fairness guarantees of MVars (e.g. threads -- blocked in this operation are woken up in FIFO order). -- -- Throws BlockedIndefinitelyOnMVar when the channel is empty -- and no other thread holds a reference to the channel. readChan :: () => Chan a -> IO a -- | Write a value to a Chan. writeChan :: () => Chan a -> a -> IO () -- | Build and returns a new instance of Chan. newChan :: () => IO (Chan a) -- | Chan is an abstract type representing an unbounded FIFO -- channel. data Chan a -- | Signal that a unit of the QSem is available signalQSem :: QSem -> IO () -- | Wait for a unit to become available waitQSem :: QSem -> IO () -- | Build a new QSem with a supplied initial quantity. The initial -- quantity must be at least 0. newQSem :: Int -> IO QSem -- | QSem is a quantity semaphore in which the resource is acquired -- and released in units of one. It provides guaranteed FIFO ordering for -- satisfying blocked waitQSem calls. -- -- The pattern -- --
-- bracket_ waitQSem signalQSem (...) ---- -- is safe; it never loses a unit of the resource. data QSem -- | Signal that a given quantity is now available from the QSemN. signalQSemN :: QSemN -> Int -> IO () -- | Wait for the specified quantity to become available waitQSemN :: QSemN -> Int -> IO () -- | Build a new QSemN with a supplied initial quantity. The initial -- quantity must be at least 0. newQSemN :: Int -> IO QSemN -- | QSemN is a quantity semaphore in which the resource is acquired -- and released in units of one. It provides guaranteed FIFO ordering for -- satisfying blocked waitQSemN calls. -- -- The pattern -- --
-- bracket_ (waitQSemN n) (signalQSemN n) (...) ---- -- is safe; it never loses any of the resource. data QSemN -- | A bifunctor is a type constructor that takes two type arguments and is -- a functor in both arguments. That is, unlike with -- Functor, a type constructor such as Either does not need -- to be partially applied for a Bifunctor instance, and the -- methods in this class permit mapping functions over the Left -- value or the Right value, or both at the same time. -- -- Formally, the class Bifunctor represents a bifunctor from -- Hask -> Hask. -- -- Intuitively it is a bifunctor where both the first and second -- arguments are covariant. -- -- You can define a Bifunctor by either defining bimap or -- by defining both first and second. -- -- If you supply bimap, you should ensure that: -- --
-- bimap id id ≡ id ---- -- If you supply first and second, ensure: -- --
-- first id ≡ id -- second id ≡ id ---- -- If you supply both, you should also ensure: -- --
-- bimap f g ≡ first f . second g ---- -- These ensure by parametricity: -- --
-- bimap (f . g) (h . i) ≡ bimap f h . bimap g i -- first (f . g) ≡ first f . first g -- second (f . g) ≡ second f . second g --class Bifunctor (p :: Type -> Type -> Type) -- | Map over both arguments at the same time. -- --
-- bimap f g ≡ first f . second g ---- --
-- >>> bimap toUpper (+1) ('j', 3)
-- ('J',4)
--
--
-- -- >>> bimap toUpper (+1) (Left 'j') -- Left 'J' ---- --
-- >>> bimap toUpper (+1) (Right 3) -- Right 4 --bimap :: Bifunctor p => (a -> b) -> (c -> d) -> p a c -> p b d -- | Map covariantly over the first argument. -- --
-- first f ≡ bimap f id ---- --
-- >>> first toUpper ('j', 3)
-- ('J',3)
--
--
-- -- >>> first toUpper (Left 'j') -- Left 'J' --first :: Bifunctor p => (a -> b) -> p a c -> p b c -- | Map covariantly over the second argument. -- --
-- second ≡ bimap id ---- --
-- >>> second (+1) ('j', 3)
-- ('j',4)
--
--
-- -- >>> second (+1) (Right 3) -- Right 4 --second :: Bifunctor p => (b -> c) -> p a b -> p a c -- | approxRational, applied to two real fractional numbers -- x and epsilon, returns the simplest rational number -- within epsilon of x. A rational number y is -- said to be simpler than another y' if -- --
-- >>> :{
-- runST (do
-- ref <- newSTRef ""
-- modifySTRef ref (const "world")
-- modifySTRef ref (++ "!")
-- modifySTRef ref ("Hello, " ++)
-- readSTRef ref )
-- :}
-- "Hello, world!"
--
--
-- Be warned that modifySTRef does not apply the function
-- strictly. This means if the program calls modifySTRef many
-- times, but seldomly uses the value, thunks will pile up in memory
-- resulting in a space leak. This is a common mistake made when using an
-- STRef as a counter. For example, the following will leak memory and
-- may produce a stack overflow:
--
--
-- >>> import Control.Monad (replicateM_)
--
-- >>> :{
-- print (runST (do
-- ref <- newSTRef 0
-- replicateM_ 1000 $ modifySTRef ref (+1)
-- readSTRef ref ))
-- :}
-- 1000
--
--
-- To avoid this problem, use modifySTRef' instead.
modifySTRef :: () => STRef s a -> (a -> a) -> ST s ()
-- | Hashes a Unique into an Int. Two Uniques may hash
-- to the same value, although in practice this is unlikely. The
-- Int returned makes a good hash key.
hashUnique :: Unique -> Int
-- | Creates a new object of type Unique. The value returned will
-- not compare equal to any other value of type Unique returned by
-- previous calls to newUnique. There is no limit on the number of
-- times newUnique may be called.
newUnique :: IO Unique
-- | An abstract unique object. Objects of type Unique may be
-- compared for equality and ordering and hashed into Int.
--
--
-- >>> :{
-- do x <- newUnique
-- print (x == x)
-- y <- newUnique
-- print (x == y)
-- :}
-- True
-- False
--
data Unique
-- | Equality on StableName that does not require that the types of
-- the arguments match.
eqStableName :: () => StableName a -> StableName b -> Bool
-- | Convert a StableName to an Int. The Int returned
-- is not necessarily unique; several StableNames may map to the
-- same Int (in practice however, the chances of this are small,
-- so the result of hashStableName makes a good hash key).
hashStableName :: () => StableName a -> Int
-- | Makes a StableName for an arbitrary object. The object passed
-- as the first argument is not evaluated by makeStableName.
makeStableName :: () => a -> IO (StableName a)
-- | An abstract name for an object, that supports equality and hashing.
--
-- Stable names have the following property:
--
-- -- setEnv name "" ---- -- has the same effect as -- --
-- unsetEnv name ---- -- If you'd like to be able to set environment variables to blank -- strings, use setEnv. -- -- Throws IOException if name is the empty string or -- contains an equals sign. setEnv :: String -> String -> IO () -- | Return the value of the environment variable var, or -- Nothing if there is no such value. -- -- For POSIX users, this is equivalent to getEnv. lookupEnv :: String -> IO (Maybe String) -- | Computation getEnv var returns the value of the -- environment variable var. For the inverse, the setEnv -- function can be used. -- -- This computation may fail with: -- --
-- >>> printf "%s, %d, %.4f" "hello" 123 pi -- hello, 123, 3.1416 ---- -- The return value is either String or (IO a) -- (which should be (IO '()'), but Haskell's type system -- makes this hard). -- -- The format string consists of ordinary characters and conversion -- specifications, which specify how to format one of the arguments -- to printf in the output string. A format specification is -- introduced by the % character; this character can be -- self-escaped into the format string using %%. A format -- specification ends with a /format character/ that provides the primary -- information about how to format the value. The rest of the conversion -- specification is optional. In order, one may have flag characters, a -- width specifier, a precision specifier, and type-specific modifier -- characters. -- -- Unlike C printf(3), the formatting of this printf is -- driven by the argument type; formatting is type specific. The types -- formatted by printf "out of the box" are: -- -- -- -- printf is also extensible to support other types: see below. -- -- A conversion specification begins with the character %, -- followed by zero or more of the following flags: -- --
-- - left adjust (default is right adjust) -- + always use a sign (+ or -) for signed conversions -- space leading space for positive numbers in signed conversions -- 0 pad with zeros rather than spaces -- # use an \"alternate form\": see below ---- -- When both flags are given, - overrides 0 and -- + overrides space. A negative width specifier in a * -- conversion is treated as positive but implies the left adjust flag. -- -- The "alternate form" for unsigned radix conversions is as in C -- printf(3): -- --
-- %o prefix with a leading 0 if needed -- %x prefix with a leading 0x if nonzero -- %X prefix with a leading 0X if nonzero -- %b prefix with a leading 0b if nonzero -- %[eEfFgG] ensure that the number contains a decimal point ---- -- Any flags are followed optionally by a field width: -- --
-- num field width -- * as num, but taken from argument list ---- -- The field width is a minimum, not a maximum: it will be expanded as -- needed to avoid mutilating a value. -- -- Any field width is followed optionally by a precision: -- --
-- .num precision -- . same as .0 -- .* as num, but taken from argument list ---- -- Negative precision is taken as 0. The meaning of the precision depends -- on the conversion type. -- --
-- Integral minimum number of digits to show -- RealFloat number of digits after the decimal point -- String maximum number of characters ---- -- The precision for Integral types is accomplished by zero-padding. If -- both precision and zero-pad are given for an Integral field, the -- zero-pad is ignored. -- -- Any precision is followed optionally for Integral types by a width -- modifier; the only use of this modifier being to set the implicit size -- of the operand for conversion of a negative operand to unsigned: -- --
-- hh Int8 -- h Int16 -- l Int32 -- ll Int64 -- L Int64 ---- -- The specification ends with a format character: -- --
-- c character Integral -- d decimal Integral -- o octal Integral -- x hexadecimal Integral -- X hexadecimal Integral -- b binary Integral -- u unsigned decimal Integral -- f floating point RealFloat -- F floating point RealFloat -- g general format float RealFloat -- G general format float RealFloat -- e exponent format float RealFloat -- E exponent format float RealFloat -- s string String -- v default format any type ---- -- The "%v" specifier is provided for all built-in types, and should be -- provided for user-defined type formatters as well. It picks a "best" -- representation for the given type. For the built-in types the "%v" -- specifier is converted as follows: -- --
-- c Char -- u other unsigned Integral -- d other signed Integral -- g RealFloat -- s String ---- -- Mismatch between the argument types and the format string, as well as -- any other syntactic or semantic errors in the format string, will -- cause an exception to be thrown at runtime. -- -- Note that the formatting for RealFloat types is currently a bit -- different from that of C printf(3), conforming instead to -- showEFloat, showFFloat and showGFloat (and their -- alternate versions showFFloatAlt and showGFloatAlt). -- This is hard to fix: the fixed versions would format in a -- backward-incompatible way. In any case the Haskell behavior is -- generally more sensible than the C behavior. A brief summary of some -- key differences: -- --
-- filter = ( mfilter :: (a -> Bool) -> [a] -> [a] ) ---- -- An example using mfilter with the Maybe monad: -- --
-- >>> mfilter odd (Just 1) -- Just 1 -- >>> mfilter odd (Just 2) -- Nothing --mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a -- | Strict version of <$>. (<$!>) :: Monad m => (a -> b) -> m a -> m b infixl 4 <$!> -- | The reverse of when. unless :: Applicative f => Bool -> f () -> f () -- | Like replicateM, but discards the result. replicateM_ :: Applicative m => Int -> m a -> m () -- | replicateM n act performs the action n times, -- gathering the results. replicateM :: Applicative m => Int -> m a -> m [a] -- | Like foldM, but discards the result. foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m () -- | The foldM function is analogous to foldl, except that -- its result is encapsulated in a monad. Note that foldM works -- from left-to-right over the list arguments. This could be an issue -- where (>>) and the `folded function' are not -- commutative. -- --
-- foldM f a1 [x1, x2, ..., xm] -- -- == -- -- do -- a2 <- f a1 x1 -- a3 <- f a2 x2 -- ... -- f am xm ---- -- If right-to-left evaluation is required, the input list should be -- reversed. -- -- Note: foldM is the same as foldlM foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | zipWithM_ is the extension of zipWithM which ignores the -- final result. zipWithM_ :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m () -- | The zipWithM function generalizes zipWith to arbitrary -- applicative functors. zipWithM :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m [c] -- | The mapAndUnzipM function maps its first argument over a list, -- returning the result as a pair of lists. This function is mainly used -- with complicated data structures or a state-transforming monad. mapAndUnzipM :: Applicative m => (a -> m (b, c)) -> [a] -> m ([b], [c]) -- | Repeat an action indefinitely. -- --
-- echoServer :: Socket -> IO () -- echoServer socket = forever $ do -- client <- accept socket -- forkFinally (echo client) (\_ -> hClose client) -- where -- echo :: Handle -> IO () -- echo client = forever $ -- hGetLine client >>= hPutStrLn client --forever :: Applicative f => f a -> f b -- | Right-to-left composition of Kleisli arrows. -- (>=>), with the arguments flipped. -- -- Note how this operator resembles function composition -- (.): -- --
-- (.) :: (b -> c) -> (a -> b) -> a -> c -- (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c --(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c infixr 1 <=< -- | Left-to-right composition of Kleisli arrows. (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 >=> -- | This generalizes the list-based filter function. filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a] -- | Construct tag-less Version makeVersion :: [Int] -> Version -- | A parser for versions in the format produced by showVersion. parseVersion :: ReadP Version -- | Provides one possible concrete representation for Version. For -- a version with versionBranch = [1,2,3] and -- versionTags = ["tag1","tag2"], the output will be -- 1.2.3-tag1-tag2. showVersion :: Version -> String -- | A Version represents the version of a software entity. -- -- An instance of Eq is provided, which implements exact equality -- modulo reordering of the tags in the versionTags field. -- -- An instance of Ord is also provided, which gives lexicographic -- ordering on the versionBranch fields (i.e. 2.1 > 2.0, 1.2.3 -- > 1.2.2, etc.). This is expected to be sufficient for many uses, -- but note that you may need to use a more specific ordering for your -- versioning scheme. For example, some versioning schemes may include -- pre-releases which have tags "pre1", "pre2", and so -- on, and these would need to be taken into account when determining -- ordering. In some cases, date ordering may be more appropriate, so the -- application would have to look for date tags in the -- versionTags field and compare those. The bottom line is, don't -- always assume that compare and other Ord operations are -- the right thing for every Version. -- -- Similarly, concrete representations of versions may differ. One -- possible concrete representation is provided (see showVersion -- and parseVersion), but depending on the application a different -- concrete representation may be more appropriate. data Version Version :: [Int] -> [String] -> Version -- | The numeric branch for this version. This reflects the fact that most -- software versions are tree-structured; there is a main trunk which is -- tagged with versions at various points (1,2,3...), and the first -- branch off the trunk after version 3 is 3.1, the second branch off the -- trunk after version 3 is 3.2, and so on. The tree can be branched -- arbitrarily, just by adding more digits. -- -- We represent the branch as a list of Int, so version 3.2.1 -- becomes [3,2,1]. Lexicographic ordering (i.e. the default instance of -- Ord for [Int]) gives the natural ordering of branches. [versionBranch] :: Version -> [Int] -- | A version can be tagged with an arbitrary list of strings. The -- interpretation of the list of tags is entirely dependent on the entity -- that this version applies to. [versionTags] :: Version -> [String] -- | The traceMarkerIO function emits a marker to the eventlog, if -- eventlog profiling is available and enabled at runtime. -- -- Compared to traceMarker, traceMarkerIO sequences the -- event with respect to other IO actions. traceMarkerIO :: String -> IO () -- | The traceMarker function emits a marker to the eventlog, if -- eventlog profiling is available and enabled at runtime. The -- String is the name of the marker. The name is just used in -- the profiling tools to help you keep clear which marker is which. -- -- This function is suitable for use in pure code. In an IO context use -- traceMarkerIO instead. -- -- Note that when using GHC's SMP runtime, it is possible (but rare) to -- get duplicate events emitted if two CPUs simultaneously evaluate the -- same thunk that uses traceMarker. traceMarker :: () => String -> a -> a -- | The traceEventIO function emits a message to the eventlog, if -- eventlog profiling is available and enabled at runtime. -- -- Compared to traceEvent, traceEventIO sequences the event -- with respect to other IO actions. traceEventIO :: String -> IO () -- | The traceEvent function behaves like trace with the -- difference that the message is emitted to the eventlog, if eventlog -- profiling is available and enabled at runtime. -- -- It is suitable for use in pure code. In an IO context use -- traceEventIO instead. -- -- Note that when using GHC's SMP runtime, it is possible (but rare) to -- get duplicate events emitted if two CPUs simultaneously evaluate the -- same thunk that uses traceEvent. traceEvent :: () => String -> a -> a -- | like trace, but additionally prints a call stack if one is -- available. -- -- In the current GHC implementation, the call stack is only available if -- the program was compiled with -prof; otherwise -- traceStack behaves exactly like trace. Entries in the -- call stack correspond to SCC annotations, so it is a good -- idea to use -fprof-auto or -fprof-auto-calls to add -- SCC annotations automatically. traceStack :: () => String -> a -> a -- | Like traceM, but uses show on the argument to convert it -- to a String. -- --
-- >>> :{
-- do
-- x <- Just 3
-- traceShowM x
-- y <- pure 12
-- traceShowM y
-- pure (x*2 + y)
-- :}
-- 3
-- 12
-- Just 18
--
traceShowM :: (Show a, Applicative f) => a -> f ()
-- | Like trace but returning unit in an arbitrary
-- Applicative context. Allows for convenient use in do-notation.
--
-- Note that the application of traceM is not an action in the
-- Applicative context, as traceIO is in the IO
-- type. While the fresh bindings in the following example will force the
-- traceM expressions to be reduced every time the
-- do-block is executed, traceM "not crashed" would
-- only be reduced once, and the message would only be printed once. If
-- your monad is in MonadIO, liftIO . traceIO may be a
-- better option.
--
--
-- >>> :{
-- do
-- x <- Just 3
-- traceM ("x: " ++ show x)
-- y <- pure 12
-- traceM ("y: " ++ show y)
-- pure (x*2 + y)
-- :}
-- x: 3
-- y: 12
-- Just 18
--
traceM :: Applicative f => String -> f ()
-- | Like traceShow but returns the shown value instead of a third
-- value.
--
-- -- >>> traceShowId (1+2+3, "hello" ++ "world") -- (6,"helloworld") -- (6,"helloworld") --traceShowId :: Show a => a -> a -- | Like trace, but uses show on the argument to convert it -- to a String. -- -- This makes it convenient for printing the values of interesting -- variables or expressions inside a function. For example here we print -- the value of the variables x and y: -- --
-- >>> let f x y = traceShow (x,y) (x + y) in f (1+2) 5 -- (3,5) -- 8 --traceShow :: Show a => a -> b -> b -- | Like trace but returns the message instead of a third value. -- --
-- >>> traceId "hello" -- "hello -- hello" --traceId :: String -> String putTraceMsg :: String -> IO () -- | The traceIO function outputs the trace message from the IO -- monad. This sequences the output with respect to other IO actions. traceIO :: String -> IO () -- | The isSubsequenceOf function takes two lists and returns -- True if all the elements of the first list occur, in order, in -- the second. The elements do not have to occur consecutively. -- -- isSubsequenceOf x y is equivalent to elem x -- (subsequences y). -- --
-- >>> isSubsequenceOf "GHC" "The Glorious Haskell Compiler" -- True -- -- >>> isSubsequenceOf ['a','d'..'z'] ['a'..'z'] -- True -- -- >>> isSubsequenceOf [1..10] [10,9..0] -- False --isSubsequenceOf :: Eq a => [a] -> [a] -> Bool -- | This function may be used as a value for foldMap in a -- Foldable instance. -- --
-- foldMapDefault f ≡ getConst . traverse (Const . f) --foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m -- | This function may be used as a value for fmap in a -- Functor instance, provided that traverse is defined. -- (Using fmapDefault with a Traversable instance defined -- only by sequenceA will result in infinite recursion.) -- --
-- fmapDefault f ≡ runIdentity . traverse (Identity . f) --fmapDefault :: Traversable t => (a -> b) -> t a -> t b -- | The mapAccumR function behaves like a combination of -- fmap and foldr; it applies a function to each element -- of a structure, passing an accumulating parameter from right to left, -- and returning a final value of this accumulator together with the new -- structure. mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) -- | The mapAccumL function behaves like a combination of -- fmap and foldl; it applies a function to each element -- of a structure, passing an accumulating parameter from left to right, -- and returning a final value of this accumulator together with the new -- structure. mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) -- | forM is mapM with its arguments flipped. For a version -- that ignores the results see forM_. forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b) -- | for is traverse with its arguments flipped. For a -- version that ignores the results see for_. for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b) -- | One or none. optional :: Alternative f => f a -> f (Maybe a) newtype WrappedMonad (m :: Type -> Type) a WrapMonad :: m a -> WrappedMonad a [unwrapMonad] :: WrappedMonad a -> m a newtype WrappedArrow (a :: Type -> Type -> Type) b c WrapArrow :: a b c -> WrappedArrow b c [unwrapArrow] :: WrappedArrow b c -> a b c -- | Lists, but with an Applicative functor based on zipping. newtype ZipList a ZipList :: [a] -> ZipList a [getZipList] :: ZipList a -> [a] -- | Any instance of ArrowApply can be made into an instance of -- ArrowChoice by defining left = leftApp. leftApp :: ArrowApply a => a b c -> a (Either b d) (Either c d) -- | Postcomposition with a pure function (right-to-left variant). (^<<) :: Arrow a => (c -> d) -> a b c -> a b d infixr 1 ^<< -- | Precomposition with a pure function (right-to-left variant). (<<^) :: Arrow a => a c d -> (b -> c) -> a b d infixr 1 <<^ -- | Postcomposition with a pure function. (>>^) :: Arrow a => a b c -> (c -> d) -> a b d infixr 1 >>^ -- | Precomposition with a pure function. (^>>) :: Arrow a => (b -> c) -> a c d -> a b d infixr 1 ^>> -- | The identity arrow, which plays the role of return in arrow -- notation. returnA :: Arrow a => a b b -- | The basic arrow class. -- -- Instances should satisfy the following laws: -- --
arr id = id
arr (f >>> g) = arr f >>> -- arr g
first (arr f) = arr (first -- f)
first (f >>> g) = first f >>> -- first g
first f >>> arr fst = -- arr fst >>> f
first f >>> arr (id *** g) = -- arr (id *** g) >>> first f
first (first f) >>> arr -- assoc = arr assoc >>> first -- f
-- assoc ((a,b),c) = (a,(b,c)) ---- -- The other combinators have sensible default definitions, which may be -- overridden for efficiency. class Category a => Arrow (a :: Type -> Type -> Type) -- | Lift a function to an arrow. arr :: Arrow a => (b -> c) -> a b c -- | Split the input between the two argument arrows and combine their -- output. Note that this is in general not a functor. -- -- The default definition may be overridden with a more efficient version -- if desired. (***) :: Arrow a => a b c -> a b' c' -> a (b, b') (c, c') -- | Fanout: send the input to both argument arrows and combine their -- output. -- -- The default definition may be overridden with a more efficient version -- if desired. (&&&) :: Arrow a => a b c -> a b c' -> a b (c, c') infixr 3 *** infixr 3 &&& -- | Kleisli arrows of a monad. newtype Kleisli (m :: Type -> Type) a b Kleisli :: (a -> m b) -> Kleisli a b [runKleisli] :: Kleisli a b -> a -> m b class Arrow a => ArrowZero (a :: Type -> Type -> Type) zeroArrow :: ArrowZero a => a b c -- | A monoid on arrows. class ArrowZero a => ArrowPlus (a :: Type -> Type -> Type) -- | An associative operation with identity zeroArrow. (<+>) :: ArrowPlus a => a b c -> a b c -> a b c infixr 5 <+> -- | Choice, for arrows that support it. This class underlies the -- if and case constructs in arrow notation. -- -- Instances should satisfy the following laws: -- --
left (arr f) = arr (left -- f)
left (f >>> g) = left f >>> -- left g
f >>> arr Left = arr -- Left >>> left f
left f >>> arr (id +++ g) = -- arr (id +++ g) >>> left f
left (left f) >>> arr -- assocsum = arr assocsum >>> -- left f
-- assocsum (Left (Left x)) = Left x -- assocsum (Left (Right y)) = Right (Left y) -- assocsum (Right z) = Right (Right z) ---- -- The other combinators have sensible default definitions, which may be -- overridden for efficiency. class Arrow a => ArrowChoice (a :: Type -> Type -> Type) -- | Feed marked inputs through the argument arrow, passing the rest -- through unchanged to the output. left :: ArrowChoice a => a b c -> a (Either b d) (Either c d) -- | A mirror image of left. -- -- The default definition may be overridden with a more efficient version -- if desired. right :: ArrowChoice a => a b c -> a (Either d b) (Either d c) -- | Split the input between the two argument arrows, retagging and merging -- their outputs. Note that this is in general not a functor. -- -- The default definition may be overridden with a more efficient version -- if desired. (+++) :: ArrowChoice a => a b c -> a b' c' -> a (Either b b') (Either c c') -- | Fanin: Split the input between the two argument arrows and merge their -- outputs. -- -- The default definition may be overridden with a more efficient version -- if desired. (|||) :: ArrowChoice a => a b d -> a c d -> a (Either b c) d infixr 2 ||| infixr 2 +++ -- | Some arrows allow application of arrow inputs to other inputs. -- Instances should satisfy the following laws: -- --
first (arr (\x -> arr (\y -> -- (x,y)))) >>> app = id
first (arr (g >>>)) >>> -- app = second g >>> app
first (arr (>>> h)) >>> -- app = app >>> h
-- assoc ((a,b),c) = (a,(b,c)) -- unassoc (a,(b,c)) = ((a,b),c) --class Arrow a => ArrowLoop (a :: Type -> Type -> Type) loop :: ArrowLoop a => a (b, d) (c, d) -> a b c -- | The readIO function is similar to read except that it -- signals parse failure to the IO monad instead of terminating -- the program. readIO :: Read a => String -> IO a -- | The readLn function combines getLine and readIO. readLn :: Read a => IO a -- | The computation appendFile file str function appends -- the string str, to the file file. -- -- Note that writeFile and appendFile write a literal -- string to a file. To write a value of any printable type, as with -- print, use the show function to convert the value to a -- string first. -- --
-- main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]]) --appendFile :: FilePath -> String -> IO () -- | The computation writeFile file str function writes the -- string str, to the file file. writeFile :: FilePath -> String -> IO () -- | The readFile function reads a file and returns the contents of -- the file as a string. The file is read lazily, on demand, as with -- getContents. readFile :: FilePath -> IO String -- | The interact function takes a function of type -- String->String as its argument. The entire input from the -- standard input device is passed to this function as its argument, and -- the resulting string is output on the standard output device. interact :: (String -> String) -> IO () -- | The getContents operation returns all user input as a single -- string, which is read lazily as it is needed (same as -- hGetContents stdin). getContents :: IO String -- | Read a line from the standard input device (same as hGetLine -- stdin). getLine :: IO String -- | Read a character from the standard input device (same as -- hGetChar stdin). getChar :: IO Char -- | The same as putStr, but adds a newline character. putStrLn :: String -> IO () -- | Write a string to the standard output device (same as hPutStr -- stdout). putStr :: String -> IO () -- | Write a character to the standard output device (same as -- hPutChar stdout). putChar :: Char -> IO () -- | Computation hClose hdl makes handle hdl -- closed. Before the computation finishes, if hdl is writable -- its buffer is flushed as for hFlush. Performing hClose -- on a handle that has already been closed has no effect; doing so is -- not an error. All other operations on a closed handle will fail. If -- hClose fails for any reason, any further operations (apart from -- hClose) on the handle will still fail as if hdl had -- been successfully closed. hClose :: Handle -> IO () -- | Switch the value of returned TVar from initial value -- False to True after a given number of microseconds. The -- caveats associated with threadDelay also apply. registerDelay :: Int -> IO (TVar Bool) -- | Suspends the current thread for a given number of microseconds (GHC -- only). -- -- There is no guarantee that the thread will be rescheduled promptly -- when the delay has expired, but the thread will never continue to run -- earlier than specified. threadDelay :: Int -> IO () -- | Close a file descriptor in a concurrency-safe way (GHC only). If you -- are using threadWaitRead or threadWaitWrite to perform -- blocking I/O, you must use this function to close file -- descriptors, or blocked threads may not be woken. -- -- Any threads that are blocked on the file descriptor via -- threadWaitRead or threadWaitWrite will be unblocked by -- having IO exceptions thrown. closeFdWith :: (Fd -> IO ()) -> Fd -> IO () ioManagerCapabilitiesChanged :: IO () ensureIOManagerIsRunning :: IO () runHandlers :: ForeignPtr Word8 -> Signal -> IO () setHandler :: Signal -> Maybe (HandlerFun, Dynamic) -> IO (Maybe (HandlerFun, Dynamic)) type Signal = CInt type HandlerFun = ForeignPtr Word8 -> IO () -- | Make a Weak pointer to an MVar, using the second -- argument as a finalizer to run when MVar is garbage-collected mkWeakMVar :: () => MVar a -> IO () -> IO (Weak (MVar a)) addMVarFinalizer :: () => MVar a -> IO () -> IO () -- | Like modifyMVar, but the IO action in the second -- argument is executed with asynchronous exceptions masked. modifyMVarMasked :: () => MVar a -> (a -> IO (a, b)) -> IO b -- | Like modifyMVar_, but the IO action in the second -- argument is executed with asynchronous exceptions masked. modifyMVarMasked_ :: () => MVar a -> (a -> IO a) -> IO () -- | A slight variation on modifyMVar_ that allows a value to be -- returned (b) in addition to the modified value of the -- MVar. modifyMVar :: () => MVar a -> (a -> IO (a, b)) -> IO b -- | An exception-safe wrapper for modifying the contents of an -- MVar. Like withMVar, modifyMVar will replace the -- original contents of the MVar if an exception is raised during -- the operation. This function is only atomic if there are no other -- producers for this MVar. modifyMVar_ :: () => MVar a -> (a -> IO a) -> IO () -- | Like withMVar, but the IO action in the second -- argument is executed with asynchronous exceptions masked. withMVarMasked :: () => MVar a -> (a -> IO b) -> IO b -- | withMVar is an exception-safe wrapper for operating on the -- contents of an MVar. This operation is exception-safe: it will -- replace the original contents of the MVar if an exception is -- raised (see Control.Exception). However, it is only atomic if -- there are no other producers for this MVar. withMVar :: () => MVar a -> (a -> IO b) -> IO b -- | Take a value from an MVar, put a new value into the MVar -- and return the value taken. This function is atomic only if there are -- no other producers for this MVar. swapMVar :: () => MVar a -> a -> IO a -- | A slightly faster version of fixIO that may not be safe to use -- with multiple threads. The unsafety arises when used like this: -- --
-- unsafeFixIO $ \r -> do -- forkIO (print r) -- return (...) ---- -- In this case, the child thread will receive a NonTermination -- exception instead of waiting for the value of r to be -- computed. unsafeFixIO :: () => (a -> IO a) -> IO a -- | When invoked inside mask, this function allows a masked -- asynchronous exception to be raised, if one exists. It is equivalent -- to performing an interruptible operation (see #interruptible), but -- does not involve any actual blocking. -- -- When called outside mask, or inside uninterruptibleMask, -- this function has no effect. allowInterrupt :: IO () -- | 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 -- | Adds a location description and maybe a file path and file handle to -- an IOException. If any of the file handle or file path is not -- given the corresponding value in the IOException remains -- unaltered. annotateIOError :: IOError -> String -> Maybe Handle -> Maybe FilePath -> IOError -- | Catch any IOException that occurs in the computation and throw -- a modified version. modifyIOError :: () => (IOError -> IOError) -> IO a -> IO a ioeSetFileName :: IOError -> FilePath -> IOError ioeSetHandle :: IOError -> Handle -> IOError ioeSetLocation :: IOError -> String -> IOError ioeSetErrorString :: IOError -> String -> IOError ioeSetErrorType :: IOError -> IOErrorType -> IOError ioeGetFileName :: IOError -> Maybe FilePath ioeGetHandle :: IOError -> Maybe Handle ioeGetLocation :: IOError -> String ioeGetErrorString :: IOError -> String ioeGetErrorType :: IOError -> IOErrorType -- | I/O error that is programmer-defined. isUserErrorType :: IOErrorType -> Bool -- | I/O error where the operation failed because the user does not have -- sufficient operating system privilege to perform that operation. isPermissionErrorType :: IOErrorType -> Bool -- | I/O error where the operation is not possible. isIllegalOperationErrorType :: IOErrorType -> Bool -- | I/O error where the operation failed because the end of file has been -- reached. isEOFErrorType :: IOErrorType -> Bool -- | I/O error where the operation failed because the device is full. isFullErrorType :: IOErrorType -> Bool -- | I/O error where the operation failed because one of its arguments is a -- single-use resource, which is already being used. isAlreadyInUseErrorType :: IOErrorType -> Bool -- | I/O error where the operation failed because one of its arguments does -- not exist. isDoesNotExistErrorType :: IOErrorType -> Bool -- | I/O error where the operation failed because one of its arguments -- already exists. isAlreadyExistsErrorType :: IOErrorType -> Bool -- | I/O error that is programmer-defined. userErrorType :: IOErrorType -- | I/O error where the operation failed because the user does not have -- sufficient operating system privilege to perform that operation. permissionErrorType :: IOErrorType -- | I/O error where the operation is not possible. illegalOperationErrorType :: IOErrorType -- | I/O error where the operation failed because the end of file has been -- reached. eofErrorType :: IOErrorType -- | I/O error where the operation failed because the device is full. fullErrorType :: IOErrorType -- | I/O error where the operation failed because one of its arguments is a -- single-use resource, which is already being used. alreadyInUseErrorType :: IOErrorType -- | I/O error where the operation failed because one of its arguments does -- not exist. doesNotExistErrorType :: IOErrorType -- | I/O error where the operation failed because one of its arguments -- already exists. alreadyExistsErrorType :: IOErrorType -- | A programmer-defined error value constructed using userError. isUserError :: IOError -> Bool -- | An error indicating that an IO operation failed because the -- user does not have sufficient operating system privilege to perform -- that operation. isPermissionError :: IOError -> Bool -- | An error indicating that an IO operation failed because the -- operation was not possible. Any computation which returns an IO -- result may fail with isIllegalOperation. In some cases, an -- implementation will not be able to distinguish between the possible -- error causes. In this case it should fail with -- isIllegalOperation. isIllegalOperation :: IOError -> Bool -- | An error indicating that an IO operation failed because the end -- of file has been reached. isEOFError :: IOError -> Bool -- | An error indicating that an IO operation failed because the -- device is full. isFullError :: IOError -> Bool -- | An error indicating that an IO operation failed because one of -- its arguments is a single-use resource, which is already being used -- (for example, opening the same file twice for writing might give this -- error). isAlreadyInUseError :: IOError -> Bool -- | An error indicating that an IO operation failed because one of -- its arguments does not exist. isDoesNotExistError :: IOError -> Bool -- | An error indicating that an IO operation failed because one of -- its arguments already exists. isAlreadyExistsError :: IOError -> Bool -- | Construct an IOException of the given type where the second -- argument describes the error location and the third and fourth -- argument contain the file handle and file path of the file involved in -- the error if applicable. mkIOError :: IOErrorType -> String -> Maybe Handle -> Maybe FilePath -> IOError -- | The construct tryIOError comp exposes IO errors which -- occur within a computation, and which are not fully handled. -- -- Non-I/O exceptions are not caught by this variant; to catch all -- exceptions, use try from Control.Exception. tryIOError :: () => IO a -> IO (Either IOError a) -- | This function maps one exception into another as proposed in the paper -- "A semantics for imprecise exceptions". mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a -- | A pattern match failed. The String gives information about -- the source location of the pattern. newtype PatternMatchFail PatternMatchFail :: String -> PatternMatchFail -- | A record selector was applied to a constructor without the appropriate -- field. This can only happen with a datatype with multiple -- constructors, where some fields are in one constructor but not -- another. The String gives information about the source -- location of the record selector. newtype RecSelError RecSelError :: String -> RecSelError -- | An uninitialised record field was used. The String gives -- information about the source location where the record was -- constructed. newtype RecConError RecConError :: String -> RecConError -- | A record update was performed on a constructor without the appropriate -- field. This can only happen with a datatype with multiple -- constructors, where some fields are in one constructor but not -- another. The String gives information about the source -- location of the record update. newtype RecUpdError RecUpdError :: String -> RecUpdError -- | A class method without a definition (neither a default definition, nor -- a definition in the appropriate instance) was called. The -- String gives information about which method it was. newtype NoMethodError NoMethodError :: String -> NoMethodError -- | An expression that didn't typecheck during compile time was called. -- This is only possible with -fdefer-type-errors. The String -- gives details about the failed type check. newtype TypeError TypeError :: String -> TypeError -- | Thrown when the runtime system detects that the computation is -- guaranteed not to terminate. Note that there is no guarantee that the -- runtime system will notice whether any given computation is guaranteed -- to terminate or not. data NonTermination NonTermination :: NonTermination -- | Thrown when the program attempts to call atomically, from the -- stm package, inside another call to atomically. data NestedAtomically NestedAtomically :: NestedAtomically getUncaughtExceptionHandler :: IO (SomeException -> IO ()) setUncaughtExceptionHandler :: (SomeException -> IO ()) -> IO () reportError :: SomeException -> IO () reportStackOverflow :: IO () -- | Write the supplied value into a TVar. writeTVar :: () => TVar a -> a -> STM () -- | Return the current value stored in a TVar. readTVar :: () => TVar a -> STM a -- | Return the current value stored in a TVar. This is equivalent -- to -- --
-- readTVarIO = atomically . readTVar ---- -- but works much faster, because it doesn't perform a complete -- transaction, it just reads the current value of the TVar. readTVarIO :: () => TVar a -> IO a -- | IO version of newTVar. This is useful for creating -- top-level TVars using unsafePerformIO, because using -- atomically inside unsafePerformIO isn't possible. newTVarIO :: () => a -> IO (TVar a) -- | Create a new TVar holding a value supplied newTVar :: () => a -> STM (TVar a) -- | Exception handling within STM actions. catchSTM :: Exception e => STM a -> (e -> STM a) -> STM a -- | A variant of throw that can only be used within the STM -- monad. -- -- Throwing an exception in STM aborts the transaction and -- propagates the exception. -- -- Although throwSTM has a type that is an instance of the type of -- throw, the two functions are subtly different: -- --
-- throw e `seq` x ===> throw e -- throwSTM e `seq` x ===> x ---- -- The first example will cause the exception e to be raised, -- whereas the second one won't. In fact, throwSTM will only cause -- an exception to be raised when it is used within the STM monad. -- The throwSTM variant should be used in preference to -- throw to raise an exception within the STM monad because -- it guarantees ordering with respect to other STM operations, -- whereas throw does not. throwSTM :: Exception e => e -> STM a -- | Compose two alternative STM actions (GHC only). -- -- If the first action completes without retrying then it forms the -- result of the orElse. Otherwise, if the first action retries, -- then the second action is tried in its place. If both actions retry -- then the orElse as a whole retries. orElse :: () => STM a -> STM a -> STM a -- | Retry execution of the current memory transaction because it has seen -- values in TVars which mean that it should not continue (e.g. -- the TVars represent a shared buffer that is now empty). The -- implementation may block the thread until one of the TVars that -- it has read from has been updated. (GHC only) retry :: () => STM a -- | Perform a series of STM actions atomically. -- -- Using atomically inside an unsafePerformIO or -- unsafeInterleaveIO subverts some of guarantees that STM -- provides. It makes it possible to run a transaction inside of another -- transaction, depending on when the thunk is evaluated. If a nested -- transaction is attempted, an exception is thrown by the runtime. It is -- possible to safely use atomically inside unsafePerformIO -- or unsafeInterleaveIO, but the typechecker does not rule out -- programs that may attempt nested transactions, meaning that the -- programmer must take special care to prevent these. -- -- However, there are functions for creating transactional variables that -- can always be safely called in unsafePerformIO. See: -- newTVarIO, newTChanIO, newBroadcastTChanIO, -- newTQueueIO, newTBQueueIO, and newTMVarIO. -- -- Using unsafePerformIO inside of atomically is also -- dangerous but for different reasons. See unsafeIOToSTM for more -- on this. atomically :: () => STM a -> IO a -- | Unsafely performs IO in the STM monad. Beware: this is a highly -- dangerous thing to do. -- --
-- killThread tid = throwTo tid ThreadKilled --killThread :: ThreadId -> IO () childHandler :: SomeException -> IO () -- | Returns the number of sparks currently in the local spark pool numSparks :: IO Int -- | Returns the number of CPUs that the machine has getNumProcessors :: IO Int -- | Set the number of Haskell threads that can run truly simultaneously -- (on separate physical processors) at any given time. The number passed -- to forkOn is interpreted modulo this value. The initial value -- is given by the +RTS -N runtime flag. -- -- This is also the number of threads that will participate in parallel -- garbage collection. It is strongly recommended that the number of -- capabilities is not set larger than the number of physical processor -- cores, and it may often be beneficial to leave one or more cores free -- to avoid contention with other processes in the machine. setNumCapabilities :: Int -> IO () -- | Returns the number of Haskell threads that can run truly -- simultaneously (on separate physical processors) at any given time. To -- change this value, use setNumCapabilities. getNumCapabilities :: IO Int -- | the value passed to the +RTS -N flag. This is the number of -- Haskell threads that can run truly simultaneously at any given time, -- and is typically set to the number of physical processor cores on the -- machine. -- -- Strictly speaking it is better to use getNumCapabilities, -- because the number of capabilities might vary at runtime. numCapabilities :: Int -- | Like forkIOWithUnmask, but the child thread is pinned to the -- given CPU, as with forkOn. forkOnWithUnmask :: Int -> ((forall a. () => IO a -> IO a) -> IO ()) -> IO ThreadId -- | Like forkIO, but lets you specify on which capability the -- thread should run. Unlike a forkIO thread, a thread created by -- forkOn will stay on the same capability for its entire lifetime -- (forkIO threads can migrate between capabilities according to -- the scheduling policy). forkOn is useful for overriding the -- scheduling policy when you know in advance how best to distribute the -- threads. -- -- The Int argument specifies a capability number (see -- getNumCapabilities). Typically capabilities correspond to -- physical processors, but the exact behaviour is -- implementation-dependent. The value passed to forkOn is -- interpreted modulo the total number of capabilities as returned by -- getNumCapabilities. -- -- GHC note: the number of capabilities is specified by the +RTS -- -N option when the program is started. Capabilities can be fixed -- to actual processor cores with +RTS -qa if the underlying -- operating system supports that, although in practice this is usually -- unnecessary (and may actually degrade performance in some cases - -- experimentation is recommended). forkOn :: Int -> IO () -> IO ThreadId -- | Like forkIO, but the child thread is passed a function that can -- be used to unmask asynchronous exceptions. This function is typically -- used in the following way -- --
-- ... mask_ $ forkIOWithUnmask $ \unmask -> -- catch (unmask ...) handler ---- -- so that the exception handler in the child thread is established with -- asynchronous exceptions masked, meanwhile the main body of the child -- thread is executed in the unmasked state. -- -- Note that the unmask function passed to the child thread should only -- be used in that thread; the behaviour is undefined if it is invoked in -- a different thread. forkIOWithUnmask :: ((forall a. () => IO a -> IO a) -> IO ()) -> IO ThreadId -- | Creates a new thread to run the IO computation passed as the -- first argument, and returns the ThreadId of the newly created -- thread. -- -- The new thread will be a lightweight, unbound thread. Foreign -- calls made by this thread are not guaranteed to be made by any -- particular OS thread; if you need foreign calls to be made by a -- particular OS thread, then use forkOS instead. -- -- The new thread inherits the masked state of the parent (see -- mask). -- -- The newly created thread has an exception handler that discards the -- exceptions BlockedIndefinitelyOnMVar, -- BlockedIndefinitelyOnSTM, and ThreadKilled, and passes -- all other exceptions to the uncaught exception handler. forkIO :: IO () -> IO ThreadId -- | Disable allocation limit processing for the current thread. disableAllocationLimit :: IO () -- | Enables the allocation counter to be treated as a limit for the -- current thread. When the allocation limit is enabled, if the -- allocation counter counts down below zero, the thread will be sent the -- AllocationLimitExceeded asynchronous exception. When this -- happens, the counter is reinitialised (by default to 100K, but tunable -- with the +RTS -xq option) so that it can handle the exception -- and perform any necessary clean up. If it exhausts this additional -- allowance, another AllocationLimitExceeded exception is sent, -- and so forth. Like other asynchronous exceptions, the -- AllocationLimitExceeded exception is deferred while the thread -- is inside mask or an exception handler in catch. -- -- Note that memory allocation is unrelated to live memory, also -- known as heap residency. A thread can allocate a large amount -- of memory and retain anything between none and all of it. It is better -- to think of the allocation limit as a limit on CPU time, rather -- than a limit on memory. -- -- Compared to using timeouts, allocation limits don't count time spent -- blocked or in foreign calls. enableAllocationLimit :: IO () -- | Return the current value of the allocation counter for the current -- thread. getAllocationCounter :: IO Int64 -- | Every thread has an allocation counter that tracks how much memory has -- been allocated by the thread. The counter is initialized to zero, and -- setAllocationCounter sets the current value. The allocation -- counter counts *down*, so in the absence of a call to -- setAllocationCounter its value is the negation of the number of -- bytes of memory allocated by the thread. -- -- There are two things that you can do with this counter: -- --
-- ref <- newIORef '1'
-- forever $ atomicModifyIORef ref (\_ -> ('2', ()))
--
--
-- Use atomicModifyIORef' or atomicWriteIORef to avoid this
-- problem.
atomicModifyIORef :: () => IORef a -> (a -> (a, b)) -> IO b
-- | Strict version of modifyIORef
modifyIORef' :: () => IORef a -> (a -> a) -> IO ()
-- | Mutate the contents of an IORef.
--
-- Be warned that modifyIORef does not apply the function
-- strictly. This means if the program calls modifyIORef many
-- times, but seldomly uses the value, thunks will pile up in memory
-- resulting in a space leak. This is a common mistake made when using an
-- IORef as a counter. For example, the following will likely produce a
-- stack overflow:
--
-- -- ref <- newIORef 0 -- replicateM_ 1000000 $ modifyIORef ref (+1) -- readIORef ref >>= print ---- -- To avoid this problem, use modifyIORef' instead. modifyIORef :: () => IORef a -> (a -> a) -> IO () -- | Make a Weak pointer to an IORef, using the second -- argument as a finalizer to run when IORef is garbage-collected mkWeakIORef :: () => IORef a -> IO () -> IO (Weak (IORef a)) -- | This function is similar to mallocArray0, but yields a memory -- area that has a finalizer attached that releases the memory area. As -- with mallocForeignPtr, it is not guaranteed that the block of -- memory was allocated by malloc. mallocForeignPtrArray0 :: Storable a => Int -> IO (ForeignPtr a) -- | This function is similar to mallocArray, but yields a memory -- area that has a finalizer attached that releases the memory area. As -- with mallocForeignPtr, it is not guaranteed that the block of -- memory was allocated by malloc. mallocForeignPtrArray :: Storable a => Int -> IO (ForeignPtr a) -- | This variant of newForeignPtr adds a finalizer that expects an -- environment in addition to the finalized pointer. The environment that -- will be passed to the finalizer is fixed by the second argument to -- newForeignPtrEnv. newForeignPtrEnv :: () => FinalizerEnvPtr env a -> Ptr env -> Ptr a -> IO (ForeignPtr a) -- | This is a way to look at the pointer living inside a foreign object. -- This function takes a function which is applied to that pointer. The -- resulting IO action is then executed. The foreign object is -- kept alive at least during the whole action, even if it is not used -- directly inside. Note that it is not safe to return the pointer from -- the action and use it after the action completes. All uses of the -- pointer should be inside the withForeignPtr bracket. The reason -- for this unsafeness is the same as for unsafeForeignPtrToPtr -- below: the finalizer may run earlier than expected, because the -- compiler can only track usage of the ForeignPtr object, not a -- Ptr object made from it. -- -- This function is normally used for marshalling data to or from the -- object pointed to by the ForeignPtr, using the operations from -- the Storable class. withForeignPtr :: () => ForeignPtr a -> (Ptr a -> IO b) -> IO b -- | Turns a plain memory reference into a foreign pointer, and associates -- a finalizer with the reference. The finalizer will be executed after -- the last reference to the foreign object is dropped. There is no -- guarantee of promptness, however the finalizer will be executed before -- the program exits. newForeignPtr :: () => FinalizerPtr a -> Ptr a -> IO (ForeignPtr a) -- | Causes the finalizers associated with a foreign pointer to be run -- immediately. finalizeForeignPtr :: () => ForeignPtr a -> IO () -- | Advances the given address by the given offset in bytes. -- -- The new ForeignPtr shares the finalizer of the original, -- equivalent from a finalization standpoint to just creating another -- reference to the original. That is, the finalizer will not be called -- before the new ForeignPtr is unreachable, nor will it be called -- an additional time due to this call, and the finalizer will be called -- with the same address that it would have had this call not happened, -- *not* the new address. plusForeignPtr :: () => ForeignPtr a -> Int -> ForeignPtr b -- | This function casts a ForeignPtr parameterised by one type into -- another type. castForeignPtr :: () => ForeignPtr a -> ForeignPtr b -- | This function ensures that the foreign object in question is alive at -- the given place in the sequence of IO actions. In particular -- withForeignPtr does a touchForeignPtr after it executes -- the user action. -- -- Note that this function should not be used to express dependencies -- between finalizers on ForeignPtrs. For example, if the -- finalizer for a ForeignPtr F1 calls -- touchForeignPtr on a second ForeignPtr F2, then -- the only guarantee is that the finalizer for F2 is never -- started before the finalizer for F1. They might be started -- together if for example both F1 and F2 are otherwise -- unreachable, and in that case the scheduler might end up running the -- finalizer for F2 first. -- -- In general, it is not recommended to use finalizers on separate -- objects with ordering constraints between them. To express the -- ordering robustly requires explicit synchronisation using -- MVars between the finalizers, but even then the runtime -- sometimes runs multiple finalizers sequentially in a single thread -- (for performance reasons), so synchronisation between finalizers could -- result in artificial deadlock. Another alternative is to use explicit -- reference counting. touchForeignPtr :: () => ForeignPtr a -> IO () -- | Turns a plain memory reference into a foreign pointer that may be -- associated with finalizers by using addForeignPtrFinalizer. newForeignPtr_ :: () => Ptr a -> IO (ForeignPtr a) -- | Like addForeignPtrFinalizerEnv but allows the finalizer to be -- passed an additional environment parameter to be passed to the -- finalizer. The environment passed to the finalizer is fixed by the -- second argument to addForeignPtrFinalizerEnv addForeignPtrFinalizerEnv :: () => FinalizerEnvPtr env a -> Ptr env -> ForeignPtr a -> IO () -- | This function adds a finalizer to the given foreign object. The -- finalizer will run before all other finalizers for the same -- object which have already been registered. addForeignPtrFinalizer :: () => FinalizerPtr a -> ForeignPtr a -> IO () -- | This function is similar to mallocForeignPtr, except that the -- size of the memory required is given explicitly as a number of bytes. mallocForeignPtrBytes :: () => Int -> IO (ForeignPtr a) -- | Allocate some memory and return a ForeignPtr to it. The memory -- will be released automatically when the ForeignPtr is -- discarded. -- -- mallocForeignPtr is equivalent to -- --
-- do { p <- malloc; newForeignPtr finalizerFree p }
--
--
-- although it may be implemented differently internally: you may not
-- assume that the memory returned by mallocForeignPtr has been
-- allocated with malloc.
--
-- GHC notes: mallocForeignPtr has a heavily optimised
-- implementation in GHC. It uses pinned memory in the garbage collected
-- heap, so the ForeignPtr does not require a finalizer to free
-- the memory. Use of mallocForeignPtr and associated functions is
-- strongly recommended in preference to newForeignPtr with a
-- finalizer.
mallocForeignPtr :: Storable a => IO (ForeignPtr a)
-- | A finalizer is represented as a pointer to a foreign function that, at
-- finalisation time, gets as an argument a plain pointer variant of the
-- foreign pointer that the finalizer is associated with.
--
-- Note that the foreign function must use the ccall
-- calling convention.
type FinalizerPtr a = FunPtr Ptr a -> IO ()
type FinalizerEnvPtr env a = FunPtr Ptr env -> Ptr a -> IO ()
-- | Write a new value into an IORef
writeIORef :: () => IORef a -> a -> IO ()
-- | Read the value of an IORef
readIORef :: () => IORef a -> IO a
-- | Build a new IORef
newIORef :: () => a -> IO (IORef a)
-- | A mutable variable in the IO monad
data IORef a
-- | Evaluate the argument to weak head normal form.
--
-- evaluate is typically used to uncover any exceptions that a
-- lazy value may contain, and possibly handle them.
--
-- evaluate only evaluates to weak head normal form. If
-- deeper evaluation is needed, the force function from
-- Control.DeepSeq may be handy:
--
-- -- evaluate $ force x ---- -- There is a subtle difference between evaluate x and -- return $! x, analogous to the difference -- between throwIO and throw. If the lazy value x -- throws an exception, return $! x will fail to -- return an IO action and will throw an exception instead. -- evaluate x, on the other hand, always produces an -- IO action; that action will throw an exception upon -- execution iff x throws an exception upon -- evaluation. -- -- The practical implication of this difference is that due to the -- imprecise exceptions semantics, -- --
-- (return $! error "foo") >> error "bar" ---- -- may throw either "foo" or "bar", depending on the -- optimizations performed by the compiler. On the other hand, -- --
-- evaluate (error "foo") >> error "bar" ---- -- is guaranteed to throw "foo". -- -- The rule of thumb is to use evaluate to force or handle -- exceptions in lazy values. If, on the other hand, you are forcing a -- lazy value for efficiency reasons only and do not care about -- exceptions, you may use return $! x. evaluate :: () => a -> IO a -- | Returns the MaskingState for the current thread. getMaskingState :: IO MaskingState -- | Allow asynchronous exceptions to be raised even inside mask, -- making the operation interruptible (see the discussion of -- "Interruptible operations" in Exception). -- -- When called outside mask, or inside uninterruptibleMask, -- this function has no effect. interruptible :: () => IO a -> IO a -- | A variant of throw that can only be used within the IO -- monad. -- -- Although throwIO has a type that is an instance of the type of -- throw, the two functions are subtly different: -- --
-- throw e `seq` x ===> throw e -- throwIO e `seq` x ===> x ---- -- The first example will cause the exception e to be raised, -- whereas the second one won't. In fact, throwIO will only cause -- an exception to be raised when it is used within the IO monad. -- The throwIO variant should be used in preference to -- throw to raise an exception within the IO monad because -- it guarantees ordering with respect to other IO operations, -- whereas throw does not. throwIO :: Exception e => e -> IO a -- | Embed a strict state transformer in an IO action. The -- RealWorld parameter indicates that the internal state used by -- the ST computation is a special one supplied by the IO -- monad, and thus distinct from those used by invocations of -- runST. stToIO :: () => ST RealWorld a -> IO a -- | File and directory names are values of type String, whose -- precise meaning is operating system dependent. Files can be opened, -- yielding a handle which can then be used to operate on the contents of -- that file. type FilePath = String -- | Describes the behaviour of a thread when an asynchronous exception is -- received. data MaskingState -- | asynchronous exceptions are unmasked (the normal state) Unmasked :: MaskingState -- | the state during mask: asynchronous exceptions are masked, but -- blocking operations may still be interrupted MaskedInterruptible :: MaskingState -- | the state during uninterruptibleMask: asynchronous exceptions -- are masked, and blocking operations may not be interrupted MaskedUninterruptible :: MaskingState -- | Construct an IOException value with a string describing the -- error. The fail method of the IO instance of the -- Monad class raises a userError, thus: -- --
-- instance Monad IO where -- ... -- fail s = ioError (userError s) --userError :: String -> IOError -- | Exceptions that occur in the IO monad. An -- IOException records a more specific error type, a descriptive -- string and maybe the handle that was used when the error was flagged. data IOException IOError :: Maybe Handle -> IOErrorType -> String -> String -> Maybe CInt -> Maybe FilePath -> IOException [ioe_handle] :: IOException -> Maybe Handle [ioe_type] :: IOException -> IOErrorType [ioe_location] :: IOException -> String [ioe_description] :: IOException -> String [ioe_errno] :: IOException -> Maybe CInt [ioe_filename] :: IOException -> Maybe FilePath -- | The Haskell 2010 type for exceptions in the IO monad. Any I/O -- operation may raise an IOException instead of returning a -- result. For a more general type of exception, including also those -- that arise in pure code, see Exception. -- -- In Haskell 2010, this is an opaque type. type IOError = IOException -- | Throw an exception. Exceptions may be thrown from purely functional -- code, but may only be caught within the IO monad. throw :: Exception e => e -> a -- | This is thrown when the user calls error. The first -- String is the argument given to error, second -- String is the location. data ErrorCall ErrorCallWithLocation :: String -> String -> ErrorCall -- | Any type that you wish to throw or catch as an exception must be an -- instance of the Exception class. The simplest case is a new -- exception type directly below the root: -- --
-- data MyException = ThisException | ThatException -- deriving Show -- -- instance Exception MyException ---- -- The default method definitions in the Exception class do what -- we need in this case. You can now throw and catch -- ThisException and ThatException as exceptions: -- --
-- *Main> throw ThisException `catch` \e -> putStrLn ("Caught " ++ show (e :: MyException))
-- Caught ThisException
--
--
-- In more complicated examples, you may wish to define a whole hierarchy
-- of exceptions:
--
-- -- --------------------------------------------------------------------- -- -- Make the root exception type for all the exceptions in a compiler -- -- data SomeCompilerException = forall e . Exception e => SomeCompilerException e -- -- instance Show SomeCompilerException where -- show (SomeCompilerException e) = show e -- -- instance Exception SomeCompilerException -- -- compilerExceptionToException :: Exception e => e -> SomeException -- compilerExceptionToException = toException . SomeCompilerException -- -- compilerExceptionFromException :: Exception e => SomeException -> Maybe e -- compilerExceptionFromException x = do -- SomeCompilerException a <- fromException x -- cast a -- -- --------------------------------------------------------------------- -- -- Make a subhierarchy for exceptions in the frontend of the compiler -- -- data SomeFrontendException = forall e . Exception e => SomeFrontendException e -- -- instance Show SomeFrontendException where -- show (SomeFrontendException e) = show e -- -- instance Exception SomeFrontendException where -- toException = compilerExceptionToException -- fromException = compilerExceptionFromException -- -- frontendExceptionToException :: Exception e => e -> SomeException -- frontendExceptionToException = toException . SomeFrontendException -- -- frontendExceptionFromException :: Exception e => SomeException -> Maybe e -- frontendExceptionFromException x = do -- SomeFrontendException a <- fromException x -- cast a -- -- --------------------------------------------------------------------- -- -- Make an exception type for a particular frontend compiler exception -- -- data MismatchedParentheses = MismatchedParentheses -- deriving Show -- -- instance Exception MismatchedParentheses where -- toException = frontendExceptionToException -- fromException = frontendExceptionFromException ---- -- We can now catch a MismatchedParentheses exception as -- MismatchedParentheses, SomeFrontendException or -- SomeCompilerException, but not other types, e.g. -- IOException: -- --
-- *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: MismatchedParentheses))
-- Caught MismatchedParentheses
-- *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeFrontendException))
-- Caught MismatchedParentheses
-- *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeCompilerException))
-- Caught MismatchedParentheses
-- *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: IOException))
-- *** Exception: MismatchedParentheses
--
class (Typeable e, Show e) => Exception e
toException :: Exception e => e -> SomeException
fromException :: Exception e => SomeException -> Maybe e
-- | Render this exception value in a human-friendly manner.
--
-- Default implementation: show.
displayException :: Exception e => e -> String
-- | Arithmetic exceptions.
data ArithException
Overflow :: ArithException
Underflow :: ArithException
LossOfPrecision :: ArithException
DivideByZero :: ArithException
Denormal :: ArithException
RatioZeroDenominator :: ArithException
typeOf7 :: Typeable t => t a b c d e f g -> TypeRep
typeOf6 :: Typeable t => t a b c d e f -> TypeRep
typeOf5 :: Typeable t => t a b c d e -> TypeRep
typeOf4 :: Typeable t => t a b c d -> TypeRep
typeOf3 :: Typeable t => t a b c -> TypeRep
typeOf2 :: Typeable t => t a b -> TypeRep
typeOf1 :: Typeable t => t a -> TypeRep
-- | Force a TypeRep to normal form.
rnfTypeRep :: TypeRep -> ()
-- | Takes a value of type a and returns a concrete representation
-- of that type.
typeRepFingerprint :: TypeRep -> Fingerprint
-- | Observe the type constructor of a quantified type representation.
typeRepTyCon :: TypeRep -> TyCon
-- | Observe the argument types of a type representation
typeRepArgs :: TypeRep -> [TypeRep]
-- | Splits a type constructor application. Note that if the type
-- constructor is polymorphic, this will not return the kinds that were
-- used.
splitTyConApp :: TypeRep -> (TyCon, [TypeRep])
-- | Build a function type.
mkFunTy :: TypeRep -> TypeRep -> TypeRep
-- | Applies a type to a function type. Returns: Just u if the
-- first argument represents a function of type t -> u and
-- the second argument represents a function of type t.
-- Otherwise, returns Nothing.
funResultTy :: TypeRep -> TypeRep -> Maybe TypeRep
-- | Cast over k1 -> k2 -> k3
gcast2 :: (Typeable t, Typeable t') => c (t a b) -> Maybe (c (t' a b))
-- | Cast over k1 -> k2
gcast1 :: (Typeable t, Typeable t') => c (t a) -> Maybe (c (t' a))
-- | A flexible variation parameterised in a type constructor
gcast :: (Typeable a, Typeable b) => c a -> Maybe (c b)
-- | Extract a witness of equality of two types
eqT :: (Typeable a, Typeable b) => Maybe (a :~: b)
-- | The type-safe cast operation
cast :: (Typeable a, Typeable b) => a -> Maybe b
-- | Show a type representation
showsTypeRep :: TypeRep -> ShowS
-- | Takes a value of type a and returns a concrete representation
-- of that type.
typeRep :: Typeable a => proxy a -> TypeRep
-- | Observe a type representation for the type of a value.
typeOf :: Typeable a => a -> TypeRep
-- | A quantified type representation.
type TypeRep = SomeTypeRep
rnfTyCon :: TyCon -> ()
tyConFingerprint :: TyCon -> Fingerprint
tyConName :: TyCon -> String
tyConModule :: TyCon -> String
tyConPackage :: TyCon -> String
-- | The Const functor.
newtype Const a (b :: k) :: forall k. () => Type -> k -> Type
Const :: a -> Const a
[getConst] :: Const a -> a
-- | The find function takes a predicate and a structure and returns
-- the leftmost element of the structure matching the predicate, or
-- Nothing if there is no such element.
find :: Foldable t => (a -> Bool) -> t a -> Maybe a
-- | notElem is the negation of elem.
notElem :: (Foldable t, Eq a) => a -> t a -> Bool
infix 4 `notElem`
-- | The least element of a non-empty structure with respect to the given
-- comparison function.
minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
-- | The largest element of a non-empty structure with respect to the given
-- comparison function.
maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
-- | Determines whether all elements of the structure satisfy the
-- predicate.
all :: Foldable t => (a -> Bool) -> t a -> Bool
-- | Determines whether any element of the structure satisfies the
-- predicate.
any :: Foldable t => (a -> Bool) -> t a -> Bool
-- | or returns the disjunction of a container of Bools. For the
-- result to be False, the container must be finite; True,
-- however, results from a True value finitely far from the left
-- end.
or :: Foldable t => t Bool -> Bool
-- | and returns the conjunction of a container of Bools. For the
-- result to be True, the container must be finite; False,
-- however, results from a False value finitely far from the left
-- end.
and :: Foldable t => t Bool -> Bool
-- | Map a function over all the elements of a container and concatenate
-- the resulting lists.
concatMap :: Foldable t => (a -> [b]) -> t a -> [b]
-- | The concatenation of all the elements of a container of lists.
concat :: Foldable t => t [a] -> [a]
-- | The sum of a collection of actions, generalizing concat. As of
-- base 4.8.0.0, msum is just asum, specialized to
-- MonadPlus.
msum :: (Foldable t, MonadPlus m) => t (m a) -> m a
-- | The sum of a collection of actions, generalizing concat.
--
-- asum [Just Hello, Nothing, Just World] Just Hello
asum :: (Foldable t, Alternative f) => t (f a) -> f a
-- | Evaluate each monadic action in the structure from left to right, and
-- ignore the results. For a version that doesn't ignore the results see
-- sequence.
--
-- As of base 4.8.0.0, sequence_ is just sequenceA_,
-- specialized to Monad.
sequence_ :: (Foldable t, Monad m) => t (m a) -> m ()
-- | Evaluate each action in the structure from left to right, and ignore
-- the results. For a version that doesn't ignore the results see
-- sequenceA.
sequenceA_ :: (Foldable t, Applicative f) => t (f a) -> f ()
-- | forM_ is mapM_ with its arguments flipped. For a version
-- that doesn't ignore the results see forM.
--
-- As of base 4.8.0.0, forM_ is just for_, specialized to
-- Monad.
forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m ()
-- | Map each element of a structure to a monadic action, evaluate these
-- actions from left to right, and ignore the results. For a version that
-- doesn't ignore the results see mapM.
--
-- As of base 4.8.0.0, mapM_ is just traverse_, specialized
-- to Monad.
mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()
-- | for_ is traverse_ with its arguments flipped. For a
-- version that doesn't ignore the results see for.
--
-- -- >>> for_ [1..4] print -- 1 -- 2 -- 3 -- 4 --for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f () -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and ignore the results. For a version that doesn't -- ignore the results see traverse. traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f () -- | Monadic fold over the elements of a structure, associating to the -- left, i.e. from left to right. foldlM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | Monadic fold over the elements of a structure, associating to the -- right, i.e. from right to left. foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b -- | Maybe monoid returning the leftmost non-Nothing value. -- -- First a is isomorphic to Alt Maybe -- a, but precedes it historically. -- --
-- >>> getFirst (First (Just "hello") <> First Nothing <> First (Just "world")) -- Just "hello" ---- -- Use of this type is discouraged. Note the following equivalence: -- --
-- Data.Monoid.First x === Maybe (Data.Semigroup.First x) ---- -- In addition to being equivalent in the structural sense, the two also -- have Monoid instances that behave the same. This type will be -- marked deprecated in GHC 8.8, and removed in GHC 8.10. Users are -- advised to use the variant from Data.Semigroup and wrap it in -- Maybe. newtype First a First :: Maybe a -> First a [getFirst] :: First a -> Maybe a -- | Maybe monoid returning the rightmost non-Nothing value. -- -- Last a is isomorphic to Dual (First -- a), and thus to Dual (Alt Maybe a) -- --
-- >>> getLast (Last (Just "hello") <> Last Nothing <> Last (Just "world")) -- Just "world" ---- -- Use of this type is discouraged. Note the following equivalence: -- --
-- Data.Monoid.Last x === Maybe (Data.Semigroup.Last x) ---- -- In addition to being equivalent in the structural sense, the two also -- have Monoid instances that behave the same. This type will be -- marked deprecated in GHC 8.8, and removed in GHC 8.10. Users are -- advised to use the variant from Data.Semigroup and wrap it in -- Maybe. newtype Last a Last :: Maybe a -> Last a [getLast] :: Last a -> Maybe a -- | This data type witnesses the lifting of a Monoid into an -- Applicative pointwise. newtype Ap (f :: k -> Type) (a :: k) :: forall k. () => k -> Type -> k -> Type Ap :: f a -> Ap [getAp] :: Ap -> f a -- | The dual of a Monoid, obtained by swapping the arguments of -- mappend. -- --
-- >>> getDual (mappend (Dual "Hello") (Dual "World")) -- "WorldHello" --newtype Dual a Dual :: a -> Dual a [getDual] :: Dual a -> a -- | The monoid of endomorphisms under composition. -- --
-- >>> let computation = Endo ("Hello, " ++) <> Endo (++ "!")
--
-- >>> appEndo computation "Haskell"
-- "Hello, Haskell!"
--
newtype Endo a
Endo :: (a -> a) -> Endo a
[appEndo] :: Endo a -> a -> a
-- | Boolean monoid under conjunction (&&).
--
-- -- >>> getAll (All True <> mempty <> All False) -- False ---- --
-- >>> getAll (mconcat (map (\x -> All (even x)) [2,4,6,7,8])) -- False --newtype All All :: Bool -> All [getAll] :: All -> Bool -- | Boolean monoid under disjunction (||). -- --
-- >>> getAny (Any True <> mempty <> Any False) -- True ---- --
-- >>> getAny (mconcat (map (\x -> Any (even x)) [2,4,6,7,8])) -- True --newtype Any Any :: Bool -> Any [getAny] :: Any -> Bool -- | Monoid under addition. -- --
-- >>> getSum (Sum 1 <> Sum 2 <> mempty) -- 3 --newtype Sum a Sum :: a -> Sum a [getSum] :: Sum a -> a -- | Monoid under multiplication. -- --
-- >>> getProduct (Product 3 <> Product 4 <> mempty) -- 12 --newtype Product a Product :: a -> Product a [getProduct] :: Product a -> a -- | Monoid under <|>. newtype Alt (f :: k -> Type) (a :: k) :: forall k. () => k -> Type -> k -> Type Alt :: f a -> Alt [getAlt] :: Alt -> f a unsafeCoerce :: () => a -> b -- | unwords is an inverse operation to words. It joins words -- with separating spaces. -- --
-- >>> unwords ["Lorem", "ipsum", "dolor"] -- "Lorem ipsum dolor" --unwords :: [String] -> String -- | words breaks a string up into a list of words, which were -- delimited by white space. -- --
-- >>> words "Lorem ipsum\ndolor" -- ["Lorem","ipsum","dolor"] --words :: String -> [String] -- | unlines is an inverse operation to lines. It joins -- lines, after appending a terminating newline to each. -- --
-- >>> unlines ["Hello", "World", "!"] -- "Hello\nWorld\n!\n" --unlines :: [String] -> String -- | lines breaks a string up into a list of strings at newline -- characters. The resulting strings do not contain newlines. -- -- Note that after splitting the string at newline characters, the last -- part of the string is considered a line even if it doesn't end with a -- newline. For example, -- --
-- >>> lines "" -- [] ---- --
-- >>> lines "\n" -- [""] ---- --
-- >>> lines "one" -- ["one"] ---- --
-- >>> lines "one\n" -- ["one"] ---- --
-- >>> lines "one\n\n" -- ["one",""] ---- --
-- >>> lines "one\ntwo" -- ["one","two"] ---- --
-- >>> lines "one\ntwo\n" -- ["one","two"] ---- -- Thus lines s contains at least as many elements as -- newlines in s. lines :: String -> [String] -- | The unfoldr function is a `dual' to foldr: while -- foldr reduces a list to a summary value, unfoldr builds -- a list from a seed value. The function takes the element and returns -- Nothing if it is done producing the list or returns Just -- (a,b), in which case, a is a prepended to the list -- and b is used as the next element in a recursive call. For -- example, -- --
-- iterate f == unfoldr (\x -> Just (x, f x)) ---- -- In some cases, unfoldr can undo a foldr operation: -- --
-- unfoldr f' (foldr f z xs) == xs ---- -- if the following holds: -- --
-- f' (f x y) = Just (x,y) -- f' z = Nothing ---- -- A simple use of unfoldr: -- --
-- >>> unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10 -- [10,9,8,7,6,5,4,3,2,1] --unfoldr :: () => (b -> Maybe (a, b)) -> b -> [a] -- | Sort a list by comparing the results of a key function applied to each -- element. sortOn f is equivalent to sortBy (comparing -- f), but has the performance advantage of only evaluating -- f once for each element in the input list. This is called the -- decorate-sort-undecorate paradigm, or Schwartzian transform. -- -- Elements are arranged from from lowest to highest, keeping duplicates -- in the order they appeared in the input. -- --
-- >>> sortOn fst [(2, "world"), (4, "!"), (1, "Hello")] -- [(1,"Hello"),(2,"world"),(4,"!")] --sortOn :: Ord b => (a -> b) -> [a] -> [a] -- | The sortBy function is the non-overloaded version of -- sort. -- --
-- >>> sortBy (\(a,_) (b,_) -> compare a b) [(2, "world"), (4, "!"), (1, "Hello")] -- [(1,"Hello"),(2,"world"),(4,"!")] --sortBy :: () => (a -> a -> Ordering) -> [a] -> [a] -- | The sort function implements a stable sorting algorithm. It is -- a special case of sortBy, which allows the programmer to supply -- their own comparison function. -- -- Elements are arranged from from lowest to highest, keeping duplicates -- in the order they appeared in the input. -- --
-- >>> sort [1,6,4,3,2,5] -- [1,2,3,4,5,6] --sort :: Ord a => [a] -> [a] -- | The permutations function returns the list of all permutations -- of the argument. -- --
-- >>> permutations "abc" -- ["abc","bac","cba","bca","cab","acb"] --permutations :: () => [a] -> [[a]] -- | The subsequences function returns the list of all subsequences -- of the argument. -- --
-- >>> subsequences "abc" -- ["","a","b","ab","c","ac","bc","abc"] --subsequences :: () => [a] -> [[a]] -- | The tails function returns all final segments of the argument, -- longest first. For example, -- --
-- >>> tails "abc" -- ["abc","bc","c",""] ---- -- Note that tails has the following strictness property: -- tails _|_ = _|_ : _|_ tails :: () => [a] -> [[a]] -- | The inits function returns all initial segments of the -- argument, shortest first. For example, -- --
-- >>> inits "abc" -- ["","a","ab","abc"] ---- -- Note that inits has the following strictness property: -- inits (xs ++ _|_) = inits xs ++ _|_ -- -- In particular, inits _|_ = [] : _|_ inits :: () => [a] -> [[a]] -- | The groupBy function is the non-overloaded version of -- group. groupBy :: () => (a -> a -> Bool) -> [a] -> [[a]] -- | The group function takes a list and returns a list of lists -- such that the concatenation of the result is equal to the argument. -- Moreover, each sublist in the result contains only equal elements. For -- example, -- --
-- >>> group "Mississippi" -- ["M","i","ss","i","ss","i","pp","i"] ---- -- It is a special case of groupBy, which allows the programmer to -- supply their own equality test. group :: Eq a => [a] -> [[a]] -- | The deleteFirstsBy function takes a predicate and two lists and -- returns the first list with the first occurrence of each element of -- the second list removed. deleteFirstsBy :: () => (a -> a -> Bool) -> [a] -> [a] -> [a] -- | The unzip7 function takes a list of seven-tuples and returns -- seven lists, analogous to unzip. unzip7 :: () => [(a, b, c, d, e, f, g)] -> ([a], [b], [c], [d], [e], [f], [g]) -- | The unzip6 function takes a list of six-tuples and returns six -- lists, analogous to unzip. unzip6 :: () => [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f]) -- | The unzip5 function takes a list of five-tuples and returns -- five lists, analogous to unzip. unzip5 :: () => [(a, b, c, d, e)] -> ([a], [b], [c], [d], [e]) -- | The unzip4 function takes a list of quadruples and returns four -- lists, analogous to unzip. unzip4 :: () => [(a, b, c, d)] -> ([a], [b], [c], [d]) -- | The zipWith7 function takes a function which combines seven -- elements, as well as seven lists and returns a list of their -- point-wise combination, analogous to zipWith. zipWith7 :: () => (a -> b -> c -> d -> e -> f -> g -> h) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [h] -- | The zipWith6 function takes a function which combines six -- elements, as well as six lists and returns a list of their point-wise -- combination, analogous to zipWith. zipWith6 :: () => (a -> b -> c -> d -> e -> f -> g) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -- | The zipWith5 function takes a function which combines five -- elements, as well as five lists and returns a list of their point-wise -- combination, analogous to zipWith. zipWith5 :: () => (a -> b -> c -> d -> e -> f) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -- | The zipWith4 function takes a function which combines four -- elements, as well as four lists and returns a list of their point-wise -- combination, analogous to zipWith. zipWith4 :: () => (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e] -- | The zip7 function takes seven lists and returns a list of -- seven-tuples, analogous to zip. zip7 :: () => [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a, b, c, d, e, f, g)] -- | The zip6 function takes six lists and returns a list of -- six-tuples, analogous to zip. zip6 :: () => [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a, b, c, d, e, f)] -- | The zip5 function takes five lists and returns a list of -- five-tuples, analogous to zip. zip5 :: () => [a] -> [b] -> [c] -> [d] -> [e] -> [(a, b, c, d, e)] -- | The zip4 function takes four lists and returns a list of -- quadruples, analogous to zip. zip4 :: () => [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)] -- | The genericReplicate function is an overloaded version of -- replicate, which accepts any Integral value as the -- number of repetitions to make. genericReplicate :: Integral i => i -> a -> [a] -- | The genericIndex function is an overloaded version of -- !!, which accepts any Integral value as the index. genericIndex :: Integral i => [a] -> i -> a -- | The genericSplitAt function is an overloaded version of -- splitAt, which accepts any Integral value as the -- position at which to split. genericSplitAt :: Integral i => i -> [a] -> ([a], [a]) -- | The genericDrop function is an overloaded version of -- drop, which accepts any Integral value as the number of -- elements to drop. genericDrop :: Integral i => i -> [a] -> [a] -- | The genericTake function is an overloaded version of -- take, which accepts any Integral value as the number of -- elements to take. genericTake :: Integral i => i -> [a] -> [a] -- | The genericLength function is an overloaded version of -- length. In particular, instead of returning an Int, it -- returns any type which is an instance of Num. It is, however, -- less efficient than length. genericLength :: Num i => [a] -> i -- | The non-overloaded version of insert. insertBy :: () => (a -> a -> Ordering) -> a -> [a] -> [a] -- | The insert function takes an element and a list and inserts the -- element into the list at the first position where it is less than or -- equal to the next element. In particular, if the list is sorted before -- the call, the result will also be sorted. It is a special case of -- insertBy, which allows the programmer to supply their own -- comparison function. -- --
-- >>> insert 4 [1,2,3,5,6,7] -- [1,2,3,4,5,6,7] --insert :: Ord a => a -> [a] -> [a] -- | The partition function takes a predicate a list and returns the -- pair of lists of elements which do and do not satisfy the predicate, -- respectively; i.e., -- --
-- partition p xs == (filter p xs, filter (not . p) xs) ---- --
-- >>> partition (`elem` "aeiou") "Hello World!"
-- ("eoo","Hll Wrld!")
--
partition :: () => (a -> Bool) -> [a] -> ([a], [a])
-- | The transpose function transposes the rows and columns of its
-- argument. For example,
--
-- -- >>> transpose [[1,2,3],[4,5,6]] -- [[1,4],[2,5],[3,6]] ---- -- If some of the rows are shorter than the following rows, their -- elements are skipped: -- --
-- >>> transpose [[10,11],[20],[],[30,31,32]] -- [[10,20,30],[11,31],[32]] --transpose :: () => [[a]] -> [[a]] -- | intercalate xs xss is equivalent to (concat -- (intersperse xs xss)). It inserts the list xs in -- between the lists in xss and concatenates the result. -- --
-- >>> intercalate ", " ["Lorem", "ipsum", "dolor"] -- "Lorem, ipsum, dolor" --intercalate :: () => [a] -> [[a]] -> [a] -- | The intersperse function takes an element and a list and -- `intersperses' that element between the elements of the list. For -- example, -- --
-- >>> intersperse ',' "abcde" -- "a,b,c,d,e" --intersperse :: () => a -> [a] -> [a] -- | The intersectBy function is the non-overloaded version of -- intersect. intersectBy :: () => (a -> a -> Bool) -> [a] -> [a] -> [a] -- | The intersect function takes the list intersection of two -- lists. For example, -- --
-- >>> [1,2,3,4] `intersect` [2,4,6,8] -- [2,4] ---- -- If the first list contains duplicates, so will the result. -- --
-- >>> [1,2,2,3,4] `intersect` [6,4,4,2] -- [2,2,4] ---- -- It is a special case of intersectBy, which allows the -- programmer to supply their own equality test. If the element is found -- in both the first and the second list, the element from the first list -- will be used. intersect :: Eq a => [a] -> [a] -> [a] -- | The unionBy function is the non-overloaded version of -- union. unionBy :: () => (a -> a -> Bool) -> [a] -> [a] -> [a] -- | The union function returns the list union of the two lists. For -- example, -- --
-- >>> "dog" `union` "cow" -- "dogcw" ---- -- Duplicates, and elements of the first list, are removed from the the -- second list, but if the first list contains duplicates, so will the -- result. It is a special case of unionBy, which allows the -- programmer to supply their own equality test. union :: Eq a => [a] -> [a] -> [a] -- | The \\ function is list difference (non-associative). In the -- result of xs \\ ys, the first occurrence of -- each element of ys in turn (if any) has been removed from -- xs. Thus -- --
-- (xs ++ ys) \\ xs == ys. ---- --
-- >>> "Hello World!" \\ "ell W" -- "Hoorld!" ---- -- It is a special case of deleteFirstsBy, which allows the -- programmer to supply their own equality test. (\\) :: Eq a => [a] -> [a] -> [a] infix 5 \\ -- | The deleteBy function behaves like delete, but takes a -- user-supplied equality predicate. -- --
-- >>> deleteBy (<=) 4 [1..10] -- [1,2,3,5,6,7,8,9,10] --deleteBy :: () => (a -> a -> Bool) -> a -> [a] -> [a] -- | delete x removes the first occurrence of x -- from its list argument. For example, -- --
-- >>> delete 'a' "banana" -- "bnana" ---- -- It is a special case of deleteBy, which allows the programmer -- to supply their own equality test. delete :: Eq a => a -> [a] -> [a] -- | The nubBy function behaves just like nub, except it uses -- a user-supplied equality predicate instead of the overloaded == -- function. -- --
-- >>> nubBy (\x y -> mod x 3 == mod y 3) [1,2,4,5,6] -- [1,2,6] --nubBy :: () => (a -> a -> Bool) -> [a] -> [a] -- | O(n^2). The nub function removes duplicate elements from -- a list. In particular, it keeps only the first occurrence of each -- element. (The name nub means `essence'.) It is a special case -- of nubBy, which allows the programmer to supply their own -- equality test. -- --
-- >>> nub [1,2,3,4,3,2,1,2,4,3,5] -- [1,2,3,4,5] --nub :: Eq a => [a] -> [a] -- | The isInfixOf function takes two lists and returns True -- iff the first list is contained, wholly and intact, anywhere within -- the second. -- --
-- >>> isInfixOf "Haskell" "I really like Haskell." -- True ---- --
-- >>> isInfixOf "Ial" "I really like Haskell." -- False --isInfixOf :: Eq a => [a] -> [a] -> Bool -- | The isSuffixOf function takes two lists and returns True -- iff the first list is a suffix of the second. The second list must be -- finite. -- --
-- >>> "ld!" `isSuffixOf` "Hello World!" -- True ---- --
-- >>> "World" `isSuffixOf` "Hello World!" -- False --isSuffixOf :: Eq a => [a] -> [a] -> Bool -- | The isPrefixOf function takes two lists and returns True -- iff the first list is a prefix of the second. -- --
-- >>> "Hello" `isPrefixOf` "Hello World!" -- True ---- --
-- >>> "Hello" `isPrefixOf` "Wello Horld!" -- False --isPrefixOf :: Eq a => [a] -> [a] -> Bool -- | The findIndices function extends findIndex, by returning -- the indices of all elements satisfying the predicate, in ascending -- order. -- --
-- >>> findIndices (`elem` "aeiou") "Hello World!" -- [1,4,7] --findIndices :: () => (a -> Bool) -> [a] -> [Int] -- | The findIndex function takes a predicate and a list and returns -- the index of the first element in the list satisfying the predicate, -- or Nothing if there is no such element. -- --
-- >>> findIndex isSpace "Hello World!" -- Just 5 --findIndex :: () => (a -> Bool) -> [a] -> Maybe Int -- | The elemIndices function extends elemIndex, by returning -- the indices of all elements equal to the query element, in ascending -- order. -- --
-- >>> elemIndices 'o' "Hello World" -- [4,7] --elemIndices :: Eq a => a -> [a] -> [Int] -- | The elemIndex function returns the index of the first element -- in the given list which is equal (by ==) to the query element, -- or Nothing if there is no such element. -- --
-- >>> elemIndex 4 [0..] -- Just 4 --elemIndex :: Eq a => a -> [a] -> Maybe Int -- | The stripPrefix function drops the given prefix from a list. It -- returns Nothing if the list did not start with the prefix -- given, or Just the list after the prefix, if it does. -- --
-- >>> stripPrefix "foo" "foobar" -- Just "bar" ---- --
-- >>> stripPrefix "foo" "foo" -- Just "" ---- --
-- >>> stripPrefix "foo" "barfoo" -- Nothing ---- --
-- >>> stripPrefix "foo" "barfoobaz" -- Nothing --stripPrefix :: Eq a => [a] -> [a] -> Maybe [a] -- | The dropWhileEnd function drops the largest suffix of a list in -- which the given predicate holds for all elements. For example: -- --
-- >>> dropWhileEnd isSpace "foo\n" -- "foo" ---- --
-- >>> dropWhileEnd isSpace "foo bar" -- "foo bar" ---- --
-- dropWhileEnd isSpace ("foo\n" ++ undefined) == "foo" ++ undefined
--
dropWhileEnd :: () => (a -> Bool) -> [a] -> [a]
-- | Selects Unicode space and separator characters.
--
-- This function returns True if its argument has one of the
-- following GeneralCategorys, or False otherwise:
--
-- -- >>> isSeparator 'a' -- False -- -- >>> isSeparator '6' -- False -- -- >>> isSeparator ' ' -- True ---- -- Warning: newlines and tab characters are not considered separators. -- --
-- >>> isSeparator '\n' -- False -- -- >>> isSeparator '\t' -- False ---- -- But some more exotic characters are (like HTML's ): -- --
-- >>> isSeparator '\160' -- True --isSeparator :: Char -> Bool -- | Selects Unicode numeric characters, including digits from various -- scripts, Roman numerals, et cetera. -- -- This function returns True if its argument has one of the -- following GeneralCategorys, or False otherwise: -- --
-- >>> isNumber 'a' -- False -- -- >>> isNumber '%' -- False -- -- >>> isNumber '3' -- True ---- -- ASCII '0' through '9' are all numbers: -- --
-- >>> and $ map isNumber ['0'..'9'] -- True ---- -- Unicode Roman numerals are "numbers" as well: -- --
-- >>> isNumber 'Ⅸ' -- True --isNumber :: Char -> Bool -- | Selects Unicode mark characters, for example accents and the like, -- which combine with preceding characters. -- -- This function returns True if its argument has one of the -- following GeneralCategorys, or False otherwise: -- --
-- >>> isMark 'a' -- False -- -- >>> isMark '0' -- False ---- -- Combining marks such as accent characters usually need to follow -- another character before they become printable: -- --
-- >>> map isMark "ò" -- [False,True] ---- -- Puns are not necessarily supported: -- --
-- >>> isMark '✓' -- False --isMark :: Char -> Bool -- | Selects alphabetic Unicode characters (lower-case, upper-case and -- title-case letters, plus letters of caseless scripts and modifiers -- letters). This function is equivalent to isAlpha. -- -- This function returns True if its argument has one of the -- following GeneralCategorys, or False otherwise: -- --
-- >>> isLetter 'a' -- True -- -- >>> isLetter 'A' -- True -- -- >>> isLetter 'λ' -- True -- -- >>> isLetter '0' -- False -- -- >>> isLetter '%' -- False -- -- >>> isLetter '♥' -- False -- -- >>> isLetter '\31' -- False ---- -- Ensure that isLetter and isAlpha are equivalent. -- --
-- >>> let chars = [(chr 0)..] -- -- >>> let letters = map isLetter chars -- -- >>> let alphas = map isAlpha chars -- -- >>> letters == alphas -- True --isLetter :: Char -> Bool -- | Convert a single digit Char to the corresponding Int. -- This function fails unless its argument satisfies isHexDigit, -- but recognises both upper- and lower-case hexadecimal digits (that is, -- '0'..'9', 'a'..'f', -- 'A'..'F'). -- --
-- >>> map digitToInt ['0'..'9'] -- [0,1,2,3,4,5,6,7,8,9] ---- -- Both upper- and lower-case 'A' through 'F' are -- converted as well, to 10..15. -- --
-- >>> map digitToInt ['a'..'f'] -- [10,11,12,13,14,15] -- -- >>> map digitToInt ['A'..'F'] -- [10,11,12,13,14,15] ---- -- Anything else throws an exception: -- --
-- >>> digitToInt 'G' -- *** Exception: Char.digitToInt: not a digit 'G' -- -- >>> digitToInt '♥' -- *** Exception: Char.digitToInt: not a digit '\9829' --digitToInt :: Char -> Int -- | The read function reads input from a string, which must be -- completely consumed by the input process. read fails with an -- error if the parse is unsuccessful, and it is therefore -- discouraged from being used in real applications. Use readMaybe -- or readEither for safe alternatives. -- --
-- >>> read "123" :: Int -- 123 ---- --
-- >>> read "hello" :: Int -- *** Exception: Prelude.read: no parse --read :: Read a => String -> a -- | Parse a string using the Read instance. Succeeds if there is -- exactly one valid result. -- --
-- >>> readMaybe "123" :: Maybe Int -- Just 123 ---- --
-- >>> readMaybe "hello" :: Maybe Int -- Nothing --readMaybe :: Read a => String -> Maybe a -- | Parse a string using the Read instance. Succeeds if there is -- exactly one valid result. A Left value indicates a parse error. -- --
-- >>> readEither "123" :: Either String Int -- Right 123 ---- --
-- >>> readEither "hello" :: Either String Int -- Left "Prelude.read: no parse" --readEither :: Read a => String -> Either String a -- | equivalent to readsPrec with a precedence of 0. reads :: Read a => ReadS a -- | Return the contents of a Right-value or a default value -- otherwise. -- --
-- >>> fromRight 1 (Right 3) -- 3 -- -- >>> fromRight 1 (Left "foo") -- 1 --fromRight :: () => b -> Either a b -> b -- | Return the contents of a Left-value or a default value -- otherwise. -- --
-- >>> fromLeft 1 (Left 3) -- 3 -- -- >>> fromLeft 1 (Right "foo") -- 1 --fromLeft :: () => a -> Either a b -> a -- | Return True if the given value is a Right-value, -- False otherwise. -- --
-- >>> isRight (Left "foo") -- False -- -- >>> isRight (Right 3) -- True ---- -- Assuming a Left value signifies some sort of error, we can use -- isRight to write a very simple reporting function that only -- outputs "SUCCESS" when a computation has succeeded. -- -- This example shows how isRight might be used to avoid pattern -- matching when one does not care about the value contained in the -- constructor: -- --
-- >>> import Control.Monad ( when ) -- -- >>> let report e = when (isRight e) $ putStrLn "SUCCESS" -- -- >>> report (Left "parse error") -- -- >>> report (Right 1) -- SUCCESS --isRight :: () => Either a b -> Bool -- | Return True if the given value is a Left-value, -- False otherwise. -- --
-- >>> isLeft (Left "foo") -- True -- -- >>> isLeft (Right 3) -- False ---- -- Assuming a Left value signifies some sort of error, we can use -- isLeft to write a very simple error-reporting function that -- does absolutely nothing in the case of success, and outputs "ERROR" if -- any error occurred. -- -- This example shows how isLeft might be used to avoid pattern -- matching when one does not care about the value contained in the -- constructor: -- --
-- >>> import Control.Monad ( when ) -- -- >>> let report e = when (isLeft e) $ putStrLn "ERROR" -- -- >>> report (Right 1) -- -- >>> report (Left "parse error") -- ERROR --isLeft :: () => Either a b -> Bool -- | Partitions a list of Either into two lists. All the Left -- elements are extracted, in order, to the first component of the -- output. Similarly the Right elements are extracted to the -- second component of the output. -- --
-- >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ] -- -- >>> partitionEithers list -- (["foo","bar","baz"],[3,7]) ---- -- The pair returned by partitionEithers x should be the -- same pair as (lefts x, rights x): -- --
-- >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ] -- -- >>> partitionEithers list == (lefts list, rights list) -- True --partitionEithers :: () => [Either a b] -> ([a], [b]) -- | Extracts from a list of Either all the Right elements. -- All the Right elements are extracted in order. -- --
-- >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ] -- -- >>> rights list -- [3,7] --rights :: () => [Either a b] -> [b] -- | Extracts from a list of Either all the Left elements. -- All the Left elements are extracted in order. -- --
-- >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ] -- -- >>> lefts list -- ["foo","bar","baz"] --lefts :: () => [Either a b] -> [a] -- | Case analysis for the Either type. If the value is -- Left a, apply the first function to a; if it -- is Right b, apply the second function to b. -- --
-- >>> let s = Left "foo" :: Either String Int -- -- >>> let n = Right 3 :: Either String Int -- -- >>> either length (*2) s -- 3 -- -- >>> either length (*2) n -- 6 --either :: () => (a -> c) -> (b -> c) -> Either a b -> c -- |
-- comparing p x y = compare (p x) (p y) ---- -- Useful combinator for use in conjunction with the xxxBy -- family of functions from Data.List, for example: -- --
-- ... sortBy (comparing fst) ... --comparing :: Ord a => (b -> a) -> b -> b -> Ordering -- | The Down type allows you to reverse sort order conveniently. A -- value of type Down a contains a value of type -- a (represented as Down a). If a has -- an Ord instance associated with it then comparing two -- values thus wrapped will give you the opposite of their normal sort -- order. This is particularly useful when sorting in generalised list -- comprehensions, as in: then sortWith by Down x newtype Down a Down :: a -> Down a -- | Proxy is a type that holds no data, but has a phantom parameter -- of arbitrary type (or even kind). Its use is to provide type -- information, even though there is no value available of that type (or -- it may be too costly to create one). -- -- Historically, Proxy :: Proxy a is a safer -- alternative to the 'undefined :: a' idiom. -- --
-- >>> Proxy :: Proxy (Void, Int -> Int) -- Proxy ---- -- Proxy can even hold types of higher kinds, -- --
-- >>> Proxy :: Proxy Either -- Proxy ---- --
-- >>> Proxy :: Proxy Functor -- Proxy ---- --
-- >>> Proxy :: Proxy complicatedStructure -- Proxy --data Proxy (t :: k) :: forall k. () => k -> Type Proxy :: Proxy -- | Left-to-right composition (>>>) :: Category cat => cat a b -> cat b c -> cat a c infixr 1 >>> -- | Right-to-left composition (<<<) :: Category cat => cat b c -> cat a b -> cat a c infixr 1 <<< -- | A class for categories. Instances should satisfy the laws -- --
-- f . id = f -- (right identity) -- id . f = f -- (left identity) -- f . (g . h) = (f . g) . h -- (associativity) --class Category (cat :: k -> k -> Type) -- | the identity morphism id :: Category cat => cat a a -- | morphism composition (.) :: Category cat => cat b c -> cat a b -> cat a c infixr 9 . -- | Propositional equality. If a :~: b is inhabited by some -- terminating value, then the type a is the same as the type -- b. To use this equality in practice, pattern-match on the -- a :~: b to get out the Refl constructor; in the body -- of the pattern-match, the compiler knows that a ~ b. data (:~:) (a :: k) (b :: k) :: forall k. () => k -> k -> Type [Refl] :: forall k (a :: k) (b :: k). () => a :~: a infix 4 :~: -- | Kind heterogeneous propositional equality. Like :~:, a :~~: -- b is inhabited by a terminating value if and only if a -- is the same type as b. data (:~~:) (a :: k1) (b :: k2) :: forall k1 k2. () => k1 -> k2 -> Type [HRefl] :: forall k1 k2 (a :: k1) (b :: k2). () => a :~~: a infix 4 :~~: -- | casts an IntPtr to a Ptr intPtrToPtr :: () => IntPtr -> Ptr a -- | casts a Ptr to an IntPtr ptrToIntPtr :: () => Ptr a -> IntPtr -- | casts a WordPtr to a Ptr wordPtrToPtr :: () => WordPtr -> Ptr a -- | casts a Ptr to a WordPtr ptrToWordPtr :: () => Ptr a -> WordPtr -- | Release the storage associated with the given FunPtr, which -- must have been obtained from a wrapper stub. This should be called -- whenever the return value from a foreign import wrapper function is no -- longer required; otherwise, the storage it uses will leak. freeHaskellFunPtr :: () => FunPtr a -> IO () -- | An unsigned integral type that can be losslessly converted to and from -- Ptr. This type is also compatible with the C99 type -- uintptr_t, and can be marshalled to and from that type -- safely. newtype WordPtr WordPtr :: Word -> WordPtr -- | A signed integral type that can be losslessly converted to and from -- Ptr. This type is also compatible with the C99 type -- intptr_t, and can be marshalled to and from that type safely. newtype IntPtr IntPtr :: Int -> IntPtr -- | The member functions of this class facilitate writing values of -- primitive types to raw memory (which may have been allocated with the -- above mentioned routines) and reading values from blocks of raw -- memory. The class, furthermore, includes support for computing the -- storage requirements and alignment restrictions of storable types. -- -- Memory addresses are represented as values of type Ptr -- a, for some a which is an instance of class -- Storable. The type argument to Ptr helps provide some -- valuable type safety in FFI code (you can't mix pointers of different -- types without an explicit cast), while helping the Haskell type system -- figure out which marshalling method is needed for a given pointer. -- -- All marshalling between Haskell and a foreign language ultimately -- boils down to translating Haskell data structures into the binary -- representation of a corresponding data structure of the foreign -- language and vice versa. To code this marshalling in Haskell, it is -- necessary to manipulate primitive data types stored in unstructured -- memory blocks. The class Storable facilitates this manipulation -- on all types for which it is instantiated, which are the standard -- basic types of Haskell, the fixed size Int types -- (Int8, Int16, Int32, Int64), the fixed -- size Word types (Word8, Word16, Word32, -- Word64), StablePtr, all types from -- Foreign.C.Types, as well as Ptr. class Storable a -- | Computes the storage requirements (in bytes) of the argument. The -- value of the argument is not used. sizeOf :: Storable a => a -> Int -- | Computes the alignment constraint of the argument. An alignment -- constraint x is fulfilled by any address divisible by -- x. The value of the argument is not used. alignment :: Storable a => a -> Int -- | Read a value from a memory area regarded as an array of values of the -- same kind. The first argument specifies the start address of the array -- and the second the index into the array (the first element of the -- array has index 0). The following equality holds, -- --
-- peekElemOff addr idx = IOExts.fixIO $ \result -> -- peek (addr `plusPtr` (idx * sizeOf result)) ---- -- Note that this is only a specification, not necessarily the concrete -- implementation of the function. peekElemOff :: Storable a => Ptr a -> Int -> IO a -- | Write a value to a memory area regarded as an array of values of the -- same kind. The following equality holds: -- --
-- pokeElemOff addr idx x = -- poke (addr `plusPtr` (idx * sizeOf x)) x --pokeElemOff :: Storable a => Ptr a -> Int -> a -> IO () -- | Read a value from a memory location given by a base address and -- offset. The following equality holds: -- --
-- peekByteOff addr off = peek (addr `plusPtr` off) --peekByteOff :: Storable a => Ptr b -> Int -> IO a -- | Write a value to a memory location given by a base address and offset. -- The following equality holds: -- --
-- pokeByteOff addr off x = poke (addr `plusPtr` off) x --pokeByteOff :: Storable a => Ptr b -> Int -> a -> IO () -- | Read a value from the given memory location. -- -- Note that the peek and poke functions might require properly aligned -- addresses to function correctly. This is architecture dependent; thus, -- portable code should ensure that when peeking or poking values of some -- type a, the alignment constraint for a, as given by -- the function alignment is fulfilled. peek :: Storable a => Ptr a -> IO a -- | Write the given value to the given memory location. Alignment -- restrictions might apply; see peek. poke :: Storable a => Ptr a -> a -> IO () -- | The inverse of castStablePtrToPtr, i.e., we have the identity -- --
-- sp == castPtrToStablePtr (castStablePtrToPtr sp) ---- -- for any stable pointer sp on which freeStablePtr has -- not been executed yet. Moreover, castPtrToStablePtr may only be -- applied to pointers that have been produced by -- castStablePtrToPtr. castPtrToStablePtr :: () => Ptr () -> StablePtr a -- | Coerce a stable pointer to an address. No guarantees are made about -- the resulting value, except that the original stable pointer can be -- recovered by castPtrToStablePtr. In particular, the address may -- not refer to an accessible memory location and any attempt to pass it -- to the member functions of the class Storable leads to -- undefined behaviour. castStablePtrToPtr :: () => StablePtr a -> Ptr () -- | Obtain the Haskell value referenced by a stable pointer, i.e., the -- same value that was passed to the corresponding call to -- makeStablePtr. If the argument to deRefStablePtr has -- already been freed using freeStablePtr, the behaviour of -- deRefStablePtr is undefined. deRefStablePtr :: () => StablePtr a -> IO a -- | Dissolve the association between the stable pointer and the Haskell -- value. Afterwards, if the stable pointer is passed to -- deRefStablePtr or freeStablePtr, the behaviour is -- undefined. However, the stable pointer may still be passed to -- castStablePtrToPtr, but the Ptr () value -- returned by castStablePtrToPtr, in this case, is undefined (in -- particular, it may be nullPtr). Nevertheless, the call to -- castStablePtrToPtr is guaranteed not to diverge. freeStablePtr :: () => StablePtr a -> IO () -- | Casts a Ptr to a FunPtr. -- -- Note: this is valid only on architectures where data and -- function pointers range over the same set of addresses, and should -- only be used for bindings to external libraries whose interface -- already relies on this assumption. castPtrToFunPtr :: () => Ptr a -> FunPtr b -- | Casts a FunPtr to a Ptr. -- -- Note: this is valid only on architectures where data and -- function pointers range over the same set of addresses, and should -- only be used for bindings to external libraries whose interface -- already relies on this assumption. castFunPtrToPtr :: () => FunPtr a -> Ptr b -- | Casts a FunPtr to a FunPtr of a different type. castFunPtr :: () => FunPtr a -> FunPtr b -- | The constant nullFunPtr contains a distinguished value of -- FunPtr that is not associated with a valid memory location. nullFunPtr :: () => FunPtr a -- | Computes the offset required to get from the second to the first -- argument. We have -- --
-- p2 == p1 `plusPtr` (p2 `minusPtr` p1) --minusPtr :: () => Ptr a -> Ptr b -> Int -- | Given an arbitrary address and an alignment constraint, -- alignPtr yields the next higher address that fulfills the -- alignment constraint. An alignment constraint x is fulfilled -- by any address divisible by x. This operation is idempotent. alignPtr :: () => Ptr a -> Int -> Ptr a -- | Advances the given address by the given offset in bytes. plusPtr :: () => Ptr a -> Int -> Ptr b -- | The castPtr function casts a pointer from one type to another. castPtr :: () => Ptr a -> Ptr b -- | The constant nullPtr contains a distinguished value of -- Ptr that is not associated with a valid memory location. nullPtr :: () => Ptr a -- | Show non-negative Integral numbers in base 8. showOct :: (Integral a, Show a) => a -> ShowS -- | Show non-negative Integral numbers in base 16. showHex :: (Integral a, Show a) => a -> ShowS -- | Shows a non-negative Integral number using the base -- specified by the first argument, and the character representation -- specified by the second. showIntAtBase :: (Integral a, Show a) => a -> (Int -> Char) -> a -> ShowS -- | Show a floating-point value in the hexadecimal format, similar to the -- %a specifier in C's printf. -- --
-- >>> showHFloat (212.21 :: Double) "" -- "0x1.a86b851eb851fp7" -- -- >>> showHFloat (-12.76 :: Float) "" -- "-0x1.9851ecp3" -- -- >>> showHFloat (-0 :: Double) "" -- "-0x0p+0" --showHFloat :: RealFloat a => a -> ShowS -- | Show a signed RealFloat value using standard decimal notation -- for arguments whose absolute value lies between 0.1 and -- 9,999,999, and scientific notation otherwise. -- -- This behaves as showFFloat, except that a decimal point is -- always guaranteed, even if not needed. showGFloatAlt :: RealFloat a => Maybe Int -> a -> ShowS -- | Show a signed RealFloat value using standard decimal notation -- (e.g. 245000, 0.0015). -- -- This behaves as showFFloat, except that a decimal point is -- always guaranteed, even if not needed. showFFloatAlt :: RealFloat a => Maybe Int -> a -> ShowS -- | Show a signed RealFloat value using standard decimal notation -- for arguments whose absolute value lies between 0.1 and -- 9,999,999, and scientific notation otherwise. -- -- In the call showGFloat digs val, if digs is -- Nothing, the value is shown to full precision; if digs -- is Just d, then at most d digits after the -- decimal point are shown. showGFloat :: RealFloat a => Maybe Int -> a -> ShowS -- | Show a signed RealFloat value using standard decimal notation -- (e.g. 245000, 0.0015). -- -- In the call showFFloat digs val, if digs is -- Nothing, the value is shown to full precision; if digs -- is Just d, then at most d digits after the -- decimal point are shown. showFFloat :: RealFloat a => Maybe Int -> a -> ShowS -- | Show a signed RealFloat value using scientific (exponential) -- notation (e.g. 2.45e2, 1.5e-3). -- -- In the call showEFloat digs val, if digs is -- Nothing, the value is shown to full precision; if digs -- is Just d, then at most d digits after the -- decimal point are shown. showEFloat :: RealFloat a => Maybe Int -> a -> ShowS -- | Show non-negative Integral numbers in base 10. showInt :: Integral a => a -> ShowS -- | Reads a signed Real value, given a reader for an -- unsigned value. readSigned :: Real a => ReadS a -> ReadS a -- | Reads an unsigned RealFrac value, expressed in decimal -- scientific notation. readFloat :: RealFrac a => ReadS a -- | Read an unsigned number in hexadecimal notation. Both upper or lower -- case letters are allowed. -- --
-- >>> readHex "deadbeef" -- [(3735928559,"")] --readHex :: (Eq a, Num a) => ReadS a -- | Read an unsigned number in decimal notation. -- --
-- >>> readDec "0644" -- [(644,"")] --readDec :: (Eq a, Num a) => ReadS a -- | Read an unsigned number in octal notation. -- --
-- >>> readOct "0644" -- [(420,"")] --readOct :: (Eq a, Num a) => ReadS a -- | Reads an unsigned Integral value in an arbitrary base. readInt :: Num a => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a -- | Reads a non-empty string of decimal digits. lexDigits :: ReadS String -- | Read a string representation of a character, using Haskell -- source-language escape conventions, and convert it to the character -- that it encodes. For example: -- --
-- readLitChar "\\nHello" = [('\n', "Hello")]
--
readLitChar :: ReadS Char
-- | Read a string representation of a character, using Haskell
-- source-language escape conventions. For example:
--
--
-- lexLitChar "\\nHello" = [("\\n", "Hello")]
--
lexLitChar :: ReadS String
-- | The lex function reads a single lexeme from the input,
-- discarding initial white space, and returning the characters that
-- constitute the lexeme. If the input string contains only white space,
-- lex returns a single successful `lexeme' consisting of the
-- empty string. (Thus lex "" = [("","")].) If there is
-- no legal lexeme at the beginning of the input string, lex fails
-- (i.e. returns []).
--
-- This lexer is not completely faithful to the Haskell lexical syntax in
-- the following respects:
--
-- -- floatToDigits base x = ([d1,d2,...,dn], e) ---- -- then -- --
n >= 1
x = 0.d1d2...dn * (base**e)
0 <= di <= base-1
-- >>> isSymbol 'a' -- False -- -- >>> isSymbol '6' -- False -- -- >>> isSymbol '=' -- True ---- -- The definition of "math symbol" may be a little counter-intuitive -- depending on one's background: -- --
-- >>> isSymbol '+' -- True -- -- >>> isSymbol '-' -- False --isSymbol :: Char -> Bool -- | Selects Unicode punctuation characters, including various kinds of -- connectors, brackets and quotes. -- -- This function returns True if its argument has one of the -- following GeneralCategorys, or False otherwise: -- --
-- >>> isPunctuation 'a' -- False -- -- >>> isPunctuation '7' -- False -- -- >>> isPunctuation '♥' -- False -- -- >>> isPunctuation '"' -- True -- -- >>> isPunctuation '?' -- True -- -- >>> isPunctuation '—' -- True --isPunctuation :: Char -> Bool -- | Selects ASCII hexadecimal digits, i.e. '0'..'9', -- 'a'..'f', 'A'..'F'. isHexDigit :: Char -> Bool -- | Selects ASCII octal digits, i.e. '0'..'7'. isOctDigit :: Char -> Bool -- | Selects ASCII digits, i.e. '0'..'9'. isDigit :: Char -> Bool -- | Returns True for any Unicode space character, and the control -- characters \t, \n, \r, \f, -- \v. isSpace :: Char -> Bool -- | Selects ASCII upper-case letters, i.e. characters satisfying both -- isAscii and isUpper. isAsciiUpper :: Char -> Bool -- | Selects ASCII lower-case letters, i.e. characters satisfying both -- isAscii and isLower. isAsciiLower :: Char -> Bool -- | Selects the first 256 characters of the Unicode character set, -- corresponding to the ISO 8859-1 (Latin-1) character set. isLatin1 :: Char -> Bool -- | Selects the first 128 characters of the Unicode character set, -- corresponding to the ASCII character set. isAscii :: Char -> Bool -- | The Unicode general category of the character. This relies on the -- Enum instance of GeneralCategory, which must remain in -- the same order as the categories are presented in the Unicode -- standard. -- --
-- >>> generalCategory 'a' -- LowercaseLetter -- -- >>> generalCategory 'A' -- UppercaseLetter -- -- >>> generalCategory '0' -- DecimalNumber -- -- >>> generalCategory '%' -- OtherPunctuation -- -- >>> generalCategory '♥' -- OtherSymbol -- -- >>> generalCategory '\31' -- Control -- -- >>> generalCategory ' ' -- Space --generalCategory :: Char -> GeneralCategory -- | Unicode General Categories (column 2 of the UnicodeData table) in the -- order they are listed in the Unicode standard (the Unicode Character -- Database, in particular). -- --
-- >>> :t OtherLetter -- OtherLetter :: GeneralCategory ---- -- Eq instance: -- --
-- >>> UppercaseLetter == UppercaseLetter -- True -- -- >>> UppercaseLetter == LowercaseLetter -- False ---- -- Ord instance: -- --
-- >>> NonSpacingMark <= MathSymbol -- True ---- -- Enum instance: -- --
-- >>> enumFromTo ModifierLetter SpacingCombiningMark -- [ModifierLetter,OtherLetter,NonSpacingMark,SpacingCombiningMark] ---- -- Read instance: -- --
-- >>> read "DashPunctuation" :: GeneralCategory -- DashPunctuation -- -- >>> read "17" :: GeneralCategory -- *** Exception: Prelude.read: no parse ---- -- Show instance: -- --
-- >>> show EnclosingMark -- "EnclosingMark" ---- -- Bounded instance: -- --
-- >>> minBound :: GeneralCategory -- UppercaseLetter -- -- >>> maxBound :: GeneralCategory -- NotAssigned ---- -- Ix instance: -- --
-- >>> import Data.Ix ( index ) -- -- >>> index (OtherLetter,Control) FinalQuote -- 12 -- -- >>> index (OtherLetter,Control) Format -- *** Exception: Error in array index --data GeneralCategory -- | Lu: Letter, Uppercase UppercaseLetter :: GeneralCategory -- | Ll: Letter, Lowercase LowercaseLetter :: GeneralCategory -- | Lt: Letter, Titlecase TitlecaseLetter :: GeneralCategory -- | Lm: Letter, Modifier ModifierLetter :: GeneralCategory -- | Lo: Letter, Other OtherLetter :: GeneralCategory -- | Mn: Mark, Non-Spacing NonSpacingMark :: GeneralCategory -- | Mc: Mark, Spacing Combining SpacingCombiningMark :: GeneralCategory -- | Me: Mark, Enclosing EnclosingMark :: GeneralCategory -- | Nd: Number, Decimal DecimalNumber :: GeneralCategory -- | Nl: Number, Letter LetterNumber :: GeneralCategory -- | No: Number, Other OtherNumber :: GeneralCategory -- | Pc: Punctuation, Connector ConnectorPunctuation :: GeneralCategory -- | Pd: Punctuation, Dash DashPunctuation :: GeneralCategory -- | Ps: Punctuation, Open OpenPunctuation :: GeneralCategory -- | Pe: Punctuation, Close ClosePunctuation :: GeneralCategory -- | Pi: Punctuation, Initial quote InitialQuote :: GeneralCategory -- | Pf: Punctuation, Final quote FinalQuote :: GeneralCategory -- | Po: Punctuation, Other OtherPunctuation :: GeneralCategory -- | Sm: Symbol, Math MathSymbol :: GeneralCategory -- | Sc: Symbol, Currency CurrencySymbol :: GeneralCategory -- | Sk: Symbol, Modifier ModifierSymbol :: GeneralCategory -- | So: Symbol, Other OtherSymbol :: GeneralCategory -- | Zs: Separator, Space Space :: GeneralCategory -- | Zl: Separator, Line LineSeparator :: GeneralCategory -- | Zp: Separator, Paragraph ParagraphSeparator :: GeneralCategory -- | Cc: Other, Control Control :: GeneralCategory -- | Cf: Other, Format Format :: GeneralCategory -- | Cs: Other, Surrogate Surrogate :: GeneralCategory -- | Co: Other, Private Use PrivateUse :: GeneralCategory -- | Cn: Other, Not Assigned NotAssigned :: GeneralCategory -- | Write a new value into an STRef writeSTRef :: () => STRef s a -> a -> ST s () -- | Read the value of an STRef readSTRef :: () => STRef s a -> ST s a -- | Build a new STRef in the current state thread newSTRef :: () => a -> ST s (STRef s a) -- | a value of type STRef s a is a mutable variable in state -- thread s, containing a value of type a -- --
-- >>> :{
-- runST (do
-- ref <- newSTRef "hello"
-- x <- readSTRef ref
-- writeSTRef ref (x ++ "world")
-- readSTRef ref )
-- :}
-- "helloworld"
--
data STRef s a
-- | Return the value computed by a state transformer computation. The
-- forall ensures that the internal state used by the ST
-- computation is inaccessible to the rest of the program.
runST :: () => (forall s. () => ST s a) -> a
-- | Attempt to convert an Integral type a to an
-- Integral type b using the size of the types as
-- measured by Bits methods.
--
-- A simpler version of this function is:
--
-- -- toIntegral :: (Integral a, Integral b) => a -> Maybe b -- toIntegral x -- | toInteger x == y = Just (fromInteger y) -- | otherwise = Nothing -- where -- y = toInteger x ---- -- This version requires going through Integer, which can be -- inefficient. However, toIntegralSized is optimized to allow -- GHC to statically determine the relative type sizes (as measured by -- bitSizeMaybe and isSigned) and avoid going through -- Integer for many types. (The implementation uses -- fromIntegral, which is itself optimized with rules for -- base types but may go through Integer for some type -- pairs.) toIntegralSized :: (Integral a, Integral b, Bits a, Bits b) => a -> Maybe b -- | Default implementation for popCount. -- -- This implementation is intentionally naive. Instances are expected to -- provide an optimized implementation for their size. popCountDefault :: (Bits a, Num a) => a -> Int -- | Default implementation for testBit. -- -- Note that: testBitDefault x i = (x .&. bit i) /= 0 testBitDefault :: (Bits a, Num a) => a -> Int -> Bool -- | Default implementation for bit. -- -- Note that: bitDefault i = 1 shiftL i bitDefault :: (Bits a, Num a) => Int -> a -- | The Bits class defines bitwise operations over integral types. -- --
clearBit zeroBits n == -- zeroBits
setBit zeroBits n == bit -- n
testBit zeroBits n == False
popCount zeroBits == 0
-- finiteBitSize = bitSize -- bitSizeMaybe = Just . finiteBitSize --finiteBitSize :: FiniteBits b => b -> Int -- | Count number of zero bits preceding the most significant set bit. -- --
-- countLeadingZeros (zeroBits :: a) = finiteBitSize (zeroBits :: a) ---- -- countLeadingZeros can be used to compute log base 2 via -- --
-- logBase2 x = finiteBitSize x - 1 - countLeadingZeros x ---- -- Note: The default implementation for this method is intentionally -- naive. However, the instances provided for the primitive integral -- types are implemented using CPU specific machine instructions. countLeadingZeros :: FiniteBits b => b -> Int -- | Count number of zero bits following the least significant set bit. -- --
-- countTrailingZeros (zeroBits :: a) = finiteBitSize (zeroBits :: a) -- countTrailingZeros . negate = countTrailingZeros ---- -- The related find-first-set operation can be expressed in terms -- of countTrailingZeros as follows -- --
-- findFirstSet x = 1 + countTrailingZeros x ---- -- Note: The default implementation for this method is intentionally -- naive. However, the instances provided for the primitive integral -- types are implemented using CPU specific machine instructions. countTrailingZeros :: FiniteBits b => b -> Int -- | Case analysis for the Bool type. bool x y p -- evaluates to x when p is False, and evaluates -- to y when p is True. -- -- This is equivalent to if p then y else x; that is, one can -- think of it as an if-then-else construct with its arguments reordered. -- --
-- >>> bool "foo" "bar" True -- "bar" -- -- >>> bool "foo" "bar" False -- "foo" ---- -- Confirm that bool x y p and if p then y else -- x are equivalent: -- --
-- >>> let p = True; x = "bar"; y = "foo" -- -- >>> bool x y p == if p then y else x -- True -- -- >>> let p = False -- -- >>> bool x y p == if p then y else x -- True --bool :: () => a -> a -> Bool -> a -- | & is a reverse application operator. This provides -- notational convenience. Its precedence is one higher than that of the -- forward application operator $, which allows & to be -- nested in $. -- --
-- >>> 5 & (+1) & show -- "6" --(&) :: () => a -> (a -> b) -> b infixl 1 & -- | on b u x y runs the binary function b -- on the results of applying unary function u to two -- arguments x and y. From the opposite perspective, it -- transforms two inputs and combines the outputs. -- --
-- ((+) `on` f) x y = f x + f y ---- -- Typical usage: sortBy (compare `on` -- fst). -- -- Algebraic properties: -- --
(*) `on` id = (*) -- (if (*) ∉ {⊥, const -- ⊥})
((*) `on` f) `on` g = (*) `on` (f . g)
flip on f . flip on g = flip on (g . -- f)
-- >>> let fac n = if n <= 1 then 1 else n * fac (n-1) in fac 5 -- 120 ---- -- This uses the fact that Haskell’s let introduces recursive -- bindings. We can rewrite this definition using fix, -- --
-- >>> fix (\rec n -> if n <= 1 then 1 else n * rec (n-1)) 5 -- 120 ---- -- Instead of making a recursive call, we introduce a dummy parameter -- rec; when used within fix, this parameter then refers -- to fix' argument, hence the recursion is reintroduced. fix :: () => (a -> a) -> a -- | void value discards or ignores the result of -- evaluation, such as the return value of an IO action. -- --
-- >>> void Nothing -- Nothing -- -- >>> void (Just 3) -- Just () ---- -- Replace the contents of an Either Int -- Int with unit, resulting in an Either -- Int '()': -- --
-- >>> void (Left 8675309) -- Left 8675309 -- -- >>> void (Right 8675309) -- Right () ---- -- Replace every element of a list with unit: -- --
-- >>> void [1,2,3] -- [(),(),()] ---- -- Replace the second element of a pair with unit: -- --
-- >>> void (1,2) -- (1,()) ---- -- Discard the result of an IO action: -- --
-- >>> mapM print [1,2] -- 1 -- 2 -- [(),()] -- -- >>> void $ mapM print [1,2] -- 1 -- 2 --void :: Functor f => f a -> f () -- | Flipped version of <$. -- --
-- >>> Nothing $> "foo" -- Nothing -- -- >>> Just 90210 $> "foo" -- Just "foo" ---- -- Replace the contents of an Either Int -- Int with a constant String, resulting in an -- Either Int String: -- --
-- >>> Left 8675309 $> "foo" -- Left 8675309 -- -- >>> Right 8675309 $> "foo" -- Right "foo" ---- -- Replace each element of a list with a constant String: -- --
-- >>> [1,2,3] $> "foo" -- ["foo","foo","foo"] ---- -- Replace the second element of a pair with a constant String: -- --
-- >>> (1,2) $> "foo" -- (1,"foo") --($>) :: Functor f => f a -> b -> f b infixl 4 $> -- | Flipped version of <$>. -- --
-- (<&>) = flip fmap ---- --
-- >>> Just 2 <&> (+1) -- Just 3 ---- --
-- >>> [1,2,3] <&> (+1) -- [2,3,4] ---- --
-- >>> Right 3 <&> (+1) -- Right 4 --(<&>) :: Functor f => f a -> (a -> b) -> f b infixl 1 <&> -- | An infix synonym for fmap. -- -- The name of this operator is an allusion to $. Note the -- similarities between their types: -- --
-- ($) :: (a -> b) -> a -> b -- (<$>) :: Functor f => (a -> b) -> f a -> f b ---- -- Whereas $ is function application, <$> is -- function application lifted over a Functor. -- --
-- >>> show <$> Nothing -- Nothing -- -- >>> show <$> Just 3 -- Just "3" ---- -- Convert from an Either Int Int to -- an Either Int String using -- show: -- --
-- >>> show <$> Left 17 -- Left 17 -- -- >>> show <$> Right 17 -- Right "17" ---- -- Double each element of a list: -- --
-- >>> (*2) <$> [1,2,3] -- [2,4,6] ---- -- Apply even to the second element of a pair: -- --
-- >>> even <$> (2,2) -- (2,True) --(<$>) :: Functor f => (a -> b) -> f a -> f b infixl 4 <$> -- | lcm x y is the smallest positive integer that both -- x and y divide. lcm :: Integral a => a -> a -> a -- | gcd x y is the non-negative factor of both x -- and y of which every common factor of x and -- y is also a factor; for example gcd 4 2 = 2, -- gcd (-4) 6 = 2, gcd 0 4 = 4. -- gcd 0 0 = 0. (That is, the common divisor -- that is "greatest" in the divisibility preordering.) -- -- Note: Since for signed fixed-width integer types, abs -- minBound < 0, the result may be negative if one of the -- arguments is minBound (and necessarily is if the other -- is 0 or minBound) for such types. gcd :: Integral a => a -> a -> a -- | raise a number to an integral power (^^) :: (Fractional a, Integral b) => a -> b -> a infixr 8 ^^ -- | raise a number to a non-negative integral power (^) :: (Num a, Integral b) => a -> b -> a infixr 8 ^ odd :: Integral a => a -> Bool even :: Integral a => a -> Bool -- | Converts a possibly-negative Real value to a string. showSigned :: Real a => (a -> ShowS) -> Int -> a -> ShowS -- | Extract the denominator of the ratio in reduced form: the numerator -- and denominator have no common factor and the denominator is positive. denominator :: () => Ratio a -> a -- | Extract the numerator of the ratio in reduced form: the numerator and -- denominator have no common factor and the denominator is positive. numerator :: () => Ratio a -> a -- | Forms the ratio of two integral numbers. (%) :: Integral a => a -> a -> Ratio a infixl 7 % -- | The toEnum method restricted to the type Char. chr :: Int -> Char -- | Convert an Int in the range 0..15 to the -- corresponding single digit Char. This function fails on other -- inputs, and generates lower-case hexadecimal digits. intToDigit :: Int -> Char -- | Convert a character to a string using only printable characters, using -- Haskell source-language escape conventions. For example: -- --
-- showLitChar '\n' s = "\\n" ++ s --showLitChar :: Char -> ShowS -- | utility function that surrounds the inner show function with -- parentheses when the Bool parameter is True. showParen :: Bool -> ShowS -> ShowS -- | utility function converting a String to a show function that -- simply prepends the string unchanged. showString :: String -> ShowS -- | utility function converting a Char to a show function that -- simply prepends the character unchanged. showChar :: Char -> ShowS -- | equivalent to showsPrec with a precedence of 0. shows :: Show a => a -> ShowS -- | The shows functions return a function that prepends the -- output String to an existing String. This allows -- constant-time concatenation of results using function composition. type ShowS = String -> String -- | The unzip3 function takes a list of triples and returns three -- lists, analogous to unzip. unzip3 :: () => [(a, b, c)] -> ([a], [b], [c]) -- | unzip transforms a list of pairs into a list of first -- components and a list of second components. unzip :: () => [(a, b)] -> ([a], [b]) -- | The zipWith3 function takes a function which combines three -- elements, as well as three lists and returns a list of their -- point-wise combination, analogous to zipWith. zipWith3 :: () => (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d] -- | zipWith generalises zip by zipping with the function -- given as the first argument, instead of a tupling function. For -- example, zipWith (+) is applied to two lists to -- produce the list of corresponding sums. -- -- zipWith is right-lazy: -- --
-- zipWith f [] _|_ = [] --zipWith :: () => (a -> b -> c) -> [a] -> [b] -> [c] -- | zip3 takes three lists and returns a list of triples, analogous -- to zip. zip3 :: () => [a] -> [b] -> [c] -> [(a, b, c)] -- | List index (subscript) operator, starting from 0. It is an instance of -- the more general genericIndex, which takes an index of any -- integral type. (!!) :: () => [a] -> Int -> a infixl 9 !! -- | lookup key assocs looks up a key in an association -- list. lookup :: Eq a => a -> [(a, b)] -> Maybe b -- | reverse xs returns the elements of xs in -- reverse order. xs must be finite. reverse :: () => [a] -> [a] -- | break, applied to a predicate p and a list -- xs, returns a tuple where first element is longest prefix -- (possibly empty) of xs of elements that do not satisfy -- p and second element is the remainder of the list: -- --
-- break (> 3) [1,2,3,4,1,2,3,4] == ([1,2,3],[4,1,2,3,4]) -- break (< 9) [1,2,3] == ([],[1,2,3]) -- break (> 9) [1,2,3] == ([1,2,3],[]) ---- -- break p is equivalent to span (not . -- p). break :: () => (a -> Bool) -> [a] -> ([a], [a]) -- | span, applied to a predicate p and a list xs, -- returns a tuple where first element is longest prefix (possibly empty) -- of xs of elements that satisfy p and second element -- is the remainder of the list: -- --
-- span (< 3) [1,2,3,4,1,2,3,4] == ([1,2],[3,4,1,2,3,4]) -- span (< 9) [1,2,3] == ([1,2,3],[]) -- span (< 0) [1,2,3] == ([],[1,2,3]) ---- -- span p xs is equivalent to (takeWhile p xs, -- dropWhile p xs) span :: () => (a -> Bool) -> [a] -> ([a], [a]) -- | splitAt n xs returns a tuple where first element is -- xs prefix of length n and second element is the -- remainder of the list: -- --
-- splitAt 6 "Hello World!" == ("Hello ","World!")
-- splitAt 3 [1,2,3,4,5] == ([1,2,3],[4,5])
-- splitAt 1 [1,2,3] == ([1],[2,3])
-- splitAt 3 [1,2,3] == ([1,2,3],[])
-- splitAt 4 [1,2,3] == ([1,2,3],[])
-- splitAt 0 [1,2,3] == ([],[1,2,3])
-- splitAt (-1) [1,2,3] == ([],[1,2,3])
--
--
-- It is equivalent to (take n xs, drop n xs) when
-- n is not _|_ (splitAt _|_ xs = _|_).
-- splitAt is an instance of the more general
-- genericSplitAt, in which n may be of any integral
-- type.
splitAt :: () => Int -> [a] -> ([a], [a])
-- | drop n xs returns the suffix of xs after the
-- first n elements, or [] if n > length
-- xs:
--
-- -- drop 6 "Hello World!" == "World!" -- drop 3 [1,2,3,4,5] == [4,5] -- drop 3 [1,2] == [] -- drop 3 [] == [] -- drop (-1) [1,2] == [1,2] -- drop 0 [1,2] == [1,2] ---- -- It is an instance of the more general genericDrop, in which -- n may be of any integral type. drop :: () => Int -> [a] -> [a] -- | take n, applied to a list xs, returns the -- prefix of xs of length n, or xs itself if -- n > length xs: -- --
-- take 5 "Hello World!" == "Hello" -- take 3 [1,2,3,4,5] == [1,2,3] -- take 3 [1,2] == [1,2] -- take 3 [] == [] -- take (-1) [1,2] == [] -- take 0 [1,2] == [] ---- -- It is an instance of the more general genericTake, in which -- n may be of any integral type. take :: () => Int -> [a] -> [a] -- | dropWhile p xs returns the suffix remaining after -- takeWhile p xs: -- --
-- dropWhile (< 3) [1,2,3,4,5,1,2,3] == [3,4,5,1,2,3] -- dropWhile (< 9) [1,2,3] == [] -- dropWhile (< 0) [1,2,3] == [1,2,3] --dropWhile :: () => (a -> Bool) -> [a] -> [a] -- | takeWhile, applied to a predicate p and a list -- xs, returns the longest prefix (possibly empty) of -- xs of elements that satisfy p: -- --
-- takeWhile (< 3) [1,2,3,4,1,2,3,4] == [1,2] -- takeWhile (< 9) [1,2,3] == [1,2,3] -- takeWhile (< 0) [1,2,3] == [] --takeWhile :: () => (a -> Bool) -> [a] -> [a] -- | cycle ties a finite list into a circular one, or equivalently, -- the infinite repetition of the original list. It is the identity on -- infinite lists. cycle :: () => [a] -> [a] -- | replicate n x is a list of length n with -- x the value of every element. It is an instance of the more -- general genericReplicate, in which n may be of any -- integral type. replicate :: () => Int -> a -> [a] -- | repeat x is an infinite list, with x the -- value of every element. repeat :: () => a -> [a] -- | 'iterate\'' is the strict version of iterate. -- -- It ensures that the result of each application of force to weak head -- normal form before proceeding. iterate' :: () => (a -> a) -> a -> [a] -- | iterate f x returns an infinite list of repeated -- applications of f to x: -- --
-- iterate f x == [x, f x, f (f x), ...] ---- -- Note that iterate is lazy, potentially leading to thunk -- build-up if the consumer doesn't force each iterate. See 'iterate\'' -- for a strict variant of this function. iterate :: () => (a -> a) -> a -> [a] -- | scanr1 is a variant of scanr that has no starting value -- argument. scanr1 :: () => (a -> a -> a) -> [a] -> [a] -- | scanr is the right-to-left dual of scanl. Note that -- --
-- head (scanr f z xs) == foldr f z xs. --scanr :: () => (a -> b -> b) -> b -> [a] -> [b] -- | A strictly accumulating version of scanl scanl' :: () => (b -> a -> b) -> b -> [a] -> [b] -- | scanl1 is a variant of scanl that has no starting value -- argument: -- --
-- scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...] --scanl1 :: () => (a -> a -> a) -> [a] -> [a] -- | scanl is similar to foldl, but returns a list of -- successive reduced values from the left: -- --
-- scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...] ---- -- Note that -- --
-- last (scanl f z xs) == foldl f z xs. --scanl :: () => (b -> a -> b) -> b -> [a] -> [b] -- | A strict version of foldl1 foldl1' :: () => (a -> a -> a) -> [a] -> a -- | Return all the elements of a list except the last one. The list must -- be non-empty. init :: () => [a] -> [a] -- | Extract the last element of a list, which must be finite and -- non-empty. last :: () => [a] -> a -- | Extract the elements after the head of a list, which must be -- non-empty. tail :: () => [a] -> [a] -- | Decompose a list into its head and tail. If the list is empty, returns -- Nothing. If the list is non-empty, returns Just (x, -- xs), where x is the head of the list and xs its -- tail. uncons :: () => [a] -> Maybe (a, [a]) -- | Extract the first element of a list, which must be non-empty. head :: () => [a] -> a -- | The mapMaybe function is a version of map which can -- throw out elements. In particular, the functional argument returns -- something of type Maybe b. If this is Nothing, -- no element is added on to the result list. If it is Just -- b, then b is included in the result list. -- --
-- >>> import Text.Read ( readMaybe ) -- -- >>> let readMaybeInt = readMaybe :: String -> Maybe Int -- -- >>> mapMaybe readMaybeInt ["1", "Foo", "3"] -- [1,3] -- -- >>> catMaybes $ map readMaybeInt ["1", "Foo", "3"] -- [1,3] ---- -- If we map the Just constructor, the entire list should be -- returned: -- --
-- >>> mapMaybe Just [1,2,3] -- [1,2,3] --mapMaybe :: () => (a -> Maybe b) -> [a] -> [b] -- | The catMaybes function takes a list of Maybes and -- returns a list of all the Just values. -- --
-- >>> catMaybes [Just 1, Nothing, Just 3] -- [1,3] ---- -- When constructing a list of Maybe values, catMaybes can -- be used to return all of the "success" results (if the list is the -- result of a map, then mapMaybe would be more -- appropriate): -- --
-- >>> import Text.Read ( readMaybe ) -- -- >>> [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ] -- [Just 1,Nothing,Just 3] -- -- >>> catMaybes $ [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ] -- [1,3] --catMaybes :: () => [Maybe a] -> [a] -- | The listToMaybe function returns Nothing on an empty -- list or Just a where a is the first element -- of the list. -- --
-- >>> listToMaybe [] -- Nothing ---- --
-- >>> listToMaybe [9] -- Just 9 ---- --
-- >>> listToMaybe [1,2,3] -- Just 1 ---- -- Composing maybeToList with listToMaybe should be the -- identity on singleton/empty lists: -- --
-- >>> maybeToList $ listToMaybe [5] -- [5] -- -- >>> maybeToList $ listToMaybe [] -- [] ---- -- But not on lists with more than one element: -- --
-- >>> maybeToList $ listToMaybe [1,2,3] -- [1] --listToMaybe :: () => [a] -> Maybe a -- | The maybeToList function returns an empty list when given -- Nothing or a singleton list when not given Nothing. -- --
-- >>> maybeToList (Just 7) -- [7] ---- --
-- >>> maybeToList Nothing -- [] ---- -- One can use maybeToList to avoid pattern matching when combined -- with a function that (safely) works on lists: -- --
-- >>> import Text.Read ( readMaybe ) -- -- >>> sum $ maybeToList (readMaybe "3") -- 3 -- -- >>> sum $ maybeToList (readMaybe "") -- 0 --maybeToList :: () => Maybe a -> [a] -- | The fromMaybe function takes a default value and and -- Maybe value. If the Maybe is Nothing, it returns -- the default values; otherwise, it returns the value contained in the -- Maybe. -- --
-- >>> fromMaybe "" (Just "Hello, World!") -- "Hello, World!" ---- --
-- >>> fromMaybe "" Nothing -- "" ---- -- Read an integer from a string using readMaybe. If we fail to -- parse an integer, we want to return 0 by default: -- --
-- >>> import Text.Read ( readMaybe ) -- -- >>> fromMaybe 0 (readMaybe "5") -- 5 -- -- >>> fromMaybe 0 (readMaybe "") -- 0 --fromMaybe :: () => a -> Maybe a -> a -- | The fromJust function extracts the element out of a Just -- and throws an error if its argument is Nothing. -- --
-- >>> fromJust (Just 1) -- 1 ---- --
-- >>> 2 * (fromJust (Just 10)) -- 20 ---- --
-- >>> 2 * (fromJust Nothing) -- *** Exception: Maybe.fromJust: Nothing --fromJust :: () => Maybe a -> a -- | The isNothing function returns True iff its argument is -- Nothing. -- --
-- >>> isNothing (Just 3) -- False ---- --
-- >>> isNothing (Just ()) -- False ---- --
-- >>> isNothing Nothing -- True ---- -- Only the outer constructor is taken into consideration: -- --
-- >>> isNothing (Just Nothing) -- False --isNothing :: () => Maybe a -> Bool -- | The isJust function returns True iff its argument is of -- the form Just _. -- --
-- >>> isJust (Just 3) -- True ---- --
-- >>> isJust (Just ()) -- True ---- --
-- >>> isJust Nothing -- False ---- -- Only the outer constructor is taken into consideration: -- --
-- >>> isJust (Just Nothing) -- True --isJust :: () => Maybe a -> Bool -- | The maybe function takes a default value, a function, and a -- Maybe value. If the Maybe value is Nothing, the -- function returns the default value. Otherwise, it applies the function -- to the value inside the Just and returns the result. -- --
-- >>> maybe False odd (Just 3) -- True ---- --
-- >>> maybe False odd Nothing -- False ---- -- Read an integer from a string using readMaybe. If we succeed, -- return twice the integer; that is, apply (*2) to it. If -- instead we fail to parse an integer, return 0 by default: -- --
-- >>> import Text.Read ( readMaybe ) -- -- >>> maybe 0 (*2) (readMaybe "5") -- 10 -- -- >>> maybe 0 (*2) (readMaybe "") -- 0 ---- -- Apply show to a Maybe Int. If we have Just -- n, we want to show the underlying Int n. But if -- we have Nothing, we return the empty string instead of (for -- example) "Nothing": -- --
-- >>> maybe "" show (Just 5) -- "5" -- -- >>> maybe "" show Nothing -- "" --maybe :: () => b -> (a -> b) -> Maybe a -> b -- | Swap the components of a pair. swap :: () => (a, b) -> (b, a) -- | uncurry converts a curried function to a function on pairs. -- --
-- >>> uncurry (+) (1,2) -- 3 ---- --
-- >>> uncurry ($) (show, 1) -- "1" ---- --
-- >>> map (uncurry max) [(1,2), (3,4), (6,8)] -- [2,4,8] --uncurry :: () => (a -> b -> c) -> (a, b) -> c -- | curry converts an uncurried function to a curried function. -- --
-- >>> curry fst 1 2 -- 1 --curry :: () => ((a, b) -> c) -> a -> b -> c -- | unsafeInterleaveIO allows an IO computation to be -- deferred lazily. When passed a value of type IO a, the -- IO will only be performed when the value of the a is -- demanded. This is used to implement lazy file reading, see -- hGetContents. unsafeInterleaveIO :: () => IO a -> IO a -- | This version of unsafePerformIO is more efficient because it -- omits the check that the IO is only being performed by a single -- thread. Hence, when you use unsafeDupablePerformIO, there is a -- possibility that the IO action may be performed multiple times (on a -- multiprocessor), and you should therefore ensure that it gives the -- same results each time. It may even happen that one of the duplicated -- IO actions is only run partially, and then interrupted in the middle -- without an exception being raised. Therefore, functions like -- bracket cannot be used safely within -- unsafeDupablePerformIO. unsafeDupablePerformIO :: () => IO a -> a -- | This is the "back door" into the IO monad, allowing IO -- computation to be performed at any time. For this to be safe, the -- IO computation should be free of side effects and independent -- of its environment. -- -- If the I/O computation wrapped in unsafePerformIO performs side -- effects, then the relative order in which those side effects take -- place (relative to the main I/O trunk, or other calls to -- unsafePerformIO) is indeterminate. Furthermore, when using -- unsafePerformIO to cause side-effects, you should take the -- following precautions to ensure the side effects are performed as many -- times as you expect them to be. Note that these precautions are -- necessary for GHC, but may not be sufficient, and other compilers may -- require different precautions: -- --
-- test :: IORef [a] -- test = unsafePerformIO $ newIORef [] -- -- main = do -- writeIORef test [42] -- bang <- readIORef test -- print (bang :: [Char]) ---- -- This program will core dump. This problem with polymorphic references -- is well known in the ML community, and does not arise with normal -- monadic use of references. There is no easy way to make it impossible -- once you use unsafePerformIO. Indeed, it is possible to write -- coerce :: a -> b with the help of unsafePerformIO. -- So be careful! unsafePerformIO :: () => IO a -> a -- | Check whether a given MVar is empty. -- -- Notice that the boolean value returned is just a snapshot of the state -- of the MVar. By the time you get to react on its result, the MVar may -- have been filled (or emptied) - so be extremely careful when using -- this operation. Use tryTakeMVar instead if possible. isEmptyMVar :: () => MVar a -> IO Bool -- | A non-blocking version of readMVar. The tryReadMVar -- function returns immediately, with Nothing if the MVar -- was empty, or Just a if the MVar was full with -- contents a. tryReadMVar :: () => MVar a -> IO (Maybe a) -- | A non-blocking version of putMVar. The tryPutMVar -- function attempts to put the value a into the MVar, -- returning True if it was successful, or False otherwise. tryPutMVar :: () => MVar a -> a -> IO Bool -- | A non-blocking version of takeMVar. The tryTakeMVar -- function returns immediately, with Nothing if the MVar -- was empty, or Just a if the MVar was full with -- contents a. After tryTakeMVar, the MVar is left -- empty. tryTakeMVar :: () => MVar a -> IO (Maybe a) -- | Put a value into an MVar. If the MVar is currently full, -- putMVar will wait until it becomes empty. -- -- There are two further important properties of putMVar: -- --
-- readMVar :: MVar a -> IO a -- readMVar m = -- mask_ $ do -- a <- takeMVar m -- putMVar m a -- return a --readMVar :: () => MVar a -> IO a -- | Return the contents of the MVar. If the MVar is -- currently empty, takeMVar will wait until it is full. After a -- takeMVar, the MVar is left empty. -- -- There are two further important properties of takeMVar: -- --
-- >>> flip (++) "hello" "world" -- "worldhello" --flip :: () => (a -> b -> c) -> b -> a -> c -- | const x is a unary function which evaluates to x for -- all inputs. -- --
-- >>> const 42 "hello" -- 42 ---- --
-- >>> map (const 42) [0..3] -- [42,42,42,42] --const :: () => a -> b -> a -- | The fromEnum method restricted to the type Char. ord :: Char -> Int -- | In many situations, the liftM operations can be replaced by -- uses of ap, which promotes function application. -- --
-- return f `ap` x1 `ap` ... `ap` xn ---- -- is equivalent to -- --
-- liftMn f x1 x2 ... xn --ap :: Monad m => m (a -> b) -> m a -> m b -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM5 :: Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM4 :: Monad m => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM3 :: Monad m => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right. For example, -- --
-- liftM2 (+) [0,1] [0,2] = [0,2,1,3] -- liftM2 (+) (Just 1) Nothing = Nothing --liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r -- | Promote a function to a monad. liftM :: Monad m => (a1 -> r) -> m a1 -> m r -- | Conditional execution of Applicative expressions. For example, -- --
-- when debug (putStrLn "Debugging") ---- -- will output the string Debugging if the Boolean value -- debug is True, and otherwise do nothing. when :: Applicative f => Bool -> f () -> f () -- | Same as >>=, but with the arguments interchanged. (=<<) :: Monad m => (a -> m b) -> m a -> m b infixr 1 =<< -- | Lift a ternary function to actions. liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d -- | Lift a function to actions. This function may be used as a value for -- fmap in a Functor instance. liftA :: Applicative f => (a -> b) -> f a -> f b -- | A variant of <*> with the arguments reversed. (<**>) :: Applicative f => f a -> f (a -> b) -> f b infixl 4 <**> -- | A monoid on applicative functors. -- -- If defined, some and many should be the least solutions -- of the equations: -- -- class Applicative f => Alternative (f :: Type -> Type) -- | The identity of <|> empty :: Alternative f => f a -- | An associative binary operation (<|>) :: Alternative f => f a -> f a -> f a -- | One or more. some :: Alternative f => f a -> f [a] -- | Zero or more. many :: Alternative f => f a -> f [a] infixl 3 <|> -- | Monads that also support choice and failure. class (Alternative m, Monad m) => MonadPlus (m :: Type -> Type) -- | The identity of mplus. It should also satisfy the equations -- --
-- mzero >>= f = mzero -- v >> mzero = mzero ---- -- The default definition is -- --
-- mzero = empty --mzero :: MonadPlus m => m a -- | An associative operation. The default definition is -- --
-- mplus = (<|>) --mplus :: MonadPlus m => m a -> m a -> m a -- | A String is a list of characters. String constants in Haskell -- are values of type String. type String = [Char] -- | A special case of error. It is expected that compilers will -- recognize this and insert error messages which are more appropriate to -- the context in which undefined appears. undefined :: HasCallStack => a -- | A variant of error that does not produce a stack trace. errorWithoutStackTrace :: () => [Char] -> a -- | error stops execution and displays an error message. error :: HasCallStack => [Char] -> a -- | The SomeException type is the root of the exception type -- hierarchy. When an exception of type e is thrown, behind the -- scenes it is encapsulated in a SomeException. data SomeException [SomeException] :: forall e. Exception e => e -> SomeException -- | Boolean "and" (&&) :: Bool -> Bool -> Bool infixr 3 && -- | Boolean "or" (||) :: Bool -> Bool -> Bool infixr 2 || -- | Boolean "not" not :: Bool -> Bool -- | Non-empty (and non-strict) list type. data NonEmpty a (:|) :: a -> [a] -> NonEmpty a infixr 5 :| -- | The class of semigroups (types with an associative binary operation). -- -- Instances should satisfy the associativity law: -- -- class Semigroup a -- | An associative operation. (<>) :: Semigroup a => a -> a -> a -- | Reduce a non-empty list with <> -- -- The default definition should be sufficient, but this can be -- overridden for efficiency. sconcat :: Semigroup a => NonEmpty a -> a -- | Repeat a value n times. -- -- Given that this works on a Semigroup it is allowed to fail if -- you request 0 or fewer repetitions, and the default definition will do -- so. -- -- By making this a member of the class, idempotent semigroups and -- monoids can upgrade this to execute in O(1) by picking -- stimes = stimesIdempotent or stimes = -- stimesIdempotentMonoid respectively. stimes :: (Semigroup a, Integral b) => b -> a -> a infixr 6 <> -- | withBinaryFile name mode act opens a file using -- openBinaryFile and passes the resulting handle to the -- computation act. The handle will be closed on exit from -- withBinaryFile, whether by normal termination or by raising an -- exception. withBinaryFile :: () => FilePath -> IOMode -> (Handle -> IO r) -> IO r -- | 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: -- --
-- from1 . to1 ≡ id -- to1 . from1 ≡ id --class Generic1 (f :: k -> Type) where { -- | Generic representation type type family Rep1 (f :: k -> Type) :: k -> Type; } -- | Convert from the datatype to its representation from1 :: Generic1 f => f a -> Rep1 f a -- | Convert from the representation to the datatype to1 :: Generic1 f => Rep1 f a -> f a class Hashable a hashWithSalt :: Hashable a => Int -> a -> Int hash :: Hashable a => a -> Int class Hashable1 (t :: Type -> Type) liftHashWithSalt :: Hashable1 t => (Int -> a -> Int) -> Int -> t a -> Int class Hashable2 (t :: Type -> Type -> Type) liftHashWithSalt2 :: Hashable2 t => (Int -> a -> Int) -> (Int -> b -> Int) -> Int -> t a b -> Int data HashMap k v data HashSet a -- | A map of integers to values a. data IntMap a -- | A set of integers. data IntSet -- | Non-empty (and non-strict) list type. data NonEmpty a (:|) :: a -> [a] -> NonEmpty a infixr 5 :| -- | The class of semigroups (types with an associative binary operation). -- -- Instances should satisfy the associativity law: -- -- class Semigroup a -- | An associative operation. (<>) :: Semigroup a => a -> a -> a -- | Reduce a non-empty list with <> -- -- The default definition should be sufficient, but this can be -- overridden for efficiency. sconcat :: Semigroup a => NonEmpty a -> a -- | Repeat a value n times. -- -- Given that this works on a Semigroup it is allowed to fail if -- you request 0 or fewer repetitions, and the default definition will do -- so. -- -- By making this a member of the class, idempotent semigroups and -- monoids can upgrade this to execute in O(1) by picking -- stimes = stimesIdempotent or stimes = -- stimesIdempotentMonoid respectively. stimes :: (Semigroup a, Integral b) => b -> a -> a infixr 6 <> -- | A space efficient, packed, unboxed Unicode text type. data Text type LazyText = Text -- | Would you believe it? The 2bit format stores blocks of Ns in a table -- at the beginning of a sequence, then packs four bases into a byte. So -- it is neither possible nor necessary to store Ns in the main sequence, -- and you would think they aren't stored there, right? And they aren't. -- Instead Ts are stored which the reader has to replace with Ns. -- -- The sensible way to treat these is probably to just say there are two -- kinds of implied annotation (repeats and large gaps for a typical -- genome), which can be interpreted in whatever way fits. And that's why -- we have Mask and getSubseqWith. module Bio.TwoBit data TwoBitFile TBF :: ByteString -> !HashMap Bytes TwoBitSequence -> TwoBitFile [tbf_raw] :: TwoBitFile -> ByteString [tbf_seqs] :: TwoBitFile -> !HashMap Bytes TwoBitSequence data TwoBitSequence TBS :: !IntMap Int -> !IntMap Int -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int -> TwoBitSequence [tbs_n_blocks] :: TwoBitSequence -> !IntMap Int [tbs_m_blocks] :: TwoBitSequence -> !IntMap Int [tbs_dna_offset] :: TwoBitSequence -> {-# UNPACK #-} !Int [tbs_dna_size] :: TwoBitSequence -> {-# UNPACK #-} !Int -- | Brings a 2bit file into memory. The file is mmap'ed, so it will not -- work on streams that are not actual files. It's also unsafe if the -- file is modified in any way. openTwoBit :: FilePath -> IO TwoBitFile getFwdSubseqWith :: TwoBitFile -> TwoBitSequence -> (Word8 -> Mask -> a) -> Int -> [a] -- | Extract a subsequence without masking. getSubseq :: TwoBitFile -> Range -> [Nucleotide] -- | Extract a subsequence and apply masking. TwoBit file can represent two -- kinds of masking (hard and soft), where hard masking is usually -- realized by replacing everything by Ns and soft masking is done by -- lowercasing. Here, we take a user supplied function to apply masking. getSubseqWith :: (Nucleotide -> Mask -> a) -> TwoBitFile -> Range -> [a] -- | Extract a subsequence with masking for biologists: soft masking is -- done by lowercasing, hard masking by printing an N. getSubseqAscii :: TwoBitFile -> Range -> String -- | Extract a subsequence with typical masking: soft masking is ignored, -- hard masked regions are replaced with Ns. getSubseqMasked :: TwoBitFile -> Range -> [Nucleotides] -- | Works only in forward direction. getLazySubseq :: TwoBitFile -> Position -> [Nucleotide] -- | Gets a fragment from a 2bit file. The result always has the desired -- length; if necessary, it is padded with Ns. Be careful about the -- unconventional encoding: 0..4 == TCAGN getFragment :: TwoBitFile -> Bytes -> Int -> Int -> Vector Word8 getFwdSubseqV :: TwoBitFile -> TwoBitSequence -> Int -> Int -> Vector Word8 getSeqnames :: TwoBitFile -> [Bytes] lookupSequence :: TwoBitFile -> Bytes -> Maybe TwoBitSequence getSeqLength :: TwoBitFile -> Bytes -> Int -- | limits a range to a position within the actual sequence clampPosition :: TwoBitFile -> Range -> Range -- | Sample a piece of random sequence uniformly from the genome. Only -- pieces that are not hard masked are sampled, soft masking is allowed, -- but not reported. On a 32bit platform, this will fail for genomes -- larger than 1G bases. However, if you're running this code on a 32bit -- platform, you have bigger problems to worry about. getRandomSeq :: TwoBitFile -> Int -> (Int -> g -> (Int, g)) -> g -> ((Range, [Nucleotide]), g) takeOverlap :: Int -> IntMap Int -> [(Int, Int)] -- | Merge blocks of Ns and blocks of Ms into single list of blocks with -- masking annotation. Gaps remain. Used internally only. mergeBlocks :: [(Int, Int)] -> [(Int, Int)] -> [(Int, Int, Mask)] data Mask None :: Mask Soft :: Mask Hard :: Mask Both :: Mask instance GHC.Show.Show Bio.TwoBit.Mask instance GHC.Enum.Enum Bio.TwoBit.Mask instance GHC.Classes.Ord Bio.TwoBit.Mask instance GHC.Classes.Eq Bio.TwoBit.Mask module Bio.Streaming.Vector -- | Reads the whole stream into a Vector. stream2vector :: (MonadIO m, Vector v a) => Stream (Of a) m r -> m (Of (v a) r) -- | Equivalent to stream2vector . Streaming.Prelude.take n, but -- terminates early and is thereby more efficient. stream2vectorN :: (MonadIO m, Vector v a) => Int -> Stream (Of a) m () -> m (v a) -- | See the simple examples of use here. We begin with a slight -- modification of the documentation to Data.ByteStream.Lazy: -- -- A time and space-efficient implementation of effectful byte streams -- using a stream of packed Word8 arrays, suitable for high -- performance use, both in terms of large data quantities, or high speed -- requirements. ByteStreams are encoded as streams of strict chunks of -- bytes. -- -- A key feature of ByteStreams is the means to manipulate large or -- unbounded streams of data without requiring the entire sequence to be -- resident in memory. To take advantage of this you have to write your -- functions in a streaming style, e.g. classic pipeline composition. The -- default I/O chunk size is 32k, which should be good in most -- circumstances. -- -- Some operations, such as concat, append, -- reverse and cons, have better complexity than their -- Data.ByteStream equivalents, due to optimisations resulting -- from the list spine structure. For other operations streaming, like -- lazy, ByteStreams are usually within a few percent of strict ones. -- -- This module is intended to be imported qualified, to avoid -- name clashes with Prelude functions. eg. -- --
-- import qualified Bio.Streaming.Bytes as B ---- -- Original GHC implementation by Bryan O'Sullivan. Rewritten to use -- UArray by Simon Marlow. Rewritten to support slices and use -- ForeignPtr by David Roundy. Rewritten again and extended by Don -- Stewart and Duncan Coutts. Lazy variant by Duncan Coutts and Don -- Stewart. Streaming variant by Michael Thompson, following the ideas of -- Gabriel Gonzales' pipes-bytestring Adapted for use in biohazard by Udo -- Stenzel. module Bio.Streaming.Bytes -- | A space-efficient representation of a succession of Word8 -- vectors, supporting many efficient operations. -- -- An effectful ByteStream contains 8-bit bytes, or by using -- certain operations can be interpreted as containing 8-bit characters. -- It also contains an offset, which will be needed to track the virtual -- offsets in the BGZF decode. data ByteStream m r Empty :: r -> ByteStream m r Chunk :: {-# UNPACK #-} !Bytes -> {-# UNPACK #-} !Int64 -> ByteStream m r -> ByteStream m r Go :: m (ByteStream m r) -> ByteStream m r -- | O(1) The empty ByteStream -- i.e. return () -- Note that ByteStream m w is generally a monoid for monoidal -- values of w, like () empty :: ByteStream m () -- | O(1) Yield a Word8 as a minimal ByteStream singleton :: Word8 -> ByteStream m () -- | O(c) Transmute a pseudo-pure lazy bytestring to its -- representation as a monadic stream of chunks. -- --
-- >>> Q.putStrLn $ Q.fromLazy "hi" -- hi -- -- >>> Q.fromLazy "hi" -- Chunk "hi" (Empty (())) -- note: a 'show' instance works in the identity monad -- -- >>> Q.fromLazy $ BL.fromChunks ["here", "are", "some", "chunks"] -- Chunk "here" (Chunk "are" (Chunk "some" (Chunk "chunks" (Empty (()))))) --fromLazy :: LazyBytes -> ByteStream m () -- | O(c) Converts a stream of strict bytestrings into a byte -- stream. fromChunks :: Monad m => Stream (Of Bytes) m r -> ByteStream m r -- | O(n) Convert an effectful byte stream into a single lazy -- ByteStream with the same internal chunk structure, retaining -- the original return value. -- -- This is the canonical way of breaking streaming (toStrict and -- the like are far more demonic). Essentially one is dividing the -- interleaved layers of effects and bytes into one immense layer of -- effects, followed by the memory of the succession of bytes. -- -- Because one preserves the return value, toLazy is a suitable -- argument for mapped -- --
-- B.mapped Q.toLazy :: Stream (ByteStream m) m r -> Stream (Of LazyBytes) m r ---- --
-- >>> Q.toLazy "hello" -- "hello" :> () -- -- >>> B.toListM $ traverses Q.toLazy $ Q.lines "one\ntwo\nthree\nfour\nfive\n" -- ["one","two","three","four","five",""] -- [LazyBytes] --toLazy :: Monad m => ByteStream m r -> m (Of LazyBytes r) -- | O(n) Convert a monadic byte stream into a single strict -- ByteStream, retaining the return value of the original pair. -- This operation is for use with mapped. -- --
-- mapped R.toStrict :: Monad m => Stream (ByteStream m) m r -> Stream (Of ByteStream) m r ---- -- It is subject to all the objections one makes to Data.ByteStream.Lazy -- toStrict; all of these are devastating. toStrict :: Monad m => ByteStream m r -> m (Of Bytes r) -- | Perform the effects contained in an effectful bytestring, ignoring the -- bytes. effects :: Monad m => ByteStream m r -> m r -- | Reconceive an effect that results in an effectful bytestring as an -- effectful bytestring. Compare Streaming.mwrap. The closes equivalent -- of -- --
-- >>> Streaming.wrap :: f (Stream f m r) -> Stream f m r ---- -- is here consChunk. mwrap is the smart constructor -- for the internal Go constructor. mwrap :: m (ByteStream m r) -> ByteStream m r -- | O(1) cons is analogous to '(:)' for lists. cons :: Word8 -> ByteStream m r -> ByteStream m r -- | O(1) Extract the head and tail of a ByteStream, or its -- return value if it is empty. This is the 'natural' uncons for an -- effectful byte stream. nextByte :: Monad m => ByteStream m r -> m (Either r (Word8, ByteStream m r)) nextByteOff :: Monad m => ByteStream m r -> m (Either r (Word8, Int64, ByteStream m r)) -- | break p is equivalent to span (not . -- p). break :: Monad m => (Word8 -> Bool) -> ByteStream m r -> ByteStream m (ByteStream m r) -- | O(n/c) drop n xs returns the suffix of -- xs after the first n elements, or [] if -- n > length xs. -- --
-- >>> Q.putStrLn $ Q.drop 6 "Wisconsin" -- sin -- -- >>> Q.putStrLn $ Q.drop 16 "Wisconsin" ---- --
-- >>> --drop :: Monad m => Int64 -> ByteStream m r -> ByteStream m r -- | dropWhile p xs returns the suffix remaining after -- takeWhile p xs. dropWhile :: Monad m => (Word8 -> Bool) -> ByteStream m r -> ByteStream m r -- | O(n/c) splitAt n xs is equivalent to -- (take n xs, drop n xs). -- --
-- >>> rest <- Q.putStrLn $ Q.splitAt 3 "therapist is a danger to good hyphenation, as Knuth notes" -- the -- -- >>> Q.putStrLn $ Q.splitAt 19 rest -- rapist is a danger --splitAt :: Monad m => Int64 -> ByteStream m r -> ByteStream m (ByteStream m r) -- | Strictly splits off a piece. This breaks streaming, so reserve its use -- for small strings or when conversion to strict Bytes is needed -- anyway. splitAt' :: Monad m => Int -> ByteStream m r -> m (Of Bytes (ByteStream m r)) trim :: Monad m => Int64 -> ByteStream m () -> ByteStream m () -- | Turns a ByteStream into a connected stream of ByteStreams that divide -- at newline characters. The resulting strings do not contain newlines. -- This is the genuinely streaming lines which only breaks chunks, -- and thus never increases the use of memory. -- -- Because ByteStreams are usually read in binary mode, with no -- line ending conversion, this function recognizes both \n and -- \r\n endings (regardless of the current platform). lines :: Monad m => ByteStream m r -> Stream (ByteStream m) m r -- | Turns a ByteStream into a stream of strict Bytes that -- divide at newline characters. The resulting strings do not contain -- newlines. This will cost memory if the lines are very long, and it -- does not recognize DOS line endings. lines' :: Monad m => ByteStream m r -> Stream (Of Bytes) m r -- | O(n) Concatenate a stream of byte streams. concat :: Monad m => Stream (ByteStream m) m r -> ByteStream m r toByteStream :: MonadIO m => Builder -> ByteStream m () -- | Take a builder and convert it to a genuine streaming bytestring, using -- a specific allocation strategy. toByteStreamWith :: MonadIO m => AllocationStrategy -> Builder -> ByteStream m () concatBuilders :: Stream (Of Builder) IO () -> Builder withOutputFile :: (MonadIO m, MonadMask m) => FilePath -> (Handle -> m a) -> m a -- | Writes a ByteStream to a file. Actually writes to a temporary -- file and renames it on successful completion. The filename "-" causes -- it to write to stdout instead. writeFile :: (MonadIO m, MonadMask m) => FilePath -> ByteStream m r -> m r -- | Read entire handle contents lazily into a ByteStream. -- Chunks are read on demand, using the default chunk size. -- -- Note: the Handle should be placed in binary mode with -- hSetBinaryMode for hGetContents to work correctly. hGetContents :: MonadIO m => Handle -> ByteStream m () -- | Read entire handle contents lazily into a ByteStream. -- Chunks are read on demand, in at most k-sized chunks. It does -- not block waiting for a whole k-sized chunk, so if less than -- k bytes are available then they will be returned immediately -- as a smaller chunk. -- -- The handle is closed on EOF. -- -- Note: the Handle should be placed in binary mode with -- hSetBinaryMode for hGetContentsN to work correctly. hGetContentsN :: MonadIO m => Int -> Handle -> ByteStream m () -- | Outputs a ByteStream to the specified Handle. hPut :: MonadIO m => Handle -> ByteStream m r -> m r nextChunk :: Monad m => ByteStream m r -> m (Either r (Bytes, ByteStream m r)) nextChunkOff :: Monad m => ByteStream m r -> m (Either r (Bytes, Int64, ByteStream m r)) -- | Smart constructor for Chunk. consChunk :: Bytes -> ByteStream m r -> ByteStream m r consChunkOff :: Bytes -> Int64 -> ByteStream m r -> ByteStream m r -- | Yield-style smart constructor for Chunk. chunk :: Bytes -> ByteStream m () copy :: Monad m => ByteStream m r -> ByteStream (ByteStream m) r mapChunksM_ :: Monad m => (Bytes -> m ()) -> ByteStream m r -> m r -- | Compresses a byte stream using GZip with default parameters. gzip :: MonadIO m => ByteStream m r -> ByteStream m r -- | Decompresses GZip if present. If any GZip stream is found, all such -- streams are decompressed and any remaining data is discarded. Else, -- the input is returned unchanged. If the input is BGZF, the result will -- contain meaningful virtual offsets. If the input contains exactly one -- GZip stream, the result will have meaningfull offsets into the -- uncompressed data. Else, the offsets will be bogus. gunzip :: MonadIO m => ByteStream m r -> ByteStream m r -- | Checks if the input is GZip at all, and runs gunzip if it is. If it -- isn't, it runs k on the input. gunzipWith :: MonadIO m => (ByteStream m r -> ByteStream m r) -> ByteStream m r -> ByteStream m r instance GHC.Base.Monad m => GHC.Base.Monad (Bio.Streaming.Bytes.ByteStream m) instance GHC.Base.Monad m => GHC.Base.Functor (Bio.Streaming.Bytes.ByteStream m) instance GHC.Base.Monad m => GHC.Base.Applicative (Bio.Streaming.Bytes.ByteStream m) instance Control.Monad.IO.Class.MonadIO m => Control.Monad.IO.Class.MonadIO (Bio.Streaming.Bytes.ByteStream m) instance Control.Monad.Trans.Class.MonadTrans Bio.Streaming.Bytes.ByteStream instance (r Data.Type.Equality.~ ()) => Data.String.IsString (Bio.Streaming.Bytes.ByteStream m r) instance (m Data.Type.Equality.~ Data.Functor.Identity.Identity, GHC.Show.Show r) => GHC.Show.Show (Bio.Streaming.Bytes.ByteStream m r) instance (GHC.Base.Semigroup r, GHC.Base.Monad m) => GHC.Base.Semigroup (Bio.Streaming.Bytes.ByteStream m r) instance (GHC.Base.Semigroup r, GHC.Base.Monoid r, GHC.Base.Monad m) => GHC.Base.Monoid (Bio.Streaming.Bytes.ByteStream m r) -- | Parsers for use with ByteStreams. module Bio.Streaming.Parse data Parser r m a data ParseError ParseError :: [String] -> String -> ParseError [errorContexts] :: ParseError -> [String] [errorMessage] :: ParseError -> String data EofException EofException :: EofException parse :: Monad m => (Int64 -> Parser r m a) -> ByteStream m r -> m (Either SomeException (Either r (a, ByteStream m r))) parseIO :: MonadIO m => (Int64 -> Parser r m a) -> ByteStream m r -> m (Either r (a, ByteStream m r)) parseM :: MonadThrow m => (Int64 -> Parser r m a) -> ByteStream m r -> m (Either r (a, ByteStream m r)) abortParse :: Monad m => Parser r m a isFinished :: Monad m => Parser r m Bool drop :: Monad m => Int -> Parser r m () dropLine :: Monad m => Parser r m () getByte :: Monad m => Parser r m Word8 getString :: Monad m => Int -> Parser r m ByteString getWord32 :: Monad m => Parser r m Word32 getWord64 :: Monad m => Parser r m Word64 isolate :: Monad m => Int -> Parser (ByteStream m r) m a -> Parser r m a atto :: Monad m => Parser a -> Parser r m a instance GHC.Show.Show Bio.Streaming.Parse.EofException instance GHC.Show.Show Bio.Streaming.Parse.ParseError instance GHC.Exception.Type.Exception Bio.Streaming.Parse.EofException instance GHC.Exception.Type.Exception Bio.Streaming.Parse.ParseError instance GHC.Base.Functor (Bio.Streaming.Parse.Parser r m) instance GHC.Base.Applicative (Bio.Streaming.Parse.Parser r m) instance GHC.Base.Monad (Bio.Streaming.Parse.Parser r m) instance Control.Monad.IO.Class.MonadIO m => Control.Monad.IO.Class.MonadIO (Bio.Streaming.Parse.Parser r m) instance Control.Monad.Trans.Class.MonadTrans (Bio.Streaming.Parse.Parser r) instance Control.Monad.Catch.MonadThrow (Bio.Streaming.Parse.Parser r m) module Bio.Bam.Header data BamMeta BamMeta :: !BamHeader -> !Refs -> [Fix BamPG] -> [(BamKey, BamOtherShit)] -> [Bytes] -> BamMeta [meta_hdr] :: BamMeta -> !BamHeader [meta_refs] :: BamMeta -> !Refs [meta_pgs] :: BamMeta -> [Fix BamPG] [meta_other_shit] :: BamMeta -> [(BamKey, BamOtherShit)] [meta_comment] :: BamMeta -> [Bytes] parseBamMeta :: Parser BamMeta -- | Creates the textual form of Bam meta data. -- -- Formatting is straight forward, only program lines are a bit involved. -- Our multiple chains may lead to common nodes, and we do not want to -- print multiple identical lines. At the same time, we may need to print -- multiple different lines that carry the same id. The solution is to -- memoize printed lines, and to reuse their identity if an identical -- line is needed. When printing a line, it gets its preferred -- identifier, but if it's already taken, a new identifier is made up by -- first removing any trailing number and then by appending numeric -- suffixes. showBamMeta :: BamMeta -> Builder -- | Adds a new program line to a header. The new entry is (arbitrarily) -- prepended to the first existing chain, or forms a new singleton chain -- if none exists. addPG :: Maybe Version -> IO (BamMeta -> BamMeta) -- | Exactly two characters, for the "named" fields in bam. newtype BamKey BamKey :: Word16 -> BamKey data BamHeader BamHeader :: (Int, Int) -> BamSorting -> BamOtherShit -> BamHeader [hdr_version] :: BamHeader -> (Int, Int) [hdr_sorting] :: BamHeader -> BamSorting [hdr_other_shit] :: BamHeader -> BamOtherShit data BamSQ BamSQ :: Bytes -> Int -> BamOtherShit -> BamSQ [sq_name] :: BamSQ -> Bytes [sq_length] :: BamSQ -> Int [sq_other_shit] :: BamSQ -> BamOtherShit -- | Possible sorting orders from bam header. Thanks to samtools, which -- doesn't declare sorted files properly, we have to have the stupid -- Unknown state, too. data BamSorting -- | undeclared sort order Unknown :: BamSorting -- | definitely not sorted Unsorted :: BamSorting -- | grouped by query name Grouped :: BamSorting -- | sorted by query name Queryname :: BamSorting -- | sorted by coordinate Coordinate :: BamSorting type BamOtherShit = [(BamKey, Bytes)] -- | Reference sequence in Bam Bam enumerates the reference sequences and -- then sorts by index. We need to track that index if we want to -- reproduce the sorting order. newtype Refseq Refseq :: Word32 -> Refseq [unRefseq] :: Refseq -> Word32 -- | The invalid Refseq. Bam uses this value to encode a missing reference -- sequence. invalidRefseq :: Refseq -- | Tests whether a reference sequence is valid. Returns true unless the -- the argument equals invalidRefseq. isValidRefseq :: Refseq -> Bool -- | The invalid position. Bam uses this value to encode a missing -- position. invalidPos :: Int -- | Tests whether a position is valid. Returns true unless the the -- argument equals invalidPos. isValidPos :: Int -> Bool unknownMapq :: Int isKnownMapq :: Int -> Bool -- | A list of reference sequences. newtype Refs Refs :: Vector BamSQ -> Refs [unRefs] :: Refs -> Vector BamSQ getRef :: Refs -> Refseq -> BamSQ -- | Compares two sequence names the way samtools does. samtools sorts by -- "strnum_cmp": -- --
-- atomically :: STM a -> IO a ---- -- is used to run STM transactions atomically. So, by specializing -- the types of atomically and join to -- --
-- atomically :: STM (IO b) -> IO (IO b) -- join :: IO (IO b) -> IO b ---- -- we can compose them as -- --
-- join . atomically :: STM (IO b) -> IO b ---- -- to run an STM transaction and the IO action it returns. join :: Monad m => m (m a) -> m a -- | 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 -- | Right-to-left composition of functors. The composition of applicative -- functors is always applicative, but the composition of monads is not -- always a monad. newtype Compose (f :: k -> Type) (g :: k1 -> k) (a :: k1) :: forall k k1. () => k -> Type -> k1 -> k -> k1 -> Type Compose :: f (g a) -> Compose [getCompose] :: Compose -> f (g a) infixr 9 `Compose` infixr 9 `Compose` -- | Lifted sum of functors. data Sum (f :: k -> Type) (g :: k -> Type) (a :: k) :: forall k. () => k -> Type -> k -> Type -> k -> Type InL :: f a -> Sum InR :: g a -> Sum -- | A bifunctor is a type constructor that takes two type arguments and is -- a functor in both arguments. That is, unlike with -- Functor, a type constructor such as Either does not need -- to be partially applied for a Bifunctor instance, and the -- methods in this class permit mapping functions over the Left -- value or the Right value, or both at the same time. -- -- Formally, the class Bifunctor represents a bifunctor from -- Hask -> Hask. -- -- Intuitively it is a bifunctor where both the first and second -- arguments are covariant. -- -- You can define a Bifunctor by either defining bimap or -- by defining both first and second. -- -- If you supply bimap, you should ensure that: -- --
-- bimap id id ≡ id ---- -- If you supply first and second, ensure: -- --
-- first id ≡ id -- second id ≡ id ---- -- If you supply both, you should also ensure: -- --
-- bimap f g ≡ first f . second g ---- -- These ensure by parametricity: -- --
-- bimap (f . g) (h . i) ≡ bimap f h . bimap g i -- first (f . g) ≡ first f . first g -- second (f . g) ≡ second f . second g --class Bifunctor (p :: Type -> Type -> Type) -- | Map over both arguments at the same time. -- --
-- bimap f g ≡ first f . second g ---- --
-- >>> bimap toUpper (+1) ('j', 3)
-- ('J',4)
--
--
-- -- >>> bimap toUpper (+1) (Left 'j') -- Left 'J' ---- --
-- >>> bimap toUpper (+1) (Right 3) -- Right 4 --bimap :: Bifunctor p => (a -> b) -> (c -> d) -> p a c -> p b d -- | Map covariantly over the first argument. -- --
-- first f ≡ bimap f id ---- --
-- >>> first toUpper ('j', 3)
-- ('J',3)
--
--
-- -- >>> first toUpper (Left 'j') -- Left 'J' --first :: Bifunctor p => (a -> b) -> p a c -> p b c -- | Map covariantly over the second argument. -- --
-- second ≡ bimap id ---- --
-- >>> second (+1) ('j', 3)
-- ('j',4)
--
--
-- -- >>> second (+1) (Right 3) -- Right 4 --second :: Bifunctor p => (b -> c) -> p a b -> p a c -- | Monads in which IO computations may be embedded. Any monad -- built by applying a sequence of monad transformers to the IO -- monad will be an instance of this class. -- -- Instances should satisfy the following laws, which state that -- liftIO is a transformer of monads: -- -- class Monad m => MonadIO (m :: Type -> Type) -- | Lift a computation from the IO monad. liftIO :: MonadIO m => IO a -> m a -- | Identity functor and monad. (a non-strict monad) newtype Identity a Identity :: a -> Identity a [runIdentity] :: Identity a -> a -- | void value discards or ignores the result of -- evaluation, such as the return value of an IO action. -- --
-- >>> void Nothing -- Nothing -- -- >>> void (Just 3) -- Just () ---- -- Replace the contents of an Either Int -- Int with unit, resulting in an Either -- Int '()': -- --
-- >>> void (Left 8675309) -- Left 8675309 -- -- >>> void (Right 8675309) -- Right () ---- -- Replace every element of a list with unit: -- --
-- >>> void [1,2,3] -- [(),(),()] ---- -- Replace the second element of a pair with unit: -- --
-- >>> void (1,2) -- (1,()) ---- -- Discard the result of an IO action: -- --
-- >>> mapM print [1,2] -- 1 -- 2 -- [(),()] -- -- >>> void $ mapM print [1,2] -- 1 -- 2 --void :: Functor f => f a -> f () -- | Promote a function to a monad, scanning the monadic arguments from -- left to right. For example, -- --
-- liftM2 (+) [0,1] [0,2] = [0,2,1,3] -- liftM2 (+) (Just 1) Nothing = Nothing --liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r -- | Promote a function to a monad. liftM :: Monad m => (a1 -> r) -> m a1 -> m r -- | Lift a ternary function to actions. liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d -- | A monoid on applicative functors. -- -- If defined, some and many should be the least solutions -- of the equations: -- -- class Applicative f => Alternative (f :: Type -> Type) -- | An associative binary operation (<|>) :: Alternative f => f a -> f a -> f a infixl 3 <|> -- | The class of monad transformers. Instances should satisfy the -- following laws, which state that lift is a monad -- transformation: -- -- class MonadTrans (t :: Type -> Type -> Type -> Type) -- | Lift a computation from the argument monad to the constructed monad. lift :: (MonadTrans t, Monad m) => m a -> t m a chunksOf :: (Monad m, Functor f) => Int -> Stream f m r -> Stream (Stream f m) m r concats :: (Monad m, Functor f) => Stream (Stream f m) m r -> Stream f m r cutoff :: (Monad m, Functor f) => Int -> Stream f m r -> Stream f m (Maybe r) decompose :: (Monad m, Functor f) => Stream (Compose m f) m r -> Stream f m r delays :: (MonadIO m, Applicative f) => Double -> Stream f m r destroy :: (Functor f, Monad m) => Stream f m r -> (f b -> b) -> (m b -> b) -> (r -> b) -> b distribute :: (Monad m, Functor f, MonadTrans t, MFunctor t, Monad (t (Stream f m))) => Stream f (t m) r -> t (Stream f m) r effect :: (Monad m, Functor f) => m (Stream f m r) -> Stream f m r expand :: (Monad m, Functor f) => (forall a b. () => (g a -> b) -> f a -> h b) -> Stream f m r -> Stream g (Stream h m) r expandPost :: (Monad m, Functor g) => (forall a b. () => (g a -> b) -> f a -> h b) -> Stream f m r -> Stream g (Stream h m) r groups :: (Monad m, Functor f, Functor g) => Stream (Sum f g) m r -> Stream (Sum (Stream f m) (Stream g m)) m r hoistUnexposed :: (Monad m, Functor f) => (forall a. () => m a -> n a) -> Stream f m r -> Stream f n r inspect :: Monad m => Stream f m r -> m (Either r (f (Stream f m r))) intercalates :: (Monad m, Monad (t m), MonadTrans t) => t m x -> Stream (t m) m r -> t m r interleaves :: (Monad m, Applicative h) => Stream h m r -> Stream h m r -> Stream h m r iterT :: (Functor f, Monad m) => (f (m a) -> m a) -> Stream f m a -> m a iterTM :: (Functor f, Monad m, MonadTrans t, Monad (t m)) => (f (t m a) -> t m a) -> Stream f m a -> t m a maps :: (Monad m, Functor f) => (forall x. () => f x -> g x) -> Stream f m r -> Stream g m r mapsM :: (Monad m, Functor f) => (forall x. () => f x -> m (g x)) -> Stream f m r -> Stream g m r mapsMPost :: (Monad m, Functor g) => (forall x. () => f x -> m (g x)) -> Stream f m r -> Stream g m r mapsM_ :: (Functor f, Monad m) => (forall x. () => f x -> m x) -> Stream f m r -> m r mapsPost :: (Monad m, Functor g) => (forall x. () => f x -> g x) -> Stream f m r -> Stream g m r never :: (Monad m, Applicative f) => Stream f m r repeats :: (Monad m, Functor f) => f () -> Stream f m r repeatsM :: (Monad m, Functor f) => m (f ()) -> Stream f m r replicates :: (Monad m, Functor f) => Int -> f () -> Stream f m () run :: Monad m => Stream m m r -> m r separate :: (Monad m, Functor f, Functor g) => Stream (Sum f g) m r -> Stream f (Stream g m) r splitsAt :: (Monad m, Functor f) => Int -> Stream f m r -> Stream f m (Stream f m r) streamBuild :: () => (forall b. () => (r -> b) -> (m b -> b) -> (f b -> b) -> b) -> Stream f m r streamFold :: (Functor f, Monad m) => (r -> b) -> (m b -> b) -> (f b -> b) -> Stream f m r -> b takes :: (Monad m, Functor f) => Int -> Stream f m r -> Stream f m () unfold :: (Monad m, Functor f) => (s -> m (Either r (f s))) -> s -> Stream f m r unseparate :: (Monad m, Functor f, Functor g) => Stream f (Stream g m) r -> Stream (Sum f g) m r untilJust :: (Monad m, Applicative f) => m (Maybe r) -> Stream f m r unzips :: (Monad m, Functor f, Functor g) => Stream (Compose f g) m r -> Stream f (Stream g m) r wrap :: (Monad m, Functor f) => f (Stream f m r) -> Stream f m r yields :: (Monad m, Functor f) => f r -> Stream f m r zips :: (Monad m, Functor f, Functor g) => Stream f m r -> Stream g m r -> Stream (Compose f g) m r zipsWith :: (Monad m, Functor h) => (forall x y. () => f x -> g y -> h (x, y)) -> Stream f m r -> Stream g m r -> Stream h m r zipsWith' :: Monad m => (forall x y p. () => (x -> y -> p) -> f x -> g y -> h p) -> Stream f m r -> Stream g m r -> Stream h m r lazily :: () => Of a b -> (a, b) mapped :: (Monad m, Functor f) => (forall x. () => f x -> m (g x)) -> Stream f m r -> Stream g m r mappedPost :: (Monad m, Functor g) => (forall x. () => f x -> m (g x)) -> Stream f m r -> Stream g m r strictly :: () => (a, b) -> Of a b class MFunctor (t :: Type -> Type -> k -> Type) hoist :: (MFunctor t, Monad m) => (forall a. () => m a -> n a) -> t m b -> t n b class (MFunctor t, MonadTrans t) => MMonad (t :: Type -> Type -> Type -> Type) embed :: (MMonad t, Monad n) => (forall a. () => m a -> t n a) -> t m b -> t n b data Of a b (:>) :: !a -> b -> Of a b data Stream (f :: Type -> Type) (m :: Type -> Type) r each :: (Monad m, Foldable f) => f a -> Stream (Of a) m () module Bio.Streaming.Furrow -- | A tiny stream that can be afforded to incrementally. -- -- The streaming abstraction works fine if multiple sources feed into a -- small constant number of functions, but fails if there is an -- unpredictable number of such consumers. In that case, -- evertStream should be used to turn each consumer into a -- Furrow. It's then possible to incrementally afford stuff -- to each Furrow in a collection in a simple loop. To get the -- final value, drain each Furrow. newtype Furrow a m r Furrow :: Stream ((->) (Maybe a)) m r -> Furrow a m r -- | Turns a function that consumes a stream into a furrow. Idea and some -- code stolen from "streaming-eversion". evertStream :: Monad m => (Stream (Of a) (Furrow a m) () -> Furrow a m b) -> Furrow a m b afford :: Monad m => Furrow a m b -> a -> m (Furrow a m b) drain :: Monad m => Furrow a m b -> m b instance Control.Monad.Morph.MMonad (Bio.Streaming.Furrow.Furrow a) instance Control.Monad.Morph.MFunctor (Bio.Streaming.Furrow.Furrow a) instance Control.Monad.IO.Class.MonadIO m => Control.Monad.IO.Class.MonadIO (Bio.Streaming.Furrow.Furrow a m) instance Control.Monad.Trans.Class.MonadTrans (Bio.Streaming.Furrow.Furrow a) instance GHC.Base.Monad m => GHC.Base.Monad (Bio.Streaming.Furrow.Furrow a m) instance GHC.Base.Monad m => GHC.Base.Applicative (Bio.Streaming.Furrow.Furrow a m) instance GHC.Base.Monad m => GHC.Base.Functor (Bio.Streaming.Furrow.Furrow a m) instance Control.Monad.Catch.MonadThrow m => Control.Monad.Catch.MonadThrow (Bio.Streaming.Furrow.Furrow a m) -- | Buffer builder to assemble Bgzf blocks. The idea is to serialize stuff -- (BAM and BCF) into a buffer, then bgzf chunks from the buffer. We use -- a large buffer, and we always make sure there is plenty of space in it -- (to avoid redundant checks). module Bio.Streaming.Bgzf -- | Decompresses a bgzip stream. Individual chunks are decompressed in -- parallel. Leftovers are discarded (some compressed HETFA files appear -- to have junk at the end). bgunzip :: MonadIO m => ByteStream m r -> ByteStream m r getBgzfHdr :: Monad m => ByteStream m r -> m (Maybe Int, ByteString, ByteStream m r) -- | We manage a large buffer (multiple megabytes), of which we fill an -- initial portion. We remember the size, the used part, and two marks -- where we later fill in sizes for the length prefixed BAM or BCF -- records. We move the buffer down when we yield a piece downstream, and -- when we run out of space, we simply move to a new buffer. Garbage -- collection should take care of the rest. Unused mark must be -- set to (maxBound::Int) so it doesn't interfere with flushing. data BB BB :: {-# UNPACK #-} !ForeignPtr Word8 -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int -> BB [buffer] :: BB -> {-# UNPACK #-} !ForeignPtr Word8 [size] :: BB -> {-# UNPACK #-} !Int [off] :: BB -> {-# UNPACK #-} !Int [used] :: BB -> {-# UNPACK #-} !Int [mark] :: BB -> {-# UNPACK #-} !Int [mark2] :: BB -> {-# UNPACK #-} !Int -- | Creates a buffer. newBuffer :: Int -> IO BB fillBuffer :: BB -> BgzfTokens -> IO (BB, BgzfTokens) -- | Creates a new buffer, copying the active content from an old one, with -- higher capacity. The size of the new buffer is twice the free space in -- the old buffer, but at least minsz. expandBuffer :: Int -> BB -> IO BB -- | Expand a chain of tokens into a buffer, sending finished pieces -- downstream as soon as possible. encodeBgzf :: MonadIO m => Int -> Stream (Of (Endo BgzfTokens)) m b -> ByteStream m b -- | Things we are able to encode. Taking inspiration from -- binary-serialise-cbor, we define these as a lazy list-like thing and -- consume it in a interpreter. data BgzfTokens TkWord32 :: {-# UNPACK #-} !Word32 -> BgzfTokens -> BgzfTokens TkWord16 :: {-# UNPACK #-} !Word16 -> BgzfTokens -> BgzfTokens TkWord8 :: {-# UNPACK #-} !Word8 -> BgzfTokens -> BgzfTokens TkFloat :: {-# UNPACK #-} !Float -> BgzfTokens -> BgzfTokens TkDouble :: {-# UNPACK #-} !Double -> BgzfTokens -> BgzfTokens TkString :: {-# UNPACK #-} !ByteString -> BgzfTokens -> BgzfTokens TkDecimal :: {-# UNPACK #-} !Int -> BgzfTokens -> BgzfTokens TkSetMark :: BgzfTokens -> BgzfTokens TkEndRecord :: BgzfTokens -> BgzfTokens TkEndRecordPart1 :: BgzfTokens -> BgzfTokens TkEndRecordPart2 :: BgzfTokens -> BgzfTokens TkEnd :: BgzfTokens TkBclSpecial :: !BclArgs -> BgzfTokens -> BgzfTokens TkLowLevel :: {-# UNPACK #-} !Int -> (BB -> IO BB) -> BgzfTokens -> BgzfTokens data BclArgs BclArgs :: BclSpecialType -> {-# UNPACK #-} !Vector Word8 -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int -> BclArgs data BclSpecialType BclNucsBin :: BclSpecialType BclNucsAsc :: BclSpecialType BclNucsAscRev :: BclSpecialType BclNucsWide :: BclSpecialType BclQualsBin :: BclSpecialType BclQualsAsc :: BclSpecialType BclQualsAscRev :: BclSpecialType loop_dec_int :: Ptr Word8 -> Int -> IO Int loop_bcl_special :: Ptr Word8 -> BclArgs -> IO Int module Bio.Bam.Regions data Region Region :: !Refseq -> !Int -> !Int -> Region [refseq] :: Region -> !Refseq [start] :: Region -> !Int [end] :: Region -> !Int -- | A subset of a genome. The idea is to map the reference sequence -- (represented by its number) to a Subseqeunce. newtype Regions Regions :: IntMap Subsequence -> Regions -- | A mostly contiguous subset of a sequence, stored as a set of -- non-overlapping intervals in an IntMap from start position to -- end position (half-open intervals, naturally). newtype Subsequence Subsequence :: IntMap Int -> Subsequence toList :: Regions -> [(Refseq, Subsequence)] fromList :: [Region] -> Regions overlaps :: Int -> Int -> Subsequence -> Bool instance GHC.Show.Show Bio.Bam.Regions.Regions instance GHC.Show.Show Bio.Bam.Regions.Subsequence instance GHC.Show.Show Bio.Bam.Regions.Region instance GHC.Classes.Ord Bio.Bam.Regions.Region instance GHC.Classes.Eq Bio.Bam.Regions.Region -- | Parsers and Printers for BAM and SAM. module Bio.Bam.Rec -- | Bam record in its native encoding along with virtual address. data BamRaw -- | Smart constructor. Makes sure we got a at least a full record. bamRaw :: Int64 -> Bytes -> BamRaw virt_offset :: BamRaw -> Int64 raw_data :: BamRaw -> Bytes -- | internal representation of a BAM record data BamRec BamRec :: Bytes -> Int -> Refseq -> Int -> Qual -> Vector Cigar -> Refseq -> Int -> Int -> Vector_Nucs_half Nucleotides -> Vector Qual -> Extensions -> Int64 -> BamRec [b_qname] :: BamRec -> Bytes [b_flag] :: BamRec -> Int [b_rname] :: BamRec -> Refseq [b_pos] :: BamRec -> Int [b_mapq] :: BamRec -> Qual [b_cigar] :: BamRec -> Vector Cigar [b_mrnm] :: BamRec -> Refseq [b_mpos] :: BamRec -> Int [b_isize] :: BamRec -> Int [b_seq] :: BamRec -> Vector_Nucs_half Nucleotides [b_qual] :: BamRec -> Vector Qual [b_exts] :: BamRec -> Extensions -- | virtual offset for indexing purposes [b_virtual_offset] :: BamRec -> Int64 unpackBam :: BamRaw -> BamRec nullBamRec :: BamRec getMd :: BamRec -> Maybe [MdOp] -- | Cigar line in BAM coding Bam encodes an operation and a length into a -- single integer, we keep those integers in an array. data Cigar (:*) :: !CigOp -> !Int -> Cigar infix 9 :* data CigOp Mat :: CigOp Ins :: CigOp Del :: CigOp Nop :: CigOp SMa :: CigOp HMa :: CigOp Pad :: CigOp -- | Extracts the aligned length from a cigar line. This gives the length -- of an alignment as measured on the reference, which is different from -- the length on the query or the length of the alignment. alignedLength :: Vector v Cigar => v Cigar -> Int -- | A nucleotide base in an alignment. Experience says we're dealing with -- Ns and gaps all the type, so purity be damned, they are included as if -- they were real bases. -- -- To allow Nucleotidess to be unpacked and incorporated into -- containers, we choose to represent them the same way as the BAM file -- format: as a 4 bit wide field. Gaps are encoded as 0 where they make -- sense, N is 15. The contained Word8 is guaranteed to be 0..15. newtype Nucleotides Ns :: Word8 -> Nucleotides [unNs] :: Nucleotides -> Word8 -- | A vector that packs two Nucleotides into one byte, just like -- Bam does. data Vector_Nucs_half a -- | A collection of extension fields. A BamKey is actually two -- ASCII characters. type Extensions = [(BamKey, Ext)] data Ext Int :: Int -> Ext Float :: Float -> Ext Text :: Bytes -> Ext Bin :: Bytes -> Ext Char :: Word8 -> Ext IntArr :: Vector Int -> Ext FloatArr :: Vector Float -> Ext extAsInt :: Int -> BamKey -> BamRec -> Int extAsString :: BamKey -> BamRec -> Bytes setQualFlag :: Char -> BamRec -> BamRec -- | Deletes all occurences of some extension field. deleteE :: BamKey -> Extensions -> Extensions -- | Blindly inserts an extension field. This can create duplicates (and -- there is no telling how other tools react to that). insertE :: BamKey -> Ext -> Extensions -> Extensions -- | Deletes all occurences of an extension field, then inserts it with a -- new value. This is safer than insertE, but also more expensive. updateE :: BamKey -> Ext -> Extensions -> Extensions -- | Adjusts a named extension by applying a function. adjustE :: (Ext -> Ext) -> BamKey -> Extensions -> Extensions isPaired :: BamRec -> Bool isProperlyPaired :: BamRec -> Bool isUnmapped :: BamRec -> Bool isMateUnmapped :: BamRec -> Bool isReversed :: BamRec -> Bool isMateReversed :: BamRec -> Bool isFirstMate :: BamRec -> Bool isSecondMate :: BamRec -> Bool isAuxillary :: BamRec -> Bool isSecondary :: BamRec -> Bool isFailsQC :: BamRec -> Bool isDuplicate :: BamRec -> Bool isSupplementary :: BamRec -> Bool isTrimmed :: BamRec -> Bool isMerged :: BamRec -> Bool isAlternative :: BamRec -> Bool isExactIndex :: BamRec -> Bool type_mask :: Int instance GHC.Show.Show Bio.Bam.Rec.BamRec instance GHC.Classes.Ord Bio.Bam.Rec.Ext instance GHC.Classes.Eq Bio.Bam.Rec.Ext instance GHC.Show.Show Bio.Bam.Rec.Ext instance GHC.Classes.Ord Bio.Bam.Rec.Cigar instance GHC.Classes.Eq Bio.Bam.Rec.Cigar instance GHC.Arr.Ix Bio.Bam.Rec.CigOp instance GHC.Enum.Bounded Bio.Bam.Rec.CigOp instance GHC.Show.Show Bio.Bam.Rec.CigOp instance GHC.Enum.Enum Bio.Bam.Rec.CigOp instance GHC.Classes.Ord Bio.Bam.Rec.CigOp instance GHC.Classes.Eq Bio.Bam.Rec.CigOp instance Data.Vector.Generic.Base.Vector Bio.Bam.Rec.Vector_Nucs_half Bio.Base.Nucleotides instance Data.Vector.Generic.Mutable.Base.MVector Bio.Bam.Rec.MVector_Nucs_half Bio.Base.Nucleotides instance GHC.Show.Show (Bio.Bam.Rec.Vector_Nucs_half Bio.Base.Nucleotides) instance GHC.Show.Show Bio.Bam.Rec.Cigar instance Foreign.Storable.Storable Bio.Bam.Rec.Cigar -- | Printers for BAM and SAM. BAM is properly supported, SAM can be piped -- to standard output. module Bio.Bam.Writer class IsBamRec a pushBam :: IsBamRec a => a -> BgzfTokens -> BgzfTokens unpackBamRec :: IsBamRec a => a -> BamRec -- | Encodes BAM records straight into a dynamic buffer, then BGZF's it. -- Should be fairly direct and perform well. encodeBamWith :: (IsBamRec a, MonadIO m) => Int -> BamMeta -> Stream (Of a) m r -> ByteStream m r packBam :: BamRec -> IO BamRaw -- | Writes BAM encoded stuff to a file. In reality, it cleverly writes to -- a temporary file and renames it when done. writeBamFile :: (IsBamRec a, MonadIO m, MonadMask m) => FilePath -> BamMeta -> Stream (Of a) m r -> m r -- | Writes BAM encoded stuff to a Handle. writeBamHandle :: (IsBamRec a, MonadIO m) => Handle -> BamMeta -> Stream (Of a) m r -> m r -- | Write BAM encoded stuff to stdout. This sends uncompressed(!) BAM to -- stdout. Useful for piping to other tools. The output is still wrapped -- in a BGZF stream, because that's what all tools expect; but the -- individuals blocks are not compressed. pipeBamOutput :: (IsBamRec a, MonadIO m) => BamMeta -> Stream (Of a) m r -> m r -- | write in SAM format to stdout -- -- This is useful for piping to other tools (say, AWK scripts) or for -- debugging. No convenience functions to send SAM to a file or to -- compress it exist, because these are stupid ideas. pipeSamOutput :: (IsBamRec a, MonadIO m) => BamMeta -> Stream (Of a) m r -> m r instance Bio.Bam.Writer.IsBamRec Bio.Bam.Rec.BamRaw instance Bio.Bam.Writer.IsBamRec Bio.Bam.Rec.BamRec instance (Bio.Bam.Writer.IsBamRec a, Bio.Bam.Writer.IsBamRec b) => Bio.Bam.Writer.IsBamRec (Data.Either.Either a b) module Bio.Bam.Rmdup -- | Removes duplicates from an aligned, sorted BAM stream. -- -- The incoming stream must be sorted by coordinate, and we check for -- violations of that assumption. We cannot assume that length was taken -- into account when sorting (samtools doesn't do so), so duplicates may -- be separated by reads that start at the same position but have -- different length or different strand. -- -- We are looking at three different kinds of reads: paired reads, true -- single ended reads, merged or trimmed reads. They are somewhat -- different, but here's the situation if we wanted to treat them -- separately. These conditions define a set of duplicates: -- -- Merged or trimmed: We compare the leftmost coordinates and the aligned -- length. If the library prep is strand-preserving, we also compare the -- strand. -- -- Paired: We compare both left-most coordinates (b_pos and b_mpos). If -- the library prep is strand-preserving, only first-mates can be -- duplicates of first-mates. Else a first-mate can be the duplicate of a -- second-mate. There may be pairs with one unmapped mate. This is not a -- problem as they get assigned synthetic coordinates and will be handled -- smoothly. -- -- True singles: We compare only the leftmost coordinate. It does not -- matter if the library prep is strand-preserving, the strand always -- matters. -- -- Across these classes, we can see more duplicates: -- -- Merged/trimmed and paired: these can be duplicates if the merging -- failed for the pair. We would need to compare the outer coordinates of -- the merged reads to the two 5' coordinates of the pair. However, since -- we don't have access to the mate, we cannot actually do anything right -- here. This case should be solved externally by merging those pairs -- that overlap in coordinate space. -- -- Single and paired: in the single case, we only have one coordinate to -- compare. This will inevitably lead to trouble, as we could find that -- the single might be the duplicate of two pairs, but those two pairs -- are definitely not duplicates of each other. We solve it by removing -- the single read(s). -- -- Single and merged/trimmed: same trouble as in the single+paired case. -- We remove the single to solve it. -- -- In principle, we might want to allow some wiggle room in the -- coordinates. So far, this has not been implemented. It adds the -- complication that groups of separated reads can turn into a set of -- duplicates because of the appearance of a new reads. Needs some -- thinking about... or maybe it's not too important. -- -- Once a set of duplicates is collected, we perform a majority vote on -- the correct CIGAR line. Of all those reads that agree on this CIGAR -- line, a consensus is called, quality scores are adjusted and clamped -- to a maximum, the MD field is updated and the XP field is assigned the -- number of reads in the original cluster. The new MAPQ becomes the RMSQ -- of the map qualities of all reads. -- -- Treatment of Read Groups: We generalize by providing a "label" -- function; only reads that have the same label are considered -- duplicates of each other. The typical label function would extract -- read groups, libraries or samples. rmdup :: (Monad m, Ord l) => (BamRec -> l) -> Bool -> Collapse -> Stream (Of BamRec) m r -> Stream (Of (Int, BamRec)) m r data Collapse cons_collapse :: Qual -> Collapse cheap_collapse :: Collapse cons_collapse_keep :: Qual -> Collapse cheap_collapse_keep :: Collapse check_sort :: (Monad m, Ord b) => (a -> b) -> String -> Stream (Of a) m r -> Stream (Of a) m r -- | Normalize a read's alignment to fall into the canonical region of -- [0..l]. Takes the name of the reference sequence and its length. -- Returns Left x if the coordinate decreased so the result is -- out of order now, Right x if the coordinate is unchanged. normalizeTo :: Bytes -> Int -> BamRec -> Either BamRec BamRec -- | Wraps a read to be fully contained in the canonical interval [0..l]. -- If the read overhangs, it is duplicated and both copies are suitably -- masked. A piece with changed coordinate that is now out of order is -- returned as Left x, if the order is fine, it is returned as -- Right x. wrapTo :: Int -> BamRec -> [Either BamRec BamRec] -- | Extended CIGAR. This subsumes both the CIGAR string and the optional -- MD field. If we have MD on input, we generate it on output, too. And -- in between, we break everything into very small operations. data ECig WithMD :: ECig WithoutMD :: ECig Mat' :: Int -> ECig -> ECig Rep' :: Nucleotides -> ECig -> ECig Ins' :: Int -> ECig -> ECig Del' :: Nucleotides -> ECig -> ECig Nop' :: Int -> ECig -> ECig SMa' :: Int -> ECig -> ECig HMa' :: Int -> ECig -> ECig Pad' :: Int -> ECig -> ECig toECig :: Vector Cigar -> [MdOp] -> ECig -- | Create an MD field from an extended CIGAR and place it in a record. We -- build it piecemeal (in go), call out to addNum, -- addRep, addDel to make sure the operations are not -- generated in a degenerate manner, and finally check if we're even -- supposed to create an MD field. setMD :: BamRec -> ECig -> BamRec toCigar :: ECig -> Vector Cigar -- | Trimming of reads as found in BAM files. Implements trimming low -- quality sequence from the 3' end. module Bio.Bam.Trim trim_3 :: Int -> BamRec -> BamRec -- | Trims from the 3' end of a sequence. trim_3' p b trims the 3' -- end of the sequence in b at the earliest position such that -- p evaluates to true on every suffix that was trimmed off. -- Note that the 3' end may be the beginning of the sequence if it -- happens to be stored in reverse-complemented form. Also note that -- trimming from the 3' end may not make sense for reads that were -- constructed by merging paired end data (but we cannot take care of -- that here). Further note that trimming may break dependent -- information, notably the "mate" information of the mate and many -- optional fields. trim_3' :: ([Nucleotides] -> [Qual] -> Bool) -> BamRec -> BamRec -- | Trim predicate to get rid of low quality sequence. -- trim_low_quality q ns qs evaluates to true if all qualities -- in qs are smaller (i.e. worse) than q. trim_low_quality :: Qual -> a -> [Qual] -> Bool -- | For merging, we don't need the complete adapters (length around 70!), -- only a sufficient prefix. Taking only the more-or-less constant part -- (length around 30), there aren't all that many different adapters in -- the world. To deal with pretty much every library, we only need the -- following forward adapters, which will be the default (defined here in -- the direction they would be sequenced in): Genomic R2, Multiplex R2, -- Fraft P7. default_fwd_adapters :: [Vector Nucleotides] -- | Like default_rev_adapters, these are the few adapters needed -- for the reverse read (defined in the direction they would be sequenced -- in as part of the second read): Genomic R1, CL 72. default_rev_adapters :: [Vector Nucleotides] -- | Finds the merge point. Input is list of forward adapters, list of -- reverse adapters, sequence1, quality1, sequence2, quality2; output is -- merge point and two qualities (YM, YN). find_merge :: [Vector Nucleotides] -> [Vector Nucleotides] -> Vector Nucleotides -> Vector Qual -> Vector Nucleotides -> Vector Qual -> (Int, Int, Int) -- | Overlap-merging of read pairs. We shall compute the likelihood for -- every possible overlap, then select the most likely one (unless it -- looks completely random), compute a quality from the second best -- merge, then merge and clamp the quality accordingly. (We could try -- looking for chimaera after completing the merge, if only we knew which -- ones to expect?) -- -- Two reads go in, with two adapter lists. We return Nothing if -- all merges looked mostly random. Else we return the two original -- reads, flagged as eflagVestigial *and* the merged version, -- flagged as eflagMerged and optionally eflagTrimmed. All -- reads contain the computed qualities (in YM and YN), which we also -- return. -- -- The merging automatically limits quality scores some of the time. We -- additionally impose a hard limit of 63 to avoid difficulties -- representing the result, and even that is ridiculous. Sane people -- would further limit the returned quality! (In practice, map quality -- later imposes a limit anyway, so no worries...) mergeBam :: Int -> Int -> [Vector Nucleotides] -> [Vector Nucleotides] -> BamRec -> BamRec -> [BamRec] -- | Finds the trimming point. Input is list of forward adapters, sequence, -- quality; output is trim point and two qualities (YM, YN). find_trim :: [Vector Nucleotides] -> Vector Nucleotides -> Vector Qual -> (Int, Int, Int) -- | Trimming for a single read: we need one adapter only (the one coming -- after the read), here provided as a list of options, and then -- we merge with an empty second read. Results in up to two reads (the -- original, possibly flagged, and the trimmed one, definitely flagged, -- and two qualities). trimBam :: Int -> Int -> [Vector Nucleotides] -> BamRec -> [BamRec] mergeTrimBam :: Monad m => Int -> Int -> [Vector Nucleotides] -> [Vector Nucleotides] -> Stream (Of BamRec) m r -> Stream (Of BamRec) m r twoMins :: (Bounded a, Ord a) => a -> Int -> (Int -> a) -> (a, Int, a) merged_seq :: (Vector v Nucleotides, Vector v Qual) => Int -> v Nucleotides -> v Qual -> v Nucleotides -> v Qual -> v Nucleotides merged_qual :: (Vector v Nucleotides, Vector v Qual) => Word8 -> Int -> v Nucleotides -> v Qual -> v Nucleotides -> v Qual -> v Qual -- | Parsers for BAM and SAM. module Bio.Bam.Reader -- | Decodes either BAM or SAM. -- -- The input can be plain, gzip'ed or bgzf'd and either BAM or SAM. BAM -- is reliably recognized, anything else is treated as SAM. The offsets -- stored in BAM records make sense only for uncompressed or bgzf'd BAM. decodeBam :: MonadIO m => ByteStream m r -> m (BamMeta, Stream (Of BamRaw) m r) decodeBamFile :: (MonadIO m, MonadMask m) => FilePath -> (BamMeta -> Stream (Of BamRaw) m () -> m r) -> m r -- | Reads multiple bam files. -- -- A continuation is run on the list of headers and streams. Since no -- attempt is made to unify the headers, this will work for completely -- unrelated bam files. All files are opened at the same time, which -- might run into the file descriptor limit given some ridiculous -- workflows. decodeBamFiles :: (MonadMask m, MonadIO m) => [FilePath] -> ([(BamMeta, Stream (Of BamRaw) m ())] -> m r) -> m r decodePlainBam :: MonadIO m => ByteStream m r -> m (BamMeta, Stream (Of BamRaw) m r) -- | Streaming parser for SAM files. -- -- It parses plain uncompressed SAM and returns a result compatible with -- decodePlainBam. Since it is supposed to work the same way as -- the BAM parser, it requires a symbol table for the reference names. -- This is extracted from the @SQ lines in the header. Note that reading -- SAM tends to be inefficient; if you care about performance at all, use -- BAM. decodePlainSam :: MonadIO m => ByteStream m r -> m (BamMeta, Stream (Of BamRaw) m r) getBamMeta :: Monad m => Parser r m BamMeta getBamRaw :: Monad m => Int64 -> Parser r m BamRaw getSamRec :: (Bytes -> Refseq) -> Bytes -> Either ParseError BamRec -- | Reads multiple bam inputs in sequence. -- -- Only one file is opened at a time, so they must also be consumed in -- sequence. If you can afford to open all inputs simultaneously, you -- probably want to use mergeInputsOn instead. The filename "-" -- refers to stdin, if no filenames are given, stdin is read. Since we -- can't look ahead into further files, the header of the first input is -- used for the result, and an exception is thrown if one of the -- subsequent headers is incompatible with the first one. concatInputs :: (MonadIO m, MonadMask m) => [FilePath] -> (BamMeta -> Stream (Of BamRaw) m () -> m r) -> m r -- | Reads multiple bam files and merges them. -- -- If the inputs are all sorted by the thing being merged on, the output -- will be sorted, too. The headers are all merged sensibly, even if -- their reference lists differ. However, for performance reasons, we -- don't want to change the rname and mrnm fields in potentially all -- records. So instead of allowing arbitrary reference lists to be -- merged, we throw an exception unless every input is compatible with -- the effective reference list. mergeInputsOn :: (Ord x, MonadIO m, MonadMask m) => (BamRaw -> x) -> [FilePath] -> (BamMeta -> Stream (Of BamRaw) m () -> m r) -> m r guardRefCompat :: MonadThrow m => (FilePath, BamMeta) -> (FilePath, BamMeta) -> m () coordinates :: BamRaw -> (Refseq, Int) qnames :: BamRaw -> Bytes instance GHC.Exception.Type.Exception Bio.Bam.Reader.IncompatibleRefs instance GHC.Show.Show Bio.Bam.Reader.IncompatibleRefs instance GHC.Exception.Type.Exception Bio.Bam.Reader.ShortRecord instance GHC.Show.Show Bio.Bam.Reader.ShortRecord -- | Pileup, similar to Samtools -- -- Pileup turns a sorted sequence of reads into a sequence of "piles", -- one for each site where a genetic variant might be called. We will -- scan each read's CIGAR line and MD field in concert with the sequence -- and effective quality. Effective quality is the lowest available -- quality score of QUAL, MAPQ, and BQ. For aDNA calling, a base is -- represented as four probabilities, derived from a position dependent -- damage model. module Bio.Bam.Pileup -- | The primitive pieces for genotype calling: A position, a base -- represented as four likelihoods, an inserted sequence, and the length -- of a deleted sequence. The logic is that we look at a base followed by -- some indel, and all those indels are combined into a single insertion -- and a single deletion. data PrimChunks -- | skip to position (at start or after N operation) Seek :: {-# UNPACK #-} !Int -> PrimBase -> PrimChunks -- | observed deletion and insertion between two bases Indel :: [Nucleotides] -> [DamagedBase] -> PrimBase -> PrimChunks -- | nothing anymore EndOfRead :: PrimChunks data PrimBase -- | more chunks Base :: {-# UNPACK #-} !Int -> {-# UNPACK #-} !DamagedBase -> {-# UNPACK #-} !Qual -> PrimChunks -> PrimBase -- | number of bases to wait due to a deletion [_pb_wait] :: PrimBase -> {-# UNPACK #-} !Int [_pb_base] :: PrimBase -> {-# UNPACK #-} !DamagedBase -- | map quality [_pb_mapq] :: PrimBase -> {-# UNPACK #-} !Qual [_pb_chunks] :: PrimBase -> PrimChunks type PosPrimChunks = (Refseq, Int, Bool, PrimChunks) -- | Represents our knowledge about a certain base, which consists of the -- base itself (A,C,G,T, encoded as 0..3; no Ns), the quality score -- (anything that isn't A,C,G,T becomes A with quality 0), and a -- substitution matrix representing post-mortem but pre-sequencing -- substitutions. -- -- Unfortunately, none of this can be rolled into something more simple, -- because damage and sequencing error behave so differently. -- -- Damage information is polymorphic. We might run with a simple version -- (a matrix) for calling, but we need more (a matrix and a mutable -- matrix, I think) for estimation. data DamagedBase -- | reference base from MD field DB :: {-# UNPACK #-} !Nucleotide -> {-# UNPACK #-} !Qual -> {-# UNPACK #-} !DmgToken -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !Nucleotides -> DamagedBase -- | called base [db_call] :: DamagedBase -> {-# UNPACK #-} !Nucleotide -- | quality of called base [db_qual] :: DamagedBase -> {-# UNPACK #-} !Qual -- | damage information [db_dmg_tk] :: DamagedBase -> {-# UNPACK #-} !DmgToken -- | damage information [db_dmg_pos] :: DamagedBase -> {-# UNPACK #-} !Int [db_ref] :: DamagedBase -> {-# UNPACK #-} !Nucleotides newtype DmgToken DmgToken :: Int -> DmgToken [fromDmgToken] :: DmgToken -> Int -- | Decomposes a BAM record into chunks suitable for piling up. We pick -- apart the CIGAR and MD fields, and combine them with sequence and -- quality as appropriate. Clipped bases are removed/skipped as needed. -- We also apply a substitution matrix to each base, which must be -- supplied along with the read. dissect :: DmgToken -> BamRaw -> [PosPrimChunks] -- | Statistics about a genotype call. Probably only useful for filtering -- (so not very useful), but we keep them because it's easy to track -- them. data CallStats CallStats :: {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int -> CallStats [read_depth] :: CallStats -> {-# UNPACK #-} !Int [reads_mapq0] :: CallStats -> {-# UNPACK #-} !Int [sum_mapq] :: CallStats -> {-# UNPACK #-} !Int [sum_mapq_squared] :: CallStats -> {-# UNPACK #-} !Int newtype V_Nuc V_Nuc :: Vector Nucleotide -> V_Nuc newtype V_Nucs V_Nucs :: Vector Nucleotides -> V_Nucs data IndelVariant IndelVariant :: !V_Nucs -> !V_Nuc -> IndelVariant [deleted_bases] :: IndelVariant -> !V_Nucs [inserted_bases] :: IndelVariant -> !V_Nuc -- | Map quality and a list of encountered bases, with damage information -- and reference base if known. type BasePile = [DamagedBase] -- | Map quality and a list of encountered indel variants. The deletion has -- the reference sequence, if known, an insertion has the inserted -- sequence with damage information. type IndelPile = [(Qual, ([Nucleotides], [DamagedBase]))] -- | Running pileup results in a series of piles. A Pile' has the -- basic statistics of a VarCall, but no likelihood values and a -- pristine list of variants instead of a proper call. We emit one pile -- with two BasePiles (one for each strand) and one -- IndelPile (the one immediately following) at a time. data Pile' a b Pile :: {-# UNPACK #-} !Refseq -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !CallStats -> a -> {-# UNPACK #-} !CallStats -> b -> Pile' a b [p_refseq] :: Pile' a b -> {-# UNPACK #-} !Refseq [p_pos] :: Pile' a b -> {-# UNPACK #-} !Int [p_snp_stat] :: Pile' a b -> {-# UNPACK #-} !CallStats [p_snp_pile] :: Pile' a b -> a [p_indel_stat] :: Pile' a b -> {-# UNPACK #-} !CallStats [p_indel_pile] :: Pile' a b -> b -- | Raw pile. Bases and indels are piled separately on forward and -- backward strands. type Pile = Pile' (BasePile, BasePile) (IndelPile, IndelPile) -- | The pileup enumeratee takes BamRaws, dissects them, interleaves -- the pieces appropriately, and generates Pile's. The output will -- contain at most one BasePile and one IndelPile for each -- position, piles are sorted by position. -- -- This top level driver receives BamRaws. Unaligned reads and -- duplicates are skipped (but not those merely failing quality checks). -- Processing stops when the first read with invalid br_rname is -- encountered or a t end of file. pileup :: Stream (Of PosPrimChunks) IO b -> Stream (Of Pile) IO b instance (GHC.Show.Show a, GHC.Show.Show b) => GHC.Show.Show (Bio.Bam.Pileup.Pile' a b) instance GHC.Generics.Generic Bio.Bam.Pileup.IndelVariant instance GHC.Show.Show Bio.Bam.Pileup.IndelVariant instance GHC.Classes.Ord Bio.Bam.Pileup.IndelVariant instance GHC.Classes.Eq Bio.Bam.Pileup.IndelVariant instance GHC.Show.Show Bio.Bam.Pileup.V_Nucs instance GHC.Classes.Ord Bio.Bam.Pileup.V_Nucs instance GHC.Classes.Eq Bio.Bam.Pileup.V_Nucs instance GHC.Show.Show Bio.Bam.Pileup.V_Nuc instance GHC.Classes.Ord Bio.Bam.Pileup.V_Nuc instance GHC.Classes.Eq Bio.Bam.Pileup.V_Nuc instance GHC.Generics.Generic Bio.Bam.Pileup.CallStats instance GHC.Classes.Eq Bio.Bam.Pileup.CallStats instance GHC.Show.Show Bio.Bam.Pileup.CallStats instance GHC.Show.Show Bio.Bam.Pileup.PrimBase instance GHC.Show.Show Bio.Bam.Pileup.PrimChunks instance GHC.Base.Functor (Bio.Bam.Pileup.PileM m) instance GHC.Base.Applicative (Bio.Bam.Pileup.PileM m) instance GHC.Base.Monad (Bio.Bam.Pileup.PileM m) instance GHC.Base.Monoid Bio.Bam.Pileup.CallStats instance GHC.Base.Semigroup Bio.Bam.Pileup.CallStats instance GHC.Show.Show Bio.Bam.Pileup.DamagedBase module Bio.Bam.Index -- | Full index, unifying BAI and CSI style. In both cases, we have the -- binning scheme, parameters are fixed in BAI, but variable in CSI. -- Checkpoints are created from the linear index in BAI or from the -- loffset field in CSI. data BamIndex a BamIndex :: {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int64 -> a -> {-# UNPACK #-} !Vector Bins -> {-# UNPACK #-} !Vector Ckpoints -> BamIndex a -- | Minshift parameter from CSI [minshift] :: BamIndex a -> {-# UNPACK #-} !Int -- | Depth parameter from CSI [depth] :: BamIndex a -> {-# UNPACK #-} !Int -- | Best guess at where the unaligned records start [unaln_off] :: BamIndex a -> {-# UNPACK #-} !Int64 -- | Room for stuff (needed for tabix) [extensions] :: BamIndex a -> a -- | Records for the binning index, where each bin has a list of segments -- belonging to it. [refseq_bins] :: BamIndex a -> {-# UNPACK #-} !Vector Bins -- | Known checkpoints of the form (pos,off) where off is the virtual -- offset of the first record crossing pos. [refseq_ckpoints] :: BamIndex a -> {-# UNPACK #-} !Vector Ckpoints withIndexedBam :: (MonadIO m, MonadMask m) => FilePath -> (BamMeta -> BamIndex () -> Handle -> m r) -> m r -- | Reads any index we can find for a file. -- -- If the file name has a .bai or .csi extension, optionally followed by -- .gz, we read it. Else we look for the index by adding such an -- extension and by replacing the extension with these two, and finally -- try the file itself. The first file that exists is used. readBamIndex :: FilePath -> IO (BamIndex ()) -- | Reads an index in BAI or CSI format, recognized automatically. The -- index can be compressed, even though this isn't standard. readBaiIndex :: MonadIO m => ByteStream m r -> m (BamIndex ()) -- | Reads a Tabix index. Note that tabix indices are compressed, this is -- taken care of automatically. readTabix :: MonadIO m => ByteStream m r -> m TabIndex data Region Region :: !Refseq -> !Int -> !Int -> Region [refseq] :: Region -> !Refseq [start] :: Region -> !Int [end] :: Region -> !Int -- | A mostly contiguous subset of a sequence, stored as a set of -- non-overlapping intervals in an IntMap from start position to -- end position (half-open intervals, naturally). newtype Subsequence Subsequence :: IntMap Int -> Subsequence -- | Streams one reference from a bam file. -- -- Seeks to a given sequence in a Bam file and enumerates only those -- records aligning to that reference. We use the first checkpoint -- available for the sequence, which an appropriate index. Streams the -- BamRaw records of the correct reference sequence only, and -- produces an empty stream if the sequence isn't found. streamBamRefseq :: MonadIO m => BamIndex b -> Handle -> Refseq -> Stream (Of BamRaw) m () streamBamRegions :: MonadIO m => BamIndex b -> Handle -> [Region] -> Stream (Of BamRaw) m () streamBamSubseq :: MonadIO m => BamIndex b -> Handle -> Refseq -> Subsequence -> Stream (Of BamRaw) m () -> Stream (Of BamRaw) m (Stream (Of BamRaw) m ()) -- | Reads from a Bam file the part with unaligned reads. -- -- Sort of the dual to streamBamRefseq. Since the index does not -- actually point to the unaligned part at the end, we use a best guess -- at where the unaligned stuff might start, then skip over any aligned -- records. Our "fallback guess" is to decode from the current position; -- this only works if something else already consumed the Bam header. streamBamUnaligned :: MonadIO m => BamIndex b -> Handle -> Stream (Of BamRaw) m () instance GHC.Show.Show Bio.Bam.Index.TabMeta instance GHC.Show.Show Bio.Bam.Index.TabFormat instance GHC.Show.Show Bio.Bam.Index.Segment instance GHC.Show.Show a => GHC.Show.Show (Bio.Bam.Index.BamIndex a) instance GHC.Exception.Type.Exception Bio.Bam.Index.IndexFormatError instance GHC.Show.Show Bio.Bam.Index.IndexFormatError -- | Quality filters adapted from prehistoric pipeline. module Bio.Bam.Filter -- | A filter/transformation applied to pairs of reads. We supply a -- predicate to be applied to single reads and one to be applied to -- pairs, the latter can get incomplete pairs, too, if mates have been -- separated or filtered asymmetrically. This fails spectacularly if the -- input isn't grouped by name. filterPairs :: Monad m => (BamRec -> [BamRec]) -> (Maybe BamRec -> Maybe BamRec -> [BamRec]) -> Stream (Of BamRec) m r -> Stream (Of BamRec) m r -- | A quality filter is simply a transformation on BamRecs. By -- convention, quality filters should set flagFailsQC, a further -- step can then remove the failed reads. Filtering of individual reads -- tends to result in mate pairs with inconsistent flags, which in turn -- will result in lone mates and all sort of troubles with programs that -- expect non-broken BAM files. It is therefore recommended to use -- pairFilter with suitable predicates to do the post -- processing. type QualFilter = BamRec -> BamRec -- | Simple complexity filter aka "Nancy Filter". A read is considered -- not-sufficiently-complex if the most common base accounts for greater -- than the cutoff fraction of all non-N bases. complexSimple :: Double -> QualFilter -- | Filter on order zero empirical entropy. Entropy per base must be -- greater than cutoff. complexEntropy :: Double -> QualFilter -- | Filter on average quality. Reads without quality string pass. qualityAverage :: Int -> QualFilter -- | Filter on minimum quality. In qualityMinimum n q, a read -- passes if it has no more than n bases with quality less than -- q. Reads without quality string pass. qualityMinimum :: Int -> Qual -> QualFilter -- | Convert quality scores from old Illumina scale (different formula and -- offset 64 in FastQ). qualityFromOldIllumina :: BamRec -> BamRec -- | Convert quality scores from new Illumina scale (standard formula but -- offset 64 in FastQ). qualityFromNewIllumina :: BamRec -> BamRec -- | Parser for FastA/FastQ, ByteStream style, based on -- Data.Attoparsec, and written such that it is compatible with -- module Bio.Bam. This gives import of FastA/FastQ while -- respecting some local (to MPI EVAN) conventions. module Bio.Bam.Fastq -- | Reader for DNA (not protein) sequences in FastA and FastQ. We read -- everything vaguely looking like FastA or FastQ, then shoehorn it into -- a BAM record. We strive to extract information following more or less -- established conventions from the header, but don't aim for -- completeness. The recognized syntactical warts are converted into -- appropriate flags and removed. Only the canonical variant of FastQ is -- supported (qualities stored as raw bytes with offset 33). -- -- Supported additional conventions: -- --
-- int bwa_cal_maxdiff(int l, double err, double thres)
-- {
-- double elambda = exp(-l * err);
-- double sum, y = 1.0;
-- int k, x = 1;
-- for (k = 1, sum = elambda; k < 1000; ++k) {
-- y *= l * err;
-- x *= k;
-- sum += elambda * y / x;
-- if (1.0 - sum < thres) return k;
-- }
-- return 2;
-- }
--
bwa_cal_maxdiff :: Double -> Int -> Int
instance GHC.Classes.Ord Bio.Adna.NPair
instance GHC.Classes.Eq Bio.Adna.NPair
instance GHC.Classes.Eq Bio.Adna.FragType
instance GHC.Show.Show Bio.Adna.FragType
instance GHC.Show.Show Bio.Adna.DmgStats
instance (GHC.Read.Read float, GHC.Read.Read (vec float)) => GHC.Read.Read (Bio.Adna.GenDamageParameters vec float)
instance GHC.Generics.Generic (Bio.Adna.GenDamageParameters vec float)
instance (GHC.Show.Show float, GHC.Show.Show (vec float)) => GHC.Show.Show (Bio.Adna.GenDamageParameters vec float)
instance GHC.Generics.Generic (Bio.Adna.NewDamageParameters vec float)
instance (GHC.Show.Show float, GHC.Show.Show (vec float)) => GHC.Show.Show (Bio.Adna.NewDamageParameters vec float)
instance (GHC.Read.Read float, GHC.Read.Read (vec float)) => GHC.Read.Read (Bio.Adna.NewDamageParameters vec float)
instance GHC.Generics.Generic (Bio.Adna.DamageParameters float)
instance GHC.Show.Show float => GHC.Show.Show (Bio.Adna.DamageParameters float)
instance GHC.Read.Read float => GHC.Read.Read (Bio.Adna.DamageParameters float)
instance GHC.Show.Show Bio.Adna.Subst
instance GHC.Arr.Ix Bio.Adna.Subst
instance GHC.Classes.Ord Bio.Adna.Subst
instance GHC.Classes.Eq Bio.Adna.Subst
instance GHC.Generics.Generic Bio.Adna.Mat44D
instance GHC.Show.Show Bio.Adna.Mat44D
instance Foreign.Storable.Storable Bio.Adna.NPair
instance GHC.Show.Show Bio.Adna.NPair
instance GHC.Base.Monoid Bio.Adna.DmgStats
instance GHC.Base.Semigroup Bio.Adna.DmgStats