-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | Custom prelude from Kowainik -- --
-- (<*>) = 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 :: * -> *) -- | 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 -- | One or none. optional :: Alternative f => f a -> f Maybe a -- | Lists, but with an Applicative functor based on zipping. newtype ZipList a ZipList :: [a] -> ZipList a [getZipList] :: ZipList a -> [a] -- | The Const functor. newtype Const a (b :: k) :: forall k. () => * -> k -> * Const :: a -> Const a [getConst] :: Const a -> a -- | Lift a ternary function to actions. liftA3 :: Applicative f => a -> b -> c -> d -> f a -> f b -> f c -> f d -- | A variant of <*> with the arguments reversed. (<**>) :: Applicative f => f a -> f a -> b -> f b infixl 4 <**> -- | A monoid on applicative functors. -- -- If defined, some and many should be the least solutions -- of the equations: -- -- class Applicative f => Alternative (f :: * -> *) -- | The identity of <|> empty :: Alternative f => f a -- | An associative binary operation (<|>) :: Alternative f => f a -> f a -> f a -- | One or more. some :: Alternative f => f a -> f [a] -- | Zero or more. many :: Alternative f => f a -> f [a] -- | Shorter alias for pure (). -- --
-- >>> pass :: Maybe () -- Just () --pass :: Applicative f => f () -- | Reexports from Data.* and GHC.* modules of -- base package. module Relude.Base -- | Bitwise "xor" xor :: Bits a => a -> a -> a infixl 6 `xor` -- | The character type Char is an enumeration whose values -- represent Unicode (or equivalently ISO/IEC 10646) code points (i.e. -- characters, see http://www.unicode.org/ for details). This set -- extends the ISO 8859-1 (Latin-1) character set (the first 256 -- characters), which is itself an extension of the ASCII character set -- (the first 128 characters). A character literal in Haskell has type -- Char. -- -- To convert a Char to or from the corresponding Int value -- defined by Unicode, use toEnum and fromEnum from the -- Enum class respectively (or equivalently ord and -- chr). data Char -- | The toEnum method restricted to the type Char. chr :: Int -> Char -- | A fixed-precision integer type with at least the range [-2^29 .. -- 2^29-1]. The exact range for a given implementation can be -- determined by using minBound and maxBound from the -- Bounded class. data Int -- | 8-bit signed integer type data Int8 -- | 16-bit signed integer type data Int16 -- | 32-bit signed integer type data Int32 -- | 64-bit signed integer type data Int64 -- | A Word is an unsigned integral type, with the same size as -- Int. data Word -- | 8-bit unsigned integer type data Word8 -- | 16-bit unsigned integer type data Word16 -- | 32-bit unsigned integer type data Word32 -- | 64-bit unsigned integer type data Word64 -- | Reverse order of bytes in Word64. byteSwap64 :: Word64 -> Word64 -- | Reverse order of bytes in Word32. byteSwap32 :: Word32 -> Word32 -- | Swap bytes in Word16. byteSwap16 :: Word16 -> Word16 -- | Type representing arbitrary-precision non-negative integers. -- --
-- >>> 2^20 :: Natural -- 1267650600228229401496703205376 ---- -- Operations whose result would be negative throw -- (Underflow :: ArithException), -- --
-- >>> -1 :: Natural -- *** Exception: arithmetic underflow --data Natural -- | The Eq class defines equality (==) and inequality -- (/=). All the basic datatypes exported by the Prelude -- are instances of Eq, and Eq may be derived for any -- datatype whose constituents are also instances of Eq. -- -- Minimal complete definition: either == or /=. class Eq a (==) :: Eq a => a -> a -> Bool (/=) :: Eq a => a -> a -> Bool -- | The Ord class is used for totally ordered datatypes. -- -- Instances of Ord can be derived for any user-defined datatype -- whose constituent types are in Ord. The declared order of the -- constructors in the data declaration determines the ordering in -- derived Ord instances. The Ordering datatype allows a -- single comparison to determine the precise ordering of two objects. -- -- Minimal complete definition: either compare or <=. -- Using compare can be more efficient for complex types. class Eq a => Ord a compare :: Ord a => a -> a -> Ordering (<) :: Ord a => a -> a -> Bool (<=) :: Ord a => a -> a -> Bool (>) :: Ord a => a -> a -> Bool (>=) :: Ord a => a -> a -> Bool max :: Ord a => a -> a -> a min :: Ord a => a -> a -> a data Ordering LT :: Ordering EQ :: Ordering GT :: Ordering -- |
-- 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 -- | A value of type IO a is a computation which, when -- performed, does some I/O before returning a value of type a. -- -- There is really only one way to "perform" an I/O action: bind it to -- Main.main in your program. When your program is run, the I/O -- will be performed. It isn't possible to perform I/O from an arbitrary -- function, unless that function is itself in the IO monad and -- called at some point, directly or indirectly, from Main.main. -- -- IO is a monad, so IO actions can be combined using -- either the do-notation or the >> and >>= -- operations from the Monad class. data IO a -- | 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: -- --
-- instance Coercible a a ---- -- Furthermore, for every type constructor there is an instance that -- allows to coerce under the type constructor. For example, let -- D be a prototypical type constructor (data or -- newtype) with three type arguments, which have roles -- nominal, representational resp. phantom. -- Then there is an instance of the form -- --
-- instance Coercible b b' => Coercible (D a b c) (D a b' c') ---- -- Note that the nominal type arguments are equal, the -- representational type arguments can differ, but need to have -- a Coercible instance themself, and the phantom type -- arguments can be changed arbitrarily. -- -- The third kind of instance exists for every newtype NT = MkNT -- T and comes in two variants, namely -- --
-- instance Coercible a T => Coercible a NT ---- --
-- instance Coercible T b => Coercible NT b ---- -- This instance is only usable if the constructor MkNT is in -- scope. -- -- If, as a library author of a type constructor like Set a, you -- want to prevent a user of your module to write coerce :: Set T -- -> Set NT, you need to set the role of Set's type -- parameter to nominal, by writing -- --
-- type role Set nominal ---- -- For more details about this feature, please refer to Safe -- Coercions by Joachim Breitner, Richard A. Eisenberg, Simon Peyton -- Jones and Stephanie Weirich. class a ~R# b => Coercible (a :: k0) (b :: k0) -- | The kind of types with values. For example Int :: Type. type Type = * -- | The kind of constraints, like Show a data Constraint -- | Proxy is a type that holds no data, but has a phantom parameter -- of arbitrary type (or even kind). Its use is to provide type -- information, even though there is no value available of that type (or -- it may be too costly to create one). -- -- Historically, Proxy :: Proxy a is a safer -- alternative to the 'undefined :: a' idiom. -- --
-- >>> Proxy :: Proxy (Void, Int -> Int) -- Proxy ---- -- Proxy can even hold types of higher kinds, -- --
-- >>> Proxy :: Proxy Either -- Proxy ---- --
-- >>> Proxy :: Proxy Functor -- Proxy ---- --
-- >>> Proxy :: Proxy complicatedStructure -- Proxy --data Proxy (t :: k) :: forall k. () => k -> * Proxy :: Proxy -- | The class Typeable allows a concrete representation of a type -- to be calculated. class Typeable (a :: k) -- | If Void is uninhabited then any Functor that holds only -- values of type Void is holding no values. vacuous :: Functor f => f Void -> f a -- | Since Void values logically don't exist, this witnesses the -- logical reasoning tool of "ex falso quodlibet". -- --
-- >>> let x :: Either Void Int; x = Right 5
--
-- >>> :{
-- case x of
-- Right r -> r
-- Left l -> absurd l
-- :}
-- 5
--
absurd :: () => Void -> a
-- | Uninhabited data type
data Void
-- | 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
maxInt :: Int
minInt :: Int
-- | asTypeOf is a type-restricted version of const. It is
-- usually used as an infix operator, and its typing forces its first
-- argument (which is usually overloaded) to have the same type as the
-- second.
asTypeOf :: () => a -> a -> a
-- | Strict (call-by-value) application operator. It takes a function and
-- an argument, evaluates the argument to weak head normal form (WHNF),
-- then calls the function with that value.
($!) :: () => a -> b -> a -> b
infixr 0 $!
-- | The fromEnum method restricted to the type Char.
ord :: Char -> Int
-- | A String is a list of characters. String constants in Haskell
-- are values of type String.
type String = [Char]
-- | 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..]. enumFrom :: Enum a => a -> [a] -- | Used in Haskell's translation of [n,n'..]. enumFromThen :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n..m]. enumFromTo :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n,n'..m]. enumFromThenTo :: Enum a => a -> a -> a -> [a] boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a] boundedEnumFrom :: (Enum a, Bounded a) => a -> [a] -- | Trigonometric and hyperbolic functions and related functions. class Fractional a => Floating a pi :: Floating a => a exp :: Floating a => a -> a sqrt :: Floating a => a -> a (**) :: Floating a => a -> a -> a logBase :: Floating a => a -> a -> a sin :: Floating a => a -> a cos :: Floating a => a -> a tan :: Floating a => a -> a asin :: Floating a => a -> a acos :: Floating a => a -> a atan :: Floating a => a -> a sinh :: Floating a => a -> a cosh :: Floating a => a -> a tanh :: Floating a => a -> a asinh :: Floating a => a -> a acosh :: Floating a => a -> a atanh :: Floating a => a -> a -- | Double-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- double-precision type. data Double D# :: Double# -> Double -- | Single-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- single-precision type. data Float F# :: Float# -> Float -- | Representable types of kind *. This class is derivable in GHC -- with the DeriveGeneric flag on. -- -- A Generic instance must satisfy the following laws: -- --
-- from . to ≡ id -- to . from ≡ id --class Generic a -- | Basic numeric class. class Num a (+) :: Num a => a -> a -> a (-) :: Num a => a -> a -> a (*) :: Num a => a -> a -> a -- | Unary negation. negate :: Num a => a -> a -- | Absolute value. abs :: Num a => a -> a -- | Sign of a number. The functions abs and signum should -- satisfy the law: -- --
-- abs x * signum x == x ---- -- For real numbers, the signum is either -1 (negative), -- 0 (zero) or 1 (positive). signum :: Num a => a -> a -- | Conversion from an Integer. An integer literal represents the -- application of the function fromInteger to the appropriate -- value of type Integer, so such literals have type -- (Num a) => a. fromInteger :: Num a => Integer -> a -- | Invariant: Jn# and Jp# are used iff value doesn't fit in -- S# -- -- Useful properties resulting from the invariants: -- -- data Integer -- | the same as flip (-). -- -- Because - is treated specially in the Haskell grammar, -- (- e) is not a section, but an application of -- prefix negation. However, (subtract -- exp) is equivalent to the disallowed section. subtract :: Num a => a -> a -> a -- | general coercion from integral types fromIntegral :: (Integral a, Num b) => a -> b -- | general coercion to fractional types realToFrac :: (Real a, Fractional b) => a -> b -- | Fractional numbers, supporting real division. class Num a => Fractional a -- | fractional division (/) :: Fractional a => a -> a -> a -- | reciprocal fraction recip :: Fractional a => a -> a -- | Conversion from a Rational (that is Ratio -- Integer). A floating literal stands for an application of -- fromRational to a value of type Rational, so such -- literals have type (Fractional a) => a. fromRational :: Fractional a => Rational -> a -- | Integral numbers, supporting integer division. class (Real a, Enum a) => Integral a -- | integer division truncated toward zero quot :: Integral a => a -> a -> a -- | integer remainder, satisfying -- --
-- (x `quot` y)*y + (x `rem` y) == x --rem :: Integral a => a -> a -> a -- | integer division truncated toward negative infinity div :: Integral a => a -> a -> a -- | integer modulus, satisfying -- --
-- (x `div` y)*y + (x `mod` y) == x --mod :: Integral a => a -> a -> a -- | simultaneous quot and rem quotRem :: Integral a => a -> a -> (a, a) -- | simultaneous div and mod divMod :: Integral a => a -> a -> (a, a) -- | conversion to Integer toInteger :: Integral a => a -> Integer class (Num a, Ord a) => Real a -- | the rational equivalent of its real argument with full precision toRational :: Real a => a -> Rational -- | Extracting components of fractions. class (Real a, Fractional a) => RealFrac a -- | The function properFraction takes a real fractional number -- x and returns a pair (n,f) such that x = -- n+f, and: -- --
-- 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, -- --
-- putStrLnWithCallStack :: HasCallStack => String -> IO () ---- -- as a variant of putStrLn that will get its call-site and -- print it, along with the string given as argument. We can access the -- call-stack inside putStrLnWithCallStack with -- callStack. -- --
-- putStrLnWithCallStack :: HasCallStack => String -> IO () -- putStrLnWithCallStack msg = do -- putStrLn msg -- putStrLn (prettyCallStack callStack) ---- -- Thus, if we call putStrLnWithCallStack we will get a -- formatted call-stack alongside our string. -- --
-- >>> putStrLnWithCallStack "hello" -- hello -- CallStack (from HasCallStack): -- putStrLnWithCallStack, called at <interactive>:2:1 in interactive:Ghci1 ---- -- GHC solves HasCallStack constraints in three steps: -- --
-- 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 () -- | The reverse of when. unless :: Applicative f => Bool -> f () -> f () -- | Conditional execution of Applicative expressions. For example, -- --
-- when debug (putStrLn "Debugging") ---- -- will output the string Debugging if the Boolean value -- debug is True, and otherwise do nothing. when :: Applicative f => Bool -> f () -> f () -- | otherwise is defined as the value True. It helps to make -- guards more readable. eg. -- --
-- f x | x < 0 = ... -- | otherwise = ... --otherwise :: Bool data Bool False :: Bool True :: Bool -- | Case analysis for the Bool type. bool x y p -- evaluates to x when p is False, and evaluates -- to y when p is True. -- -- This is equivalent to if p then y else x; that is, one can -- think of it as an if-then-else construct with its arguments reordered. -- --
-- >>> bool "foo" "bar" True -- "bar" -- -- >>> bool "foo" "bar" False -- "foo" ---- -- Confirm that bool x y p and if p then y else -- x are equivalent: -- --
-- >>> let p = True; x = "bar"; y = "foo" -- -- >>> bool x y p == if p then y else x -- True -- -- >>> let p = False -- -- >>> bool x y p == if p then y else x -- True --bool :: () => a -> a -> Bool -> a -- | Boolean "and" (&&) :: Bool -> Bool -> Bool infixr 3 && -- | Boolean "or" (||) :: Bool -> Bool -> Bool infixr 2 || -- | Boolean "not" not :: Bool -> Bool -- | Reexports all container-related stuff from base, -- containers and unordered-containers packages. module Relude.Container.Reexport -- | The class of types that can be converted to a hash value. -- -- Minimal implementation: hashWithSalt. class Hashable a -- | Return a hash value for the argument, using the given salt. -- -- The general contract of hashWithSalt is: -- --
-- >>> 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 -- | The IsList class and its methods are intended to be used in -- conjunction with the OverloadedLists extension. class IsList l -- | The fromList function constructs the structure l from -- the given list of Item l fromList :: IsList l => [Item l] -> l -- | The fromListN function takes the input list's length as a hint. -- Its behaviour should be equivalent to fromList. The hint can be -- used to construct the structure l more efficiently compared -- to fromList. If the given hint does not equal to the input -- list's length the behaviour of fromListN is not specified. fromListN :: IsList l => Int -> [Item l] -> l -- | Typeclass for creating structures from singleton element. module Relude.Container.One -- | Typeclass for data types that can be created from one element. -- --
-- >>> one True :: [Bool] -- [True] -- -- >>> one 'a' :: Text -- "a" -- -- >>> one (3, "hello") :: HashMap Int String -- fromList [(3,"hello")] --class One x where { type family OneItem x; } -- | Create a list, map, Text, etc from a single element. one :: One x => OneItem x -> x instance Relude.Container.One.One [a] instance Relude.Container.One.One (GHC.Base.NonEmpty a) instance Relude.Container.One.One (Data.Sequence.Internal.Seq a) instance Relude.Container.One.One Data.Text.Internal.Text instance Relude.Container.One.One Data.Text.Internal.Lazy.Text instance Relude.Container.One.One Data.ByteString.Internal.ByteString instance Relude.Container.One.One Data.ByteString.Lazy.Internal.ByteString instance Relude.Container.One.One (Data.Map.Internal.Map k v) instance Data.Hashable.Class.Hashable k => Relude.Container.One.One (Data.HashMap.Base.HashMap k v) instance Relude.Container.One.One (Data.IntMap.Internal.IntMap v) instance Relude.Container.One.One (Data.Set.Internal.Set v) instance Data.Hashable.Class.Hashable v => Relude.Container.One.One (Data.HashSet.HashSet v) instance Relude.Container.One.One Data.IntSet.Internal.IntSet -- | This module exports all container-related stuff. module Relude.Container -- | Reexports Data.Foldable and Data.Traversable. module Relude.Foldable.Reexport -- | Data structures that can be folded. -- -- For example, given a data type -- --
-- data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a) ---- -- a suitable instance would be -- --
-- instance Foldable Tree where -- foldMap f Empty = mempty -- foldMap f (Leaf x) = f x -- foldMap f (Node l k r) = foldMap f l `mappend` f k `mappend` foldMap f r ---- -- This is suitable even for abstract types, as the monoid is assumed to -- satisfy the monoid laws. Alternatively, one could define -- foldr: -- --
-- instance Foldable Tree where -- foldr f z Empty = z -- foldr f z (Leaf x) = f x z -- foldr f z (Node l k r) = foldr f (f k (foldr f z r)) l ---- -- Foldable instances are expected to satisfy the following -- laws: -- --
-- foldr f z t = appEndo (foldMap (Endo . f) t ) z ---- --
-- foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z ---- --
-- fold = foldMap id ---- --
-- length = getSum . foldMap (Sum . const 1) ---- -- sum, product, maximum, and minimum -- should all be essentially equivalent to foldMap forms, such -- as -- --
-- sum = getSum . foldMap Sum ---- -- but may be less defined. -- -- If the type is also a Functor instance, it should satisfy -- --
-- foldMap f = fold . fmap f ---- -- which implies that -- --
-- foldMap f . fmap g = foldMap (f . g) --class Foldable (t :: * -> *) -- | Combine the elements of a structure using a monoid. fold :: (Foldable t, Monoid m) => t m -> m -- | Map each element of the structure to a monoid, and combine the -- results. foldMap :: (Foldable t, Monoid m) => a -> m -> t a -> m -- | Right-associative fold of a structure. -- -- In the case of lists, foldr, when applied to a binary operator, -- a starting value (typically the right-identity of the operator), and a -- list, reduces the list using the binary operator, from right to left: -- --
-- foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...) ---- -- Note that, since the head of the resulting expression is produced by -- an application of the operator to the first element of the list, -- foldr can produce a terminating expression from an infinite -- list. -- -- For a general Foldable structure this should be semantically -- identical to, -- --
-- foldr f z = foldr f z . toList --foldr :: Foldable t => a -> b -> b -> b -> t a -> b -- | Left-associative fold of a structure but with strict application of -- the operator. -- -- This ensures that each step of the fold is forced to weak head normal -- form before being applied, avoiding the collection of thunks that -- would otherwise occur. This is often what you want to strictly reduce -- a finite list to a single, monolithic result (e.g. length). -- -- For a general Foldable structure this should be semantically -- identical to, -- --
-- foldl f z = foldl' f z . toList --foldl' :: Foldable t => b -> a -> b -> b -> t a -> b -- | List of elements of a structure, from left to right. toList :: Foldable t => t a -> [a] -- | Test whether the structure is empty. The default implementation is -- optimized for structures that are similar to cons-lists, because there -- is no general way to do better. null :: Foldable t => t a -> Bool -- | Returns the size/length of a finite structure as an Int. The -- default implementation is optimized for structures that are similar to -- cons-lists, because there is no general way to do better. length :: Foldable t => t a -> Int -- | The find function takes a predicate and a structure and returns -- the leftmost element of the structure matching the predicate, or -- Nothing if there is no such element. find :: Foldable t => a -> Bool -> t a -> Maybe a -- | Determines whether all elements of the structure satisfy the -- predicate. all :: Foldable t => a -> Bool -> t a -> Bool -- | Determines whether any element of the structure satisfies the -- predicate. any :: Foldable t => a -> Bool -> t a -> Bool -- | or returns the disjunction of a container of Bools. For the -- result to be False, the container must be finite; True, -- however, results from a True value finitely far from the left -- end. or :: Foldable t => t Bool -> Bool -- | and returns the conjunction of a container of Bools. For the -- result to be True, the container must be finite; False, -- however, results from a False value finitely far from the left -- end. and :: Foldable t => t Bool -> Bool -- | Map a function over all the elements of a container and concatenate -- the resulting lists. concatMap :: Foldable t => a -> [b] -> t a -> [b] -- | The concatenation of all the elements of a container of lists. concat :: Foldable t => t [a] -> [a] -- | The sum of a collection of actions, generalizing concat. -- -- asum [Just Hello, Nothing, Just World] Just Hello asum :: (Foldable t, Alternative f) => t f a -> f a -- | Evaluate each monadic action in the structure from left to right, and -- ignore the results. For a version that doesn't ignore the results see -- sequence. -- -- As of base 4.8.0.0, sequence_ is just sequenceA_, -- specialized to Monad. sequence_ :: (Foldable t, Monad m) => t m a -> m () -- | Evaluate each action in the structure from left to right, and ignore -- the results. For a version that doesn't ignore the results see -- sequenceA. sequenceA_ :: (Foldable t, Applicative f) => t f a -> f () -- | forM_ is mapM_ with its arguments flipped. For a version -- that doesn't ignore the results see forM. -- -- As of base 4.8.0.0, forM_ is just for_, specialized to -- Monad. forM_ :: (Foldable t, Monad m) => t a -> a -> m b -> m () -- | Map each element of a structure to a monadic action, evaluate these -- actions from left to right, and ignore the results. For a version that -- doesn't ignore the results see mapM. -- -- As of base 4.8.0.0, mapM_ is just traverse_, specialized -- to Monad. mapM_ :: (Foldable t, Monad m) => a -> m b -> t a -> m () -- | for_ is traverse_ with its arguments flipped. For a -- version that doesn't ignore the results see for. -- --
-- >>> for_ [1..4] print -- 1 -- 2 -- 3 -- 4 --for_ :: (Foldable t, Applicative f) => t a -> a -> f b -> f () -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and ignore the results. For a version that doesn't -- ignore the results see traverse. traverse_ :: (Foldable t, Applicative f) => a -> f b -> t a -> f () -- | Monadic fold over the elements of a structure, associating to the -- left, i.e. from left to right. foldlM :: (Foldable t, Monad m) => b -> a -> m b -> b -> t a -> m b -- | 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: -- --
-- f $ g $ h x = f (g (h x)) ---- -- It is also useful in higher-order situations, such as map -- ($ 0) xs, or zipWith ($) fs xs. ($) :: () => a -> b -> a -> b infixr 0 $ -- | & 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 -> b -> c -> a -> b -> a -> a -> c infixl 0 `on` -- | fix f is the least fixed point of the function -- f, i.e. the least defined x such that f x = -- x. -- -- For example, we can write the factorial function using direct -- recursion as -- --
-- >>> let fac n = if n <= 1 then 1 else n * fac (n-1) in fac 5 -- 120 ---- -- This uses the fact that Haskell’s let introduces recursive -- bindings. We can rewrite this definition using fix, -- --
-- >>> fix (\rec n -> if n <= 1 then 1 else n * rec (n-1)) 5 -- 120 ---- -- Instead of making a recursive call, we introduce a dummy parameter -- rec; when used within fix, this parameter then refers -- to fix' argument, hence the recursion is reintroduced. fix :: () => a -> a -> a -- | flip f takes its (first) two arguments in the reverse -- order of f. -- --
-- >>> flip (++) "hello" "world" -- "worldhello" --flip :: () => a -> b -> c -> b -> a -> c -- | Function composition. (.) :: () => b -> c -> a -> b -> a -> c infixr 9 . -- | 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 -- | Identity function. -- --
-- id x = x --id :: () => a -> a -- | Renamed version of id. identity :: a -> a -- | Reexports functionality regarding Functor and Bifunctor -- typeclasses. module Relude.Functor.Reexport -- | 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 :: * -> * -> *) -- | 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 -- | The Functor class is used for types that can be mapped over. -- Instances of Functor should satisfy the following laws: -- --
-- fmap id == id -- fmap (f . g) == fmap f . fmap g ---- -- The instances of Functor for lists, Maybe and IO -- satisfy these laws. class Functor (f :: * -> *) fmap :: Functor f => a -> b -> f a -> f b -- | Replace all locations in the input with the same value. The default -- definition is fmap . const, but this may be -- overridden with a more efficient version. (<$) :: Functor f => a -> f b -> f a -- | 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 $> -- | 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 <$> -- | Right-to-left composition of functors. The composition of applicative -- functors is always applicative, but the composition of monads is not -- always a monad. newtype Compose (f :: k -> *) (g :: k1 -> k) (a :: k1) :: forall k k1. () => k -> * -> k1 -> k -> k1 -> * Compose :: f g a -> Compose [getCompose] :: Compose -> f g a -- | Identity functor and monad. (a non-strict monad) newtype Identity a Identity :: a -> Identity a [runIdentity] :: Identity a -> a -- | This module contains useful functions to work with Functor type -- class. module Relude.Functor.Fmap -- | Alias for fmap . fmap. Convenient to work with two nested -- Functors. -- --
-- >>> negate <<$>> Just [1,2,3] -- Just [-1,-2,-3] --(<<$>>) :: (Functor f, Functor g) => (a -> b) -> f (g a) -> f (g b) infixl 4 <<$>> -- | 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 <&> -- | Takes a function in a Functor context and applies it to a -- normal value. -- --
-- >>> flap (++) "relude" "P" -- "Prelude" --flap :: Functor f => f (a -> b) -> a -> f b -- | Operator version of the flap function. -- --
-- >>> [(+2), (*3)] ?? 5 -- [7,15] ---- --
-- >>> Just (+3) ?? 5 -- Just 8 --(??) :: Functor f => f (a -> b) -> a -> f b infixl 4 ?? -- | Convenient functions to work with Functor. module Relude.Functor -- | Lifted MVar and STM functions. module Relude.Lifted.Concurrent -- | An MVar (pronounced "em-var") is a synchronising variable, used -- for communication between concurrent threads. It can be thought of as -- a a box, which may be empty or full. data MVar a -- | Lifted to MonadIO version of newEmptyMVar. newEmptyMVar :: MonadIO m => m (MVar a) -- | Lifted to MonadIO version of newMVar. newMVar :: MonadIO m => a -> m (MVar a) -- | Lifted to MonadIO version of putMVar. putMVar :: MonadIO m => MVar a -> a -> m () -- | Lifted to MonadIO version of readMVar. readMVar :: MonadIO m => MVar a -> m a -- | Lifted to MonadIO version of swapMVar. swapMVar :: MonadIO m => MVar a -> a -> m a -- | Lifted to MonadIO version of takeMVar. takeMVar :: MonadIO m => MVar a -> m a -- | Lifted to MonadIO version of tryPutMVar. tryPutMVar :: MonadIO m => MVar a -> a -> m Bool -- | Lifted to MonadIO version of tryReadMVar. tryReadMVar :: MonadIO m => MVar a -> m (Maybe a) -- | Lifted to MonadIO version of tryTakeMVar. tryTakeMVar :: MonadIO m => MVar a -> m (Maybe a) -- | A monad supporting atomic memory transactions. data STM a -- | Shared memory locations that support atomic memory transactions. data TVar a -- | Lifted to MonadIO version of atomically. atomically :: MonadIO m => STM a -> m a -- | Lifted to MonadIO version of newTVarIO. newTVarIO :: MonadIO m => a -> m (TVar a) -- | Lifted to MonadIO version of readTVarIO. readTVarIO :: MonadIO m => TVar a -> m a -- | Strict version of modifyTVar. modifyTVar' :: () => TVar a -> a -> a -> STM () -- | Create a new TVar holding a value supplied newTVar :: () => a -> STM TVar a -- | Return the current value stored in a TVar. readTVar :: () => TVar a -> STM a -- | Write the supplied value into a TVar. writeTVar :: () => TVar a -> a -> STM () -- | Lifted versions of functions that work with exit processes. module Relude.Lifted.Exit -- | Lifted version of exitWith. exitWith :: MonadIO m => ExitCode -> m a -- | Lifted version of exitFailure. exitFailure :: MonadIO m => m a -- | Lifted version of exitSuccess. exitSuccess :: MonadIO m => m a -- | Lifted version of die. die :: MonadIO m => String -> m () -- | Lifted reexports from IORef module. module Relude.Lifted.IORef -- | A mutable variable in the IO monad data IORef a -- | Lifted version of atomicModifyIORef. atomicModifyIORef :: MonadIO m => IORef a -> (a -> (a, b)) -> m b -- | Lifted version of atomicModifyIORef'. atomicModifyIORef' :: MonadIO m => IORef a -> (a -> (a, b)) -> m b -- | Lifted version of atomicWriteIORef. atomicWriteIORef :: MonadIO m => IORef a -> a -> m () -- | Lifted version of modifyIORef. modifyIORef :: MonadIO m => IORef a -> (a -> a) -> m () -- | Lifted version of modifyIORef'. modifyIORef' :: MonadIO m => IORef a -> (a -> a) -> m () -- | Lifted version of newIORef. newIORef :: MonadIO m => a -> m (IORef a) -- | Lifted version of readIORef. readIORef :: MonadIO m => IORef a -> m a -- | Lifted version of writeIORef. writeIORef :: MonadIO m => IORef a -> a -> m () -- | Reexports most of the Data.List and Data.List.NonEmpty. module Relude.List.Reexport -- | 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 ++ -- | 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. -- If one input list is short, excess elements of the longer list are -- discarded. -- -- zip is right-lazy: -- --
-- zip [] _|_ = [] --zip :: () => [a] -> [b] -> [(a, b)] -- | map f xs is the list obtained by applying f -- to each element of xs, i.e., -- --
-- map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn] -- map f [x1, x2, ...] == [f x1, f x2, ...] --map :: () => a -> b -> [a] -> [b] -- | The unfoldr function is a `dual' to foldr: while -- foldr reduces a list to a summary value, unfoldr builds -- a list from a seed value. The function takes the element and returns -- Nothing if it is done producing the list or returns Just -- (a,b), in which case, a is a prepended to the list -- and b is used as the next element in a recursive call. For -- example, -- --
-- iterate f == unfoldr (\x -> Just (x, f x)) ---- -- In some cases, unfoldr can undo a foldr operation: -- --
-- unfoldr f' (foldr f z xs) == xs ---- -- if the following holds: -- --
-- f' (f x y) = Just (x,y) -- f' z = Nothing ---- -- A simple use of unfoldr: -- --
-- >>> unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10 -- [10,9,8,7,6,5,4,3,2,1] --unfoldr :: () => b -> Maybe (a, b) -> b -> [a] -- | Sort a list by comparing the results of a key function applied to each -- element. sortOn f is equivalent to sortBy (comparing -- f), but has the performance advantage of only evaluating -- f once for each element in the input list. This is called the -- decorate-sort-undecorate paradigm, or Schwartzian transform. -- -- Elements are arranged from from lowest to highest, keeping duplicates -- in the order they appeared in the input. -- --
-- >>> sortOn fst [(2, "world"), (4, "!"), (1, "Hello")] -- [(1,"Hello"),(2,"world"),(4,"!")] --sortOn :: Ord b => a -> b -> [a] -> [a] -- | The sortBy function is the non-overloaded version of -- sort. -- --
-- >>> sortBy (\(a,_) (b,_) -> compare a b) [(2, "world"), (4, "!"), (1, "Hello")] -- [(1,"Hello"),(2,"world"),(4,"!")] --sortBy :: () => a -> a -> Ordering -> [a] -> [a] -- | The sort function implements a stable sorting algorithm. It is -- a special case of sortBy, which allows the programmer to supply -- their own comparison function. -- -- Elements are arranged from from lowest to highest, keeping duplicates -- in the order they appeared in the input. -- --
-- >>> sort [1,6,4,3,2,5] -- [1,2,3,4,5,6] --sort :: Ord a => [a] -> [a] -- | The permutations function returns the list of all permutations -- of the argument. -- --
-- >>> permutations "abc" -- ["abc","bac","cba","bca","cab","acb"] --permutations :: () => [a] -> [[a]] -- | The subsequences function returns the list of all subsequences -- of the argument. -- --
-- >>> subsequences "abc" -- ["","a","b","ab","c","ac","bc","abc"] --subsequences :: () => [a] -> [[a]] -- | The tails function returns all final segments of the argument, -- longest first. For example, -- --
-- >>> tails "abc" -- ["abc","bc","c",""] ---- -- Note that tails has the following strictness property: -- tails _|_ = _|_ : _|_ tails :: () => [a] -> [[a]] -- | The inits function returns all initial segments of the -- argument, shortest first. For example, -- --
-- >>> inits "abc" -- ["","a","ab","abc"] ---- -- Note that inits has the following strictness property: -- inits (xs ++ _|_) = inits xs ++ _|_ -- -- In particular, inits _|_ = [] : _|_ inits :: () => [a] -> [[a]] -- | The group function takes a list and returns a list of lists -- such that the concatenation of the result is equal to the argument. -- Moreover, each sublist in the result contains only equal elements. For -- example, -- --
-- >>> group "Mississippi" -- ["M","i","ss","i","ss","i","pp","i"] ---- -- It is a special case of groupBy, which allows the programmer to -- supply their own equality test. group :: Eq a => [a] -> [[a]] -- | The genericReplicate function is an overloaded version of -- replicate, which accepts any Integral value as the -- number of repetitions to make. genericReplicate :: Integral i => i -> a -> [a] -- | The genericSplitAt function is an overloaded version of -- splitAt, which accepts any Integral value as the -- position at which to split. genericSplitAt :: Integral i => i -> [a] -> ([a], [a]) -- | The genericDrop function is an overloaded version of -- drop, which accepts any Integral value as the number of -- elements to drop. genericDrop :: Integral i => i -> [a] -> [a] -- | The genericTake function is an overloaded version of -- take, which accepts any Integral value as the number of -- elements to take. genericTake :: Integral i => i -> [a] -> [a] -- | The genericLength function is an overloaded version of -- length. In particular, instead of returning an Int, it -- returns any type which is an instance of Num. It is, however, -- less efficient than length. genericLength :: Num i => [a] -> i -- | The transpose function transposes the rows and columns of its -- argument. For example, -- --
-- >>> transpose [[1,2,3],[4,5,6]] -- [[1,4],[2,5],[3,6]] ---- -- If some of the rows are shorter than the following rows, their -- elements are skipped: -- --
-- >>> transpose [[10,11],[20],[],[30,31,32]] -- [[10,20,30],[11,31],[32]] --transpose :: () => [[a]] -> [[a]] -- | intercalate xs xss is equivalent to (concat -- (intersperse xs xss)). It inserts the list xs in -- between the lists in xss and concatenates the result. -- --
-- >>> intercalate ", " ["Lorem", "ipsum", "dolor"] -- "Lorem, ipsum, dolor" --intercalate :: () => [a] -> [[a]] -> [a] -- | The intersperse function takes an element and a list and -- `intersperses' that element between the elements of the list. For -- example, -- --
-- >>> intersperse ',' "abcde" -- "a,b,c,d,e" --intersperse :: () => a -> [a] -> [a] -- | The isPrefixOf function takes two lists and returns True -- iff the first list is a prefix of the second. -- --
-- >>> "Hello" `isPrefixOf` "Hello World!" -- True ---- --
-- >>> "Hello" `isPrefixOf` "Wello Horld!" -- False --isPrefixOf :: Eq a => [a] -> [a] -> Bool -- | The unzip3 function takes a list of triples and returns three -- lists, analogous to unzip. unzip3 :: () => [(a, b, c)] -> ([a], [b], [c]) -- | unzip transforms a list of pairs into a list of first -- components and a list of second components. unzip :: () => [(a, b)] -> ([a], [b]) -- | zipWith generalises zip by zipping with the function -- given as the first argument, instead of a tupling function. For -- example, zipWith (+) is applied to two lists to -- produce the list of corresponding sums. -- -- zipWith is right-lazy: -- --
-- zipWith f [] _|_ = [] --zipWith :: () => a -> b -> c -> [a] -> [b] -> [c] -- | zip3 takes three lists and returns a list of triples, analogous -- to zip. zip3 :: () => [a] -> [b] -> [c] -> [(a, b, c)] -- | reverse xs returns the elements of xs in -- reverse order. xs must be finite. reverse :: () => [a] -> [a] -- | break, applied to a predicate p and a list -- xs, returns a tuple where first element is longest prefix -- (possibly empty) of xs of elements that do not satisfy -- p and second element is the remainder of the list: -- --
-- break (> 3) [1,2,3,4,1,2,3,4] == ([1,2,3],[4,1,2,3,4]) -- break (< 9) [1,2,3] == ([],[1,2,3]) -- break (> 9) [1,2,3] == ([1,2,3],[]) ---- -- break p is equivalent to span (not . -- p). break :: () => a -> Bool -> [a] -> ([a], [a]) -- | splitAt n xs returns a tuple where first element is -- xs prefix of length n and second element is the -- remainder of the list: -- --
-- splitAt 6 "Hello World!" == ("Hello ","World!")
-- splitAt 3 [1,2,3,4,5] == ([1,2,3],[4,5])
-- splitAt 1 [1,2,3] == ([1],[2,3])
-- splitAt 3 [1,2,3] == ([1,2,3],[])
-- splitAt 4 [1,2,3] == ([1,2,3],[])
-- splitAt 0 [1,2,3] == ([],[1,2,3])
-- splitAt (-1) [1,2,3] == ([],[1,2,3])
--
--
-- It is equivalent to (take n xs, drop n xs) when
-- n is not _|_ (splitAt _|_ xs = _|_).
-- splitAt is an instance of the more general
-- genericSplitAt, in which n may be of any integral
-- type.
splitAt :: () => Int -> [a] -> ([a], [a])
-- | drop n xs returns the suffix of xs after the
-- first n elements, or [] if n > length
-- xs:
--
-- -- drop 6 "Hello World!" == "World!" -- drop 3 [1,2,3,4,5] == [4,5] -- drop 3 [1,2] == [] -- drop 3 [] == [] -- drop (-1) [1,2] == [1,2] -- drop 0 [1,2] == [1,2] ---- -- It is an instance of the more general genericDrop, in which -- n may be of any integral type. drop :: () => Int -> [a] -> [a] -- | take n, applied to a list xs, returns the -- prefix of xs of length n, or xs itself if -- n > length xs: -- --
-- take 5 "Hello World!" == "Hello" -- take 3 [1,2,3,4,5] == [1,2,3] -- take 3 [1,2] == [1,2] -- take 3 [] == [] -- take (-1) [1,2] == [] -- take 0 [1,2] == [] ---- -- It is an instance of the more general genericTake, in which -- n may be of any integral type. take :: () => Int -> [a] -> [a] -- | dropWhile p xs returns the suffix remaining after -- takeWhile p xs: -- --
-- dropWhile (< 3) [1,2,3,4,5,1,2,3] == [3,4,5,1,2,3] -- dropWhile (< 9) [1,2,3] == [] -- dropWhile (< 0) [1,2,3] == [1,2,3] --dropWhile :: () => a -> Bool -> [a] -> [a] -- | takeWhile, applied to a predicate p and a list -- xs, returns the longest prefix (possibly empty) of -- xs of elements that satisfy p: -- --
-- takeWhile (< 3) [1,2,3,4,1,2,3,4] == [1,2] -- takeWhile (< 9) [1,2,3] == [1,2,3] -- takeWhile (< 0) [1,2,3] == [] --takeWhile :: () => a -> Bool -> [a] -> [a] -- | cycle ties a finite list into a circular one, or equivalently, -- the infinite repetition of the original list. It is the identity on -- infinite lists. cycle :: () => [a] -> [a] -- | replicate n x is a list of length n with -- x the value of every element. It is an instance of the more -- general genericReplicate, in which n may be of any -- integral type. replicate :: () => Int -> a -> [a] -- | repeat x is an infinite list, with x the -- value of every element. repeat :: () => a -> [a] -- | iterate f x returns an infinite list of repeated -- applications of f to x: -- --
-- iterate f x == [x, f x, f (f x), ...] ---- -- Note that iterate is lazy, potentially leading to thunk -- build-up if the consumer doesn't force each iterate. See 'iterate\'' -- for a strict variant of this function. iterate :: () => a -> a -> a -> [a] -- | scanr is the right-to-left dual of scanl. Note that -- --
-- head (scanr f z xs) == foldr f z xs. --scanr :: () => a -> b -> b -> b -> [a] -> [b] -- | scanl is similar to foldl, but returns a list of -- successive reduced values from the left: -- --
-- scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...] ---- -- Note that -- --
-- last (scanl f z xs) == foldl f z xs. --scanl :: () => b -> a -> b -> b -> [a] -> [b] -- | 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 everything except the last element of the stream. init :: () => NonEmpty a -> [a] -- | Extract the last element of the stream. last :: () => NonEmpty a -> a -- | Extract the possibly-empty tail of the stream. tail :: () => NonEmpty a -> [a] -- | Extract the first element of the stream. head :: () => NonEmpty a -> a -- | nonEmpty efficiently turns a normal list into a NonEmpty -- stream, producing Nothing if the input is empty. nonEmpty :: () => [a] -> Maybe NonEmpty a -- | Non-empty (and non-strict) list type. data NonEmpty a (:|) :: a -> [a] -> NonEmpty a -- | The sortWith function sorts a list of elements using the user -- supplied function to project something out of each element sortWith :: Ord b => a -> b -> [a] -> [a] -- | Reexports functions to work with monads. module Relude.Monad.Reexport -- | A monad transformer that adds exceptions to other monads. -- -- ExceptT constructs a monad parameterized over two things: -- --
runReader (withReader f m) = runReader m -- . f
runReaderT (withReaderT f m) = -- runReaderT m . f
-- Main> :t modify ((+1) :: Int -> Int) -- modify (...) :: (MonadState Int a) => a () ---- -- This says that modify (+1) acts over any Monad that is a -- member of the MonadState class, with an Int state. modify :: MonadState s m => s -> s -> m () -- | Minimal definition is either both of get and put or -- just state class Monad m => MonadState s (m :: * -> *) | m -> s -- | Return the state from the internals of the monad. get :: MonadState s m => m s -- | Replace the state inside the monad. put :: MonadState s m => s -> m () -- | Embed a simple state action into the monad. state :: MonadState s m => s -> (a, s) -> m a -- | A state transformer monad parameterized by: -- --
evalStateT m s = liftM fst -- (runStateT m s)
execStateT m s = liftM snd -- (runStateT m s)
-- (.) :: (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 Kleisli composition of monads. (>=>) :: 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] -- | Same as >>=, but with the arguments interchanged. (=<<) :: Monad m => a -> m b -> m a -> m b infixr 1 =<< -- | Monads that also support choice and failure. class (Alternative m, Monad m) => MonadPlus (m :: * -> *) -- | The identity of mplus. It should also satisfy the equations -- --
-- mzero >>= f = mzero -- v >> mzero = mzero ---- -- The default definition is -- --
-- mzero = empty --mzero :: MonadPlus m => m a -- | An associative operation. The default definition is -- --
-- mplus = (<|>) --mplus :: MonadPlus m => m a -> m a -> m a -- | When a value is bound in do-notation, the pattern on the left -- hand side of <- might not match. In this case, this class -- provides a function to recover. -- -- A Monad without a MonadFail instance may only be used in -- conjunction with pattern that always match, such as newtypes, tuples, -- data types with only a single data constructor, and irrefutable -- patterns (~pat). -- -- Instances of MonadFail should satisfy the following law: -- fail s should be a left zero for >>=, -- --
-- fail s >>= f = fail s ---- -- If your Monad is also MonadPlus, a popular definition -- is -- --
-- fail _ = mzero --class Monad m => MonadFail (m :: * -> *) fail :: MonadFail m => String -> m a -- | The Maybe type encapsulates an optional value. A value of type -- Maybe a either contains a value of type a -- (represented as Just a), or it is empty (represented -- as Nothing). Using Maybe is a good way to deal with -- errors or exceptional cases without resorting to drastic measures such -- as error. -- -- The Maybe type is also a monad. It is a simple kind of error -- monad, where all errors are represented by Nothing. A richer -- error monad can be built using the Either type. data Maybe a Nothing :: Maybe a Just :: a -> Maybe a -- | The 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 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 -- | 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 -- | 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 -- | Utility functions to work with Maybe data type as monad. module Relude.Monad.Maybe -- | Similar to fromMaybe but with flipped arguments. -- --
-- >>> readMaybe "True" ?: False -- True ---- --
-- >>> readMaybe "Tru" ?: False -- False --(?:) :: Maybe a -> a -> a infixr 0 ?: -- | Specialized version of for_ for Maybe. It's used for -- code readability. Also helps to avoid space leaks: Foldable.mapM_ -- space leak. -- --
-- >>> whenJust Nothing $ \b -> print (not b) -- -- >>> whenJust (Just True) $ \b -> print (not b) -- False --whenJust :: Applicative f => Maybe a -> (a -> f ()) -> f () -- | Monadic version of whenJust. whenJustM :: Monad m => m (Maybe a) -> (a -> m ()) -> m () -- | Performs default Applicative action if Nothing is given. -- Otherwise returns content of Just pured to Applicative. -- --
-- >>> whenNothing Nothing [True, False] -- [True,False] -- -- >>> whenNothing (Just True) [True, False] -- [True] --whenNothing :: Applicative f => Maybe a -> f a -> f a -- | Performs default Applicative action if Nothing is given. -- Do nothing for Just. Convenient for discarding Just -- content. -- --
-- >>> whenNothing_ Nothing $ putTextLn "Nothing!" -- Nothing! -- -- >>> whenNothing_ (Just True) $ putTextLn "Nothing!" --whenNothing_ :: Applicative f => Maybe a -> f () -> f () -- | Monadic version of whenNothing. whenNothingM :: Monad m => m (Maybe a) -> m a -> m a -- | Monadic version of whenNothingM_. whenNothingM_ :: Monad m => m (Maybe a) -> m () -> m () -- | Lifted versions of functions working with files and common IO. module Relude.Lifted.File -- | Lifted version of readFile. readFile :: MonadIO m => FilePath -> m String -- | Lifted version of writeFile. writeFile :: MonadIO m => FilePath -> String -> m () -- | Lifted version of appendFile. appendFile :: MonadIO m => FilePath -> String -> m () -- | Lifted version of openFile. openFile :: MonadIO m => FilePath -> IOMode -> m Handle -- | Lifted version of hClose. hClose :: MonadIO m => Handle -> m () -- | Monad transformers utilities. module Relude.Monad.Trans -- | Shorter and more readable alias for flip runReader. usingReader :: r -> Reader r a -> a -- | Shorter and more readable alias for flip runReaderT. usingReaderT :: r -> ReaderT r m a -> m a -- | Alias for flip evalState. It's not shorter but sometimes more -- readable. Done by analogy with using* functions family. evaluatingState :: s -> State s a -> a -- | Alias for flip evalStateT. It's not shorter but sometimes -- more readable. Done by analogy with using* functions family. evaluatingStateT :: Functor f => s -> StateT s f a -> f a -- | Alias for flip execState. It's not shorter but sometimes more -- readable. Done by analogy with using* functions family. executingState :: s -> State s a -> s -- | Alias for flip execStateT. It's not shorter but sometimes -- more readable. Done by analogy with using* functions family. executingStateT :: Functor f => s -> StateT s f a -> f s -- | Shorter and more readable alias for flip runState. usingState :: s -> State s a -> (a, s) -- | Shorter and more readable alias for flip runStateT. usingStateT :: s -> StateT s m a -> m (a, s) -- | Lift a Maybe to the MaybeT monad hoistMaybe :: Applicative m => Maybe a -> MaybeT m a -- | Lift a Either to the ExceptT monad hoistEither :: Applicative m => Either e a -> ExceptT e m a -- | Reexports functions to work with monoids plus adds extra useful -- functions. module Relude.Monoid -- | 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
-- >>> getFirst (First (Just "hello") <> First Nothing <> First (Just "world")) -- Just "hello" --newtype First a First :: Maybe a -> First a [getFirst] :: First a -> Maybe a -- | Maybe monoid returning the rightmost non-Nothing value. -- -- Last a is isomorphic to Dual (First -- a), and thus to Dual (Alt Maybe a) -- --
-- >>> getLast (Last (Just "hello") <> Last Nothing <> Last (Just "world")) -- Just "world" --newtype Last a Last :: Maybe a -> Last a [getLast] :: Last a -> Maybe a -- | 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 -> *) (a :: k) :: forall k. () => k -> * -> k -> * Alt :: f a -> Alt [getAlt] :: Alt -> f a -- | The class of semigroups (types with an associative binary operation). -- -- Instances should satisfy the associativity law: -- -- class Semigroup a -- | An associative operation. (<>) :: Semigroup a => a -> a -> a -- | Reduce a non-empty list with <> -- -- The default definition should be sufficient, but this can be -- overridden for efficiency. sconcat :: Semigroup a => NonEmpty a -> a -- | Repeat a value n times. -- -- Given that this works on a Semigroup it is allowed to fail if -- you request 0 or fewer repetitions, and the default definition will do -- so. -- -- By making this a member of the class, idempotent semigroups and -- monoids can upgrade this to execute in O(1) by picking -- stimes = stimesIdempotent or stimes = -- stimesIdempotentMonoid respectively. stimes :: (Semigroup a, Integral b) => b -> a -> a -- | Repeat a value n times. -- --
-- mtimesDefault n a = a <> a <> ... <> a -- using <> (n-1) times ---- -- Implemented using stimes and mempty. -- -- This is a suitable definition for an mtimes member of -- Monoid. mtimesDefault :: (Integral b, Monoid a) => b -> a -> a -- | A generalization of cycle to an arbitrary Semigroup. May -- fail to terminate for some values in some semigroups. cycle1 :: Semigroup m => m -> m -- | Provide a Semigroup for an arbitrary Monoid. -- -- NOTE: This is not needed anymore since Semigroup became -- a superclass of Monoid in base-4.11 and this newtype be -- deprecated at some point in the future. data WrappedMonoid m -- | Option is effectively Maybe with a better instance of -- Monoid, built off of an underlying Semigroup instead of -- an underlying Monoid. -- -- Ideally, this type would not exist at all and we would just fix the -- Monoid instance of Maybe newtype Option a Option :: Maybe a -> Option a [getOption] :: Option a -> Maybe a -- | This is a valid definition of stimes for a Monoid. -- -- Unlike the default definition of stimes, it is defined for 0 -- and so it should be preferred where possible. stimesMonoid :: (Integral b, Monoid a) => b -> a -> a -- | This is a valid definition of stimes for an idempotent -- Semigroup. -- -- When x <> x = x, this definition should be preferred, -- because it works in O(1) rather than O(log n). stimesIdempotent :: Integral b => b -> a -> a -- | This is a valid definition of stimes for an idempotent -- Monoid. -- -- When mappend x x = x, this definition should be preferred, -- because it works in O(1) rather than O(log n) stimesIdempotentMonoid :: (Integral b, Monoid a) => b -> a -> a -- | Extracts Monoid value from Maybe returning mempty -- if Nothing. -- --
-- >>> maybeToMonoid (Just [1,2,3] :: Maybe [Int]) -- [1,2,3] -- -- >>> maybeToMonoid (Nothing :: Maybe [Int]) -- [] --maybeToMonoid :: Monoid m => Maybe m -> m -- | Functions to remove duplicates from a list. -- --
-- >>> hashNub [3, 3, 3, 2, 2, -1, 1] -- [3,2,-1,1] --hashNub :: (Eq a, Hashable a) => [a] -> [a] -- | Like nub but runs in O(n * log n) time and requires -- Ord. -- --
-- >>> ordNub [3, 3, 3, 2, 2, -1, 1] -- [3,2,-1,1] --ordNub :: (Ord a) => [a] -> [a] -- | Like ordNub but also sorts a list. -- --
-- >>> sortNub [3, 3, 3, 2, 2, -1, 1] -- [-1,1,2,3] --sortNub :: (Ord a) => [a] -> [a] -- | Like hashNub but has better performance and also doesn't save -- the order. -- --
-- >>> unstableNub [3, 3, 3, 2, 2, -1, 1] -- [1,2,3,-1] --unstableNub :: (Eq a, Hashable a) => [a] -> [a] -- | Reexports functions to work with Text and ByteString -- types. module Relude.String.Reexport -- | Class for string-like datastructures; used by the overloaded string -- extension (-XOverloadedStrings in GHC). class IsString a fromString :: IsString a => String -> a -- | O(n) Joins words using single space characters. unwords :: [Text] -> Text -- | O(n) Joins lines, after appending a terminating newline to -- each. unlines :: [Text] -> Text -- | O(n) Breaks a Text up into a list of Texts at -- newline Chars. The resulting strings do not contain newlines. lines :: Text -> [Text] -- | O(n) Breaks a Text up into a list of words, delimited by -- Chars representing white space. words :: Text -> [Text] -- | A space efficient, packed, unboxed Unicode text type. data Text -- | Decode a ByteString containing UTF-8 encoded text. -- -- If the input contains any invalid UTF-8 data, the relevant exception -- will be returned, otherwise the decoded text. decodeUtf8' :: ByteString -> Either UnicodeException Text -- | Decode a ByteString containing UTF-8 encoded text. decodeUtf8With :: OnDecodeError -> ByteString -> Text -- | Replace an invalid input byte with the Unicode replacement character -- U+FFFD. lenientDecode :: OnDecodeError -- | Throw a UnicodeException if decoding fails. strictDecode :: OnDecodeError -- | Function type for handling a coding error. It is supplied with two -- inputs: -- --
-- 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 -- | Parse a string using the Read instance. Succeeds if there is -- exactly one valid result. -- --
-- >>> readMaybe "123" :: Maybe Int -- Just 123 ---- --
-- >>> readMaybe "hello" :: Maybe Int -- Nothing --readMaybe :: Read a => String -> Maybe a -- | equivalent to readsPrec with a precedence of 0. reads :: Read a => ReadS a -- | A space-efficient representation of a Word8 vector, supporting -- many efficient operations. -- -- A ByteString contains 8-bit bytes, or by using the operations -- from Data.ByteString.Char8 it can be interpreted as containing -- 8-bit characters. data ByteString -- | This module implements type class which allow to have conversion to -- and from Text, String and ByteString types -- (including both strict and lazy versions). Usually you need to export -- Text modules qualified and use pack / unpack -- functions to convert to/from Text. Now you can just use -- toText / toString functions. module Relude.String.Conversion -- | Type synonym for Text. type LText = Text -- | Type synonym for ByteString. type LByteString = ByteString -- | Type class for conversion to utf8 representation of text. class ConvertUtf8 a b -- | Encode as utf8 string (usually ByteString). -- --
-- >>> encodeUtf8 @Text @ByteString "патак" -- "\208\191\208\176\209\130\208\176\208\186" --encodeUtf8 :: ConvertUtf8 a b => a -> b -- | Decode from utf8 string. -- --
-- >>> decodeUtf8 @Text @ByteString "\208\191\208\176\209\130\208\176\208\186" -- "\1087\1072\1090\1072\1082" -- -- >>> putTextLn $ decodeUtf8 @Text @ByteString "\208\191\208\176\209\130\208\176\208\186" -- патак --decodeUtf8 :: ConvertUtf8 a b => b -> a -- | Decode as utf8 string but returning execption if byte sequence is -- malformed. -- --
-- >>> decodeUtf8 @Text @ByteString "\208\208\176\209\130\208\176\208\186" -- "\65533\1072\1090\1072\1082" ---- --
-- >>> decodeUtf8Strict @Text @ByteString "\208\208\176\209\130\208\176\208\186" -- Left Cannot decode byte '\xd0': Data.Text.Internal.Encoding.decodeUtf8: Invalid UTF-8 stream --decodeUtf8Strict :: ConvertUtf8 a b => b -> Either UnicodeException a -- | Type class for converting other strings to String. class ToString a toString :: ToString a => a -> String -- | Type class for converting other strings to Text. class ToLText a toLText :: ToLText a => a -> Text -- | Type class for converting other strings to Text. class ToText a toText :: ToText a => a -> Text -- | Type class for lazy-strict conversions. class LazyStrict l s | l -> s, s -> l toLazy :: LazyStrict l s => s -> l toStrict :: LazyStrict l s => l -> s -- | Alias for toStrict function. fromLazy :: LazyStrict l s => l -> s -- | Alias for toLazy function. fromStrict :: LazyStrict l s => s -> l -- | Polymorhpic version of readEither. -- --
-- >>> readEither @Text @Int "123" -- Right 123 -- -- >>> readEither @Text @Int "aa" -- Left "Prelude.read: no parse" --readEither :: (ToString a, Read b) => a -> Either Text b -- | Generalized version of show. show :: forall b a. (Show a, IsString b) => a -> b instance Relude.String.Conversion.LazyStrict Relude.String.Conversion.LByteString Data.ByteString.Internal.ByteString instance Relude.String.Conversion.LazyStrict Relude.String.Conversion.LText Data.Text.Internal.Text instance Relude.String.Conversion.ToString GHC.Base.String instance Relude.String.Conversion.ToString Data.Text.Internal.Text instance Relude.String.Conversion.ToString Data.Text.Internal.Lazy.Text instance Relude.String.Conversion.ToLText GHC.Base.String instance Relude.String.Conversion.ToLText Data.Text.Internal.Text instance Relude.String.Conversion.ToLText Data.Text.Internal.Lazy.Text instance Relude.String.Conversion.ToText GHC.Base.String instance Relude.String.Conversion.ToText Data.Text.Internal.Text instance Relude.String.Conversion.ToText Data.Text.Internal.Lazy.Text instance Relude.String.Conversion.ConvertUtf8 GHC.Base.String Data.ByteString.Internal.ByteString instance Relude.String.Conversion.ConvertUtf8 Data.Text.Internal.Text Data.ByteString.Internal.ByteString instance Relude.String.Conversion.ConvertUtf8 Data.Text.Internal.Lazy.Text Data.ByteString.Internal.ByteString instance Relude.String.Conversion.ConvertUtf8 GHC.Base.String Data.ByteString.Lazy.Internal.ByteString instance Relude.String.Conversion.ConvertUtf8 Data.Text.Internal.Text Data.ByteString.Lazy.Internal.ByteString instance Relude.String.Conversion.ConvertUtf8 Data.Text.Internal.Lazy.Text Data.ByteString.Lazy.Internal.ByteString -- | Type classes for convertion between different string representations. module Relude.String -- | Functions like putStr and putStrLn but for Text, -- LText, ByteString and LByteString. module Relude.Print -- | Lifted version of putStr. putText :: MonadIO m => Text -> m () -- | Lifted version of putStrLn. putTextLn :: MonadIO m => Text -> m () -- | Lifted version of putStr. putLText :: MonadIO m => LText -> m () -- | Lifted version of putStrLn. putLTextLn :: MonadIO m => LText -> m () -- | Lifted version of putStr. putBS :: MonadIO m => ByteString -> m () -- | Lifted version of putStrLn. putBSLn :: MonadIO m => ByteString -> m () -- | Lifted version of putStr. putLBS :: MonadIO m => LByteString -> m () -- | Lifted version of putStrLn. putLBSLn :: MonadIO m => LByteString -> m () -- | Utilites to work with Either data type. module Relude.Monad.Either -- | 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 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 -- | Maps Maybe to Either wrapping default value into -- Right. -- --
-- >>> maybeToLeft True (Just "aba") -- Left "aba" -- -- >>> maybeToLeft True Nothing -- Right True --maybeToLeft :: r -> Maybe l -> Either l r -- | Maps Maybe to Either wrapping default value into -- Left. -- --
-- >>> maybeToRight True (Just "aba") -- Right "aba" -- -- >>> maybeToRight True Nothing -- Left True --maybeToRight :: l -> Maybe r -> Either l r -- | Maps left part of Either to Maybe. -- --
-- >>> leftToMaybe (Left True) -- Just True -- -- >>> leftToMaybe (Right "aba") -- Nothing --leftToMaybe :: Either l r -> Maybe l -- | Maps right part of Either to Maybe. -- --
-- >>> rightToMaybe (Left True) -- Nothing -- -- >>> rightToMaybe (Right "aba") -- Just "aba" --rightToMaybe :: Either l r -> Maybe r -- | Applies given action to Either content if Left is given -- and returns the result. In case of Right the default value will -- be returned. whenLeft :: Applicative f => a -> Either l r -> (l -> f a) -> f a -- | Applies given action to Either content if Left is given. whenLeft_ :: Applicative f => Either l r -> (l -> f ()) -> f () -- | Monadic version of whenLeft. whenLeftM :: Monad m => a -> m (Either l r) -> (l -> m a) -> m a -- | Monadic version of whenLeft_. whenLeftM_ :: Monad m => m (Either l r) -> (l -> m ()) -> m () -- | Applies given action to Either content if Right is given -- and returns the result. In case of Left the default value will -- be returned. whenRight :: Applicative f => a -> Either l r -> (r -> f a) -> f a -- | Applies given action to Either content if Right is -- given. whenRight_ :: Applicative f => Either l r -> (r -> f ()) -> f () -- | Monadic version of whenRight. whenRightM :: Monad m => a -> m (Either l r) -> (r -> m a) -> m a -- | Monadic version of whenRight_. whenRightM_ :: Monad m => m (Either l r) -> (r -> m ()) -> m () instance Data.String.IsString str => Control.Monad.Fail.MonadFail (Data.Either.Either str) -- | Reexporting useful monadic stuff. module Relude.Monad -- | This module contains safe functions to work with list type in terms of -- NonEmpty. module Relude.List.NonEmpty -- | For safe work with lists using functinons for NonEmpty. -- --
-- >>> viaNonEmpty head [1] -- Just 1 -- -- >>> viaNonEmpty head [] -- Nothing --viaNonEmpty :: (NonEmpty a -> b) -> [a] -> Maybe b -- | Performs given action over NonEmpty list if given list is non -- empty. -- --
-- >>> whenNotNull [] $ \(b :| _) -> print (not b) -- -- >>> whenNotNull [False,True] $ \(b :| _) -> print (not b) -- True --whenNotNull :: Applicative f => [a] -> (NonEmpty a -> f ()) -> f () -- | Monadic version of whenNotNull. whenNotNullM :: Monad m => m [a] -> (NonEmpty a -> m ()) -> m () -- | Utility functions to work with lists. module Relude.List -- | Re-exports most useful functionality from 'safe-exceptions'. Also -- provides some functions to work with exceptions over -- MonadError. module Relude.Exception -- | Any type that you wish to throw or catch as an exception must be an -- instance of the Exception class. The simplest case is a new -- exception type directly below the root: -- --
-- data MyException = ThisException | ThatException -- deriving Show -- -- instance Exception MyException ---- -- The default method definitions in the Exception class do what -- we need in this case. You can now throw and catch -- ThisException and ThatException as exceptions: -- --
-- *Main> throw ThisException `catch` \e -> putStrLn ("Caught " ++ show (e :: MyException))
-- Caught ThisException
--
--
-- In more complicated examples, you may wish to define a whole hierarchy
-- of exceptions:
--
-- -- --------------------------------------------------------------------- -- -- Make the root exception type for all the exceptions in a compiler -- -- data SomeCompilerException = forall e . Exception e => SomeCompilerException e -- -- instance Show SomeCompilerException where -- show (SomeCompilerException e) = show e -- -- instance Exception SomeCompilerException -- -- compilerExceptionToException :: Exception e => e -> SomeException -- compilerExceptionToException = toException . SomeCompilerException -- -- compilerExceptionFromException :: Exception e => SomeException -> Maybe e -- compilerExceptionFromException x = do -- SomeCompilerException a <- fromException x -- cast a -- -- --------------------------------------------------------------------- -- -- Make a subhierarchy for exceptions in the frontend of the compiler -- -- data SomeFrontendException = forall e . Exception e => SomeFrontendException e -- -- instance Show SomeFrontendException where -- show (SomeFrontendException e) = show e -- -- instance Exception SomeFrontendException where -- toException = compilerExceptionToException -- fromException = compilerExceptionFromException -- -- frontendExceptionToException :: Exception e => e -> SomeException -- frontendExceptionToException = toException . SomeFrontendException -- -- frontendExceptionFromException :: Exception e => SomeException -> Maybe e -- frontendExceptionFromException x = do -- SomeFrontendException a <- fromException x -- cast a -- -- --------------------------------------------------------------------- -- -- Make an exception type for a particular frontend compiler exception -- -- data MismatchedParentheses = MismatchedParentheses -- deriving Show -- -- instance Exception MismatchedParentheses where -- toException = frontendExceptionToException -- fromException = frontendExceptionFromException ---- -- We can now catch a MismatchedParentheses exception as -- MismatchedParentheses, SomeFrontendException or -- SomeCompilerException, but not other types, e.g. -- IOException: -- --
-- *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: MismatchedParentheses))
-- Caught MismatchedParentheses
-- *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeFrontendException))
-- Caught MismatchedParentheses
-- *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeCompilerException))
-- Caught MismatchedParentheses
-- *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: IOException))
-- *** Exception: MismatchedParentheses
--
class (Typeable e, Show e) => Exception e
toException :: Exception e => e -> SomeException
fromException :: Exception e => SomeException -> Maybe e
-- | Render this exception value in a human-friendly manner.
--
-- Default implementation: show.
displayException :: Exception e => e -> String
-- | The SomeException type is the root of the exception type
-- hierarchy. When an exception of type e is thrown, behind the
-- scenes it is encapsulated in a SomeException.
data SomeException
[SomeException] :: SomeException
-- | Type that represents exceptions used in cases when a particular
-- codepath is not meant to be ever executed, but happens to be executed
-- anyway.
data Bug
Bug :: SomeException -> CallStack -> Bug
-- | Generate a pure value which, when forced, will synchronously throw the
-- exception wrapped into Bug data type.
bug :: (HasCallStack, Exception e) => e -> a
-- | Pattern synonym to easy pattern matching on exceptions. So intead of
-- writing something like this:
--
--
-- isNonCriticalExc :: SomeException -> Bool
-- isNonCriticalExc e
-- | Just (_ :: NodeAttackedError) <- fromException e = True
-- | Just DialogUnexpected{} <- fromException e = True
-- | otherwise = False
--
--
-- you can use Exc pattern synonym:
--
--
-- isNonCriticalExc :: SomeException -> Bool
-- isNonCriticalExc = case
-- Exc (_ :: NodeAttackedError) -> True -- matching all exceptions of type NodeAttackedError
-- Exc DialogUnexpected{} -> True
-- _ -> False
--
--
-- This pattern is bidirectional. You can use Exc e instead of
-- toException e.
instance GHC.Show.Show Relude.Exception.Bug
instance GHC.Exception.Exception Relude.Exception.Bug
-- | This module contains useful functions to evaluate expressions to
-- weak-head normal form or just normal form. Useful to force traces or
-- error inside monadic computation or to remove space leaks.
module Relude.DeepSeq
-- | a variant of deepseq that is useful in some circumstances:
--
-- -- force x = x `deepseq` x ---- -- force x fully evaluates x, and then returns it. Note -- that force x only performs evaluation when the value of -- force x itself is demanded, so essentially it turns shallow -- evaluation into deep evaluation. -- -- force can be conveniently used in combination with -- ViewPatterns: -- --
-- {-# LANGUAGE BangPatterns, ViewPatterns #-}
-- import Control.DeepSeq
--
-- someFun :: ComplexData -> SomeResult
-- someFun (force -> !arg) = {- 'arg' will be fully evaluated -}
--
--
-- Another useful application is to combine force with
-- evaluate in order to force deep evaluation relative to other
-- IO operations:
--
--
-- import Control.Exception (evaluate)
-- import Control.DeepSeq
--
-- main = do
-- result <- evaluate $ force $ pureComputation
-- {- 'result' will be fully evaluated at this point -}
-- return ()
--
--
-- Finally, here's an exception safe variant of the readFile'
-- example:
--
-- -- readFile' :: FilePath -> IO String -- readFile' fn = bracket (openFile fn ReadMode) hClose $ \h -> -- evaluate . force =<< hGetContents h --force :: NFData a => a -> a -- | the deep analogue of $!. In the expression f $!! x, -- x is fully evaluated before the function f is -- applied to it. ($!!) :: NFData a => a -> b -> a -> b infixr 0 $!! -- | deepseq: fully evaluates the first argument, before returning -- the second. -- -- The name deepseq is used to illustrate the relationship to -- seq: where seq is shallow in the sense that it only -- evaluates the top level of its argument, deepseq traverses the -- entire data structure evaluating it completely. -- -- deepseq can be useful for forcing pending exceptions, -- eradicating space leaks, or forcing lazy I/O to happen. It is also -- useful in conjunction with parallel Strategies (see the -- parallel package). -- -- There is no guarantee about the ordering of evaluation. The -- implementation may evaluate the components of the structure in any -- order or in parallel. To impose an actual order on evaluation, use -- pseq from Control.Parallel in the parallel -- package. deepseq :: NFData a => a -> b -> b -- | A class of types that can be fully evaluated. class NFData a -- | rnf should reduce its argument to normal form (that is, fully -- evaluate all sub-components), and then return '()'. -- --
-- {-# LANGUAGE DeriveGeneric #-}
--
-- import GHC.Generics (Generic, Generic1)
-- import Control.DeepSeq
--
-- data Foo a = Foo a String
-- deriving (Eq, Generic, Generic1)
--
-- instance NFData a => NFData (Foo a)
-- instance NFData1 Foo
--
-- data Colour = Red | Green | Blue
-- deriving Generic
--
-- instance NFData Colour
--
--
-- Starting with GHC 7.10, the example above can be written more
-- concisely by enabling the new DeriveAnyClass extension:
--
--
-- {-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
--
-- import GHC.Generics (Generic)
-- import Control.DeepSeq
--
-- data Foo a = Foo a String
-- deriving (Eq, Generic, Generic1, NFData, NFData1)
--
-- data Colour = Red | Green | Blue
-- deriving (Generic, NFData)
--
--
-- -- rnf a = seq a () ---- -- However, starting with deepseq-1.4.0.0, the default -- implementation is based on DefaultSignatures allowing for -- more accurate auto-derived NFData instances. If you need the -- previously used exact default rnf method implementation -- semantics, use -- --
-- instance NFData Colour where rnf x = seq x () ---- -- or alternatively -- --
-- instance NFData Colour where rnf = rwhnf ---- -- or -- --
-- {-# LANGUAGE BangPatterns #-}
-- instance NFData Colour where rnf !_ = ()
--
rnf :: NFData a => a -> ()
-- | Alias for evaluateWHNF . force with clearer name.
evaluateNF :: (NFData a, MonadIO m) => a -> m a
-- | Alias for evaluateWHNF . rnf. Similar to evaluateNF
-- but discards resulting value.
evaluateNF_ :: (NFData a, MonadIO m) => a -> m ()
-- | Lifted alias for evaluate with clearer name.
evaluateWHNF :: MonadIO m => a -> m a
-- | Like evaluateWNHF but discards value.
evaluateWHNF_ :: MonadIO m => a -> m ()
-- | Monadic boolean combinators.
module Relude.Bool.Guard
-- | Monadic version of guard. Occasionally useful. Here some
-- complex but real-life example:
--
-- -- findSomePath :: IO (Maybe FilePath) -- -- somePath :: MaybeT IO FilePath -- somePath = do -- path <- MaybeT findSomePath -- guardM $ liftIO $ doesDirectoryExist path -- return path --guardM :: MonadPlus m => m Bool -> m () -- | Monadic version of if-then-else. -- --
-- >>> ifM (pure True) (putTextLn "True text") (putTextLn "False text") -- True text --ifM :: Monad m => m Bool -> m a -> m a -> m a -- | Monadic version of unless. -- --
-- >>> unlessM (pure False) $ putTextLn "No text :("
-- No text :(
--
-- >>> unlessM (pure True) $ putTextLn "Yes text :)"
--
unlessM :: Monad m => m Bool -> m () -> m ()
-- | Monadic version of when.
--
--
-- >>> whenM (pure False) $ putTextLn "No text :("
--
-- >>> whenM (pure True) $ putTextLn "Yes text :)"
-- Yes text :)
--
-- >>> whenM (Just True) (pure ())
-- Just ()
--
-- >>> whenM (Just False) (pure ())
-- Just ()
--
-- >>> whenM Nothing (pure ())
-- Nothing
--
whenM :: Monad m => m Bool -> m () -> m ()
-- | Convenient commonly used and very helpful functions to work with
-- Bool and also with monads.
module Relude.Bool
-- | Fixes and additions to Foldable.
module Relude.Foldable.Fold
-- | Similar to foldl' but takes a function with its arguments
-- flipped.
--
-- -- >>> flipfoldl' (/) 5 [2,3] :: Rational -- 15 % 2 --flipfoldl' :: Foldable f => (a -> b -> b) -> b -> f a -> b -- | Polymorphic version of concatMapA function. -- --
-- >>> foldMapA @[Int] (Just . replicate 3) [1..3] -- Just [1,1,1,2,2,2,3,3,3] --foldMapA :: forall b m f a. (Monoid b, Applicative m, Foldable f) => (a -> m b) -> f a -> m b -- | Polymorphic version of concatMapM function. -- --
-- >>> foldMapM @[Int] (Just . replicate 3) [1..3] -- Just [1,1,1,2,2,2,3,3,3] --foldMapM :: forall b m f a. (Monoid b, Monad m, Foldable f) => (a -> m b) -> f a -> m b -- | Stricter version of sum. -- --
-- >>> sum [1..10] -- 55 --sum :: forall a f. (Foldable f, Num a) => f a -> a -- | Stricter version of product. -- --
-- >>> product [1..10] -- 3628800 --product :: forall a f. (Foldable f, Num a) => f a -> a -- | Like elem but doesn't work on Set and HashSet for -- performance reasons. -- --
-- >>> elem 'x' ("abc" :: String)
-- False
--
-- >>> elem False (one True :: Set Bool)
-- ...
-- • Do not use 'elem' and 'notElem' methods from 'Foldable' on Set
-- Suggestions:
-- Instead of
-- elem :: (Foldable t, Eq a) => a -> t a -> Bool
-- use
-- member :: ??? -- TODO
-- ...
-- Instead of
-- notElem :: (Foldable t, Eq a) => a -> t a -> Bool
-- use
-- notMember :: ??? -- TODO
-- ...
--
elem :: (Foldable f, DisallowElem f, Eq a) => a -> f a -> Bool
-- | Like notElem but doesn't work on Set and HashSet
-- for performance reasons.
--
--
-- >>> notElem 'x' ("abc" :: String)
-- True
--
-- >>> notElem False (one True :: Set Bool)
-- ...
-- • Do not use 'elem' and 'notElem' methods from 'Foldable' on Set
-- Suggestions:
-- Instead of
-- elem :: (Foldable t, Eq a) => a -> t a -> Bool
-- use
-- member :: ??? -- TODO
-- ...
-- Instead of
-- notElem :: (Foldable t, Eq a) => a -> t a -> Bool
-- use
-- notMember :: ??? -- TODO
-- ...
--
notElem :: (Foldable f, DisallowElem f, Eq a) => a -> f a -> Bool
-- | Monadic version of all.
--
-- -- >>> allM (readMaybe >=> pure . even) ["6", "10"] -- Just True -- -- >>> allM (readMaybe >=> pure . even) ["5", "aba"] -- Just False -- -- >>> allM (readMaybe >=> pure . even) ["aba", "10"] -- Nothing --allM :: (Foldable f, Monad m) => (a -> m Bool) -> f a -> m Bool -- | Monadic version of any. -- --
-- >>> anyM (readMaybe >=> pure . even) ["5", "10"] -- Just True -- -- >>> anyM (readMaybe >=> pure . even) ["10", "aba"] -- Just True -- -- >>> anyM (readMaybe >=> pure . even) ["aba", "10"] -- Nothing --anyM :: (Foldable f, Monad m) => (a -> m Bool) -> f a -> m Bool -- | Monadic version of and. -- --
-- >>> andM [Just True, Just False] -- Just False -- -- >>> andM [Just True] -- Just True -- -- >>> andM [Just True, Just False, Nothing] -- Just False -- -- >>> andM [Just True, Nothing] -- Nothing -- -- >>> andM [putTextLn "1" >> pure True, putTextLn "2" >> pure False, putTextLn "3" >> pure True] -- 1 -- 2 -- False --andM :: (Foldable f, Monad m) => f (m Bool) -> m Bool -- | Monadic version of or. -- --
-- >>> orM [Just True, Just False] -- Just True -- -- >>> orM [Just True, Nothing] -- Just True -- -- >>> orM [Nothing, Just True] -- Nothing --orM :: (Foldable f, Monad m) => f (m Bool) -> m Bool -- | This module exports all Foldable and Traversable related -- stuff. module Relude.Foldable -- | Contains implementation of polymorhic type classes for data types -- Set and Map. module Relude.Extra.Map -- | Read-only map or set. Contains polymorphic functions which work for -- both sets and maps. class StaticMap t where { type family Key t :: Type; type family Val t :: Type; } size :: StaticMap t => t -> Int lookup :: StaticMap t => Key t -> t -> Maybe (Val t) member :: StaticMap t => Key t -> t -> Bool -- | Modifiable Map. class StaticMap t => DynamicMap t insert :: DynamicMap t => Key t -> Val t -> t -> t insertWith :: DynamicMap t => (Val t -> Val t -> Val t) -> Key t -> Val t -> t -> t delete :: DynamicMap t => Key t -> t -> t alter :: DynamicMap t => (Maybe (Val t) -> Maybe (Val t)) -> Key t -> t -> t -- | Operator version of lookup function. (!?) :: StaticMap t => t -> Key t -> Maybe (Val t) infixl 9 !? -- | Inverse of member function. notMember :: StaticMap t => Key t -> t -> Bool -- | Return the value to which the specified key is mapped, or the default -- value if this map contains no mapping for the key. lookupDefault :: StaticMap t => Val t -> Key t -> t -> Val t -- | Converts the structure to the list of the key-value pairs. -- --
-- >>> toPairs (HashMap.fromList [('a', "xxx"), ('b', "yyy")])
-- [('a',"xxx"),('b',"yyy")]
--
toPairs :: (IsList t, Item t ~ (a, b)) => t -> [(a, b)]
-- | Converts the structure to the list of the keys.
--
--
-- >>> keys (HashMap.fromList [('a', "xxx"), ('b', "yyy")])
-- "ab"
--
keys :: (IsList t, Item t ~ (a, b)) => t -> [a]
-- | Converts the structure to the list of the values.
--
--
-- >>> elems (HashMap.fromList [('a', "xxx"), ('b', "yyy")])
-- ["xxx","yyy"]
--
elems :: (IsList t, Item t ~ (a, b)) => t -> [b]
instance GHC.Classes.Ord k => Relude.Extra.Map.DynamicMap (Data.Map.Internal.Map k v)
instance (GHC.Classes.Eq k, Data.Hashable.Class.Hashable k) => Relude.Extra.Map.DynamicMap (Data.HashMap.Base.HashMap k v)
instance Relude.Extra.Map.DynamicMap (Data.IntMap.Internal.IntMap v)
instance GHC.Classes.Ord k => Relude.Extra.Map.StaticMap (Data.Map.Internal.Map k v)
instance (GHC.Classes.Eq k, Data.Hashable.Class.Hashable k) => Relude.Extra.Map.StaticMap (Data.HashMap.Base.HashMap k v)
instance Relude.Extra.Map.StaticMap (Data.IntMap.Internal.IntMap v)
instance GHC.Classes.Ord a => Relude.Extra.Map.StaticMap (Data.Set.Internal.Set a)
instance (GHC.Classes.Eq a, Data.Hashable.Class.Hashable a) => Relude.Extra.Map.StaticMap (Data.HashSet.HashSet a)
instance Relude.Extra.Map.StaticMap Data.IntSet.Internal.IntSet
-- | Functions to work with files for Text, LText,
-- ByteString and LByteString types.
module Relude.File
-- | Lifted version of readFile.
readFileText :: MonadIO m => FilePath -> m Text
-- | Lifted version of writeFile.
writeFileText :: MonadIO m => FilePath -> Text -> m ()
-- | Lifted version of appendFile.
appendFileText :: MonadIO m => FilePath -> Text -> m ()
-- | Lifted version of readFile.
readFileLText :: MonadIO m => FilePath -> m LText
-- | Lifted version of writeFile.
writeFileLText :: MonadIO m => FilePath -> LText -> m ()
-- | Lifted version of appendFile.
appendFileLText :: MonadIO m => FilePath -> LText -> m ()
-- | Lifted version of readFile.
readFileBS :: MonadIO m => FilePath -> m ByteString
-- | Lifted version of writeFile.
writeFileBS :: MonadIO m => FilePath -> ByteString -> m ()
-- | Lifted version of appendFile.
appendFileBS :: MonadIO m => FilePath -> ByteString -> m ()
-- | Lifted version of readFile.
readFileLBS :: MonadIO m => FilePath -> m LByteString
-- | Lifted version of writeFile.
writeFileLBS :: MonadIO m => FilePath -> LByteString -> m ()
-- | Lifted version of appendFile.
appendFileLBS :: MonadIO m => FilePath -> LByteString -> m ()
-- | Functions for debugging. If you left these functions in your code then
-- a warning is generated to remind you about left usages. Also some
-- functions (and data types) are convenient for prototyping.
module Relude.Debug
-- | Version of trace that leaves warning.
-- | Warning: trace remains in code
trace :: String -> a -> a
-- | Version of traceM that leaves warning.
-- | Warning: traceM remains in code
traceM :: (Applicative f) => String -> f ()
-- | Version of traceId that leaves warning.
-- | Warning: traceId remains in code
traceId :: String -> String
-- | Version of traceShow that leaves warning.
-- | Warning: traceShow remains in code
traceShow :: Show a => a -> b -> b
-- | Version of traceShowId that leaves warning.
-- | Warning: traceShowId remains in code
traceShowId :: Show a => a -> a
-- | Version of traceShowM that leaves warning.
-- | Warning: traceShowM remains in code
traceShowM :: (Show a, Applicative f) => a -> f ()
-- | error that takes Text as an argument.
error :: forall (r :: RuntimeRep). forall (a :: TYPE r). HasCallStack => Text -> a
-- | Similar to undefined but data type.
-- | Warning: Undefined type remains in code
data Undefined
-- | Warning: Undefined type remains in code
Undefined :: Undefined
-- | undefined that leaves warning in code on every usage.
-- | Warning: undefined function remains in code
undefined :: forall (r :: RuntimeRep). forall (a :: TYPE r). HasCallStack => a
instance GHC.Generics.Generic Relude.Debug.Undefined
instance Data.Data.Data Relude.Debug.Undefined
instance GHC.Enum.Bounded Relude.Debug.Undefined
instance GHC.Enum.Enum Relude.Debug.Undefined
instance GHC.Read.Read Relude.Debug.Undefined
instance GHC.Show.Show Relude.Debug.Undefined
instance GHC.Classes.Ord Relude.Debug.Undefined
instance GHC.Classes.Eq Relude.Debug.Undefined
-- | Lifted functions to work with stdin and stdout.
module Relude.Lifted.Terminal
-- | Lifted version of getLine.
getLine :: MonadIO m => m Text
-- | Lifted version of print.
print :: forall a m. (MonadIO m, Show a) => a -> m ()
-- | Lifted version of putStr.
putStr :: MonadIO m => String -> m ()
-- | Lifted version of putStrLn.
putStrLn :: MonadIO m => String -> m ()
-- | Lifted versions of base functions.
module Relude.Lifted
-- | The main module that reexports all functionality. It's allowed to use
-- it without importing any other modules. If you want to use
-- relude per-module basis then just add next lines to your
-- module to replace default Prelude:
--
--
-- {-# LANGUAGE NoImplicitPrelude #-}
--
-- import Relude
--
--
-- Alternatively, you can replace base package in your
-- dependencies with base-noprelude and add the following
-- Prelude module to your package to use relude by
-- default in every module instead of Prelude:
--
-- -- module Prelude (module Relude) where -- import Relude ---- -- This documentation section contains the description of internal module -- structure to help navigate between modules, search for interesting -- functionalities and understand where you need to put your new changes -- (if you're a contributor). -- -- Functions and types are distributed across multiple modules and -- grouped by meaning or category. Name of the module should give -- you hints regarding what this module contains. Some categories -- contain a significant amount of both reexported functions and -- functions of our own. To make it easier to understand these enormous -- chunks of functions, all reexported stuff is moved into the separate -- module with name Relude.SomeCategory.Reexport and our own -- functions and types are in Relude.SomeCategory.SomeName. For -- example, see modules Relude.Foldable.Fold and -- Relude.Foldable.Reexport. -- -- Below is a short description of what you can find under different -- modules, imported by default from Relude: -- --
-- >>> newtype Size = Size Int deriving Show -- -- >>> un @Int (Size 5) -- 5 -- -- >>> un (Size 5) == length ['a', 'x', 'b'] -- False --un :: forall a n. Coercible a n => n -> a -- | Wraps value to newtype. Behaves exactly as un but has -- more meaningnful name in case you need to convert some value to -- newtype. -- --
-- >>> newtype Flag = Flag Bool deriving (Show, Eq) -- -- >>> wrap False == Flag True -- False --wrap :: forall n a. Coercible a n => a -> n -- | Applies function to the content of newtype. This function is -- not supposed to be used on newtypes that are created with the -- help of smart constructors. -- --
-- >>> newtype Foo = Foo Bool deriving Show -- -- >>> under not (Foo True) -- Foo False -- -- >>> newtype Bar = Bar String deriving Show -- -- >>> under (filter (== 'a')) (Bar "abacaba") -- Bar "aaaa" --under :: forall n a. Coercible a n => (n -> n) -> (a -> a) -- | Lift binary function for newtypes to work over underlying -- newtype representation. -- --
-- >>> under2 @(Sum Int) (<>) (3 :: Int) 4 -- 7 -- -- >>> under2 @All (<>) True False -- False --under2 :: forall n a. Coercible a n => (n -> n -> n) -> (a -> a -> a) -- | Version of under2 that works on newtypes parametrized -- by their representation. Provided for convenience. -- --
-- >>> underF2 @Sum (<>) (3 :: Int) 4 -- 7 -- -- >>> underF2 @Max (<>) 'p' 't' -- 't' --underF2 :: forall n a. Coercible a (n a) => (n a -> n a -> n a) -> (a -> a -> a) -- | Coercible composition (#.) :: Coercible b c => (b -> c) -> (a -> b) -> (a -> c) -- | Polymorphic grouping functions. module Relude.Extra.Group -- | Groups elements using results of the given function as keys. -- --
-- >>> groupBy even [1..6] :: HashMap Bool (NonEmpty Int) -- fromList [(False,5 :| [3,1]),(True,6 :| [4,2])] --groupBy :: forall f t a. (Foldable f, DynamicMap t, Val t ~ NonEmpty a, Monoid t) => (a -> Key t) -> f a -> t -- | Similar to groupBy but keeps only one element as value. -- --
-- >>> groupOneBy even [1 .. 6] :: HashMap Bool Int -- fromList [(False,1),(True,2)] --groupOneBy :: forall f t a. (Foldable f, DynamicMap t, Val t ~ a, Monoid t) => (a -> Key t) -> f a -> t module Relude.Extra.Foldable1 -- | The class of foldable data structures that cannot be empty. class Foldable f => Foldable1 f -- | Map each element of the non-empty structure to a semigroup, and -- combine the results. -- --
-- >>> foldMap1 SG.Sum (1 :| [2, 3, 4])
-- Sum {getSum = 10}
--
foldMap1 :: (Foldable1 f, Semigroup m) => (a -> m) -> f a -> m
-- | Combine the elements of a non-empty structure using a semigroup.
--
--
-- >>> fold1 (1 :| [2, 3, 4 :: SG.Sum Int])
-- Sum {getSum = 10}
--
-- >>> fold1 (4 :| [5, 10 :: SG.Product Int])
-- Product {getProduct = 200}
--
fold1 :: (Foldable1 f, Semigroup m) => f m -> m
-- | Convert a non-empty data structre to a NonEmpty list.
--
-- -- >>> toNonEmpty (Identity 2) -- 2 :| [] --toNonEmpty :: Foldable1 f => f a -> NonEmpty a -- | The first element of a non-empty data structure. -- --
-- >>> head1 (1 :| [2, 3, 4]) -- 1 --head1 :: Foldable1 f => f a -> a -- | The last element of a non-empty data structure. -- --
-- >>> last1 (1 :| [2, 3, 4]) -- 4 --last1 :: Foldable1 f => f a -> a -- | The largest element of a non-empty data structure. -- --
-- >>> maximum1 (32 :| [64, 8, 128, 16]) -- 128 --maximum1 :: (Foldable1 f, Ord a) => f a -> a -- | The smallest elemenet of a non-empty data structure. -- --
-- >>> minimum1 (32 :| [64, 8, 128, 16]) -- 8 --minimum1 :: (Foldable1 f, Ord a) => f a -> a -- | Strictly folds non-empty structure with given function f: -- --
-- foldl1' f [x0, x1, x2 ...] = f (f x0 x1) x2 ... ---- --
-- >>> foldl1' (++) ([1,2] :| [[3,4], [5,6]]) -- [1,2,3,4,5,6] --foldl1' :: (a -> a -> a) -> NonEmpty a -> a instance Relude.Extra.Foldable1.Foldable1 GHC.Base.NonEmpty instance Relude.Extra.Foldable1.Foldable1 Data.Functor.Identity.Identity instance Relude.Extra.Foldable1.Foldable1 ((,) c) instance (Relude.Extra.Foldable1.Foldable1 f, Relude.Extra.Foldable1.Foldable1 g) => Relude.Extra.Foldable1.Foldable1 (Data.Functor.Compose.Compose f g) instance (Relude.Extra.Foldable1.Foldable1 f, Relude.Extra.Foldable1.Foldable1 g) => Relude.Extra.Foldable1.Foldable1 (Data.Functor.Product.Product f g) instance (Relude.Extra.Foldable1.Foldable1 f, Relude.Extra.Foldable1.Foldable1 g) => Relude.Extra.Foldable1.Foldable1 (Data.Functor.Sum.Sum f g) -- | Mini bounded-enum framework inside relude. module Relude.Extra.Enum -- | Returns all values of some Bounded Enum in ascending -- order. -- --
-- >>> data TrafficLight = Red | Blue | Green deriving (Show, Enum, Bounded) -- -- >>> universe :: [TrafficLight] -- [Red,Blue,Green] -- -- >>> universe :: [Bool] -- [False,True] --universe :: (Bounded a, Enum a) => [a] -- | inverseMap f creates a function that is the inverse of a -- given function f. It does so by constructing Map for -- every value f a. The implementation makes sure that the -- Map is constructed only once and then shared for every call. -- -- The complexity of reversed mapping though is <math>. -- -- Usually you want to use inverseMap to inverse show -- function. -- --
-- >>> data Color = Red | Green | Blue deriving (Show, Enum, Bounded) -- -- >>> parse = inverseMap show :: String -> Maybe Color -- -- >>> parse "Red" -- Just Red -- -- >>> parse "Black" -- Nothing --inverseMap :: forall a k. (Bounded a, Enum a, Ord k) => (a -> k) -> (k -> Maybe a) -- | Like succ, but doesn't fail on maxBound. Instead it -- returns minBound. -- --
-- >>> next False -- True -- -- >>> next True -- False -- -- >>> succ True -- *** Exception: Prelude.Enum.Bool.succ: bad argument --next :: (Eq a, Bounded a, Enum a) => a -> a -- | Like pred, but doesn't fail on minBound. Instead it -- returns maxBound. -- --
-- >>> prec False -- True -- -- >>> prec True -- False -- -- >>> pred False -- *** Exception: Prelude.Enum.Bool.pred: bad argument --prec :: (Eq a, Bounded a, Enum a) => a -> a -- | Returns Nothing if given Int outside range. -- --
-- >>> safeToEnum @Bool 0 -- Just False -- -- >>> safeToEnum @Bool 1 -- Just True -- -- >>> safeToEnum @Bool 2 -- Nothing -- -- >>> safeToEnum @Bool (-1) -- Nothing --safeToEnum :: forall a. (Bounded a, Enum a) => Int -> Maybe a -- | Contains useful functions to work with GHC callstack. module Relude.Extra.CallStack -- | This function returns the name of its caller function, but it requires -- that the caller function has HasCallStack constraint. -- Otherwise, it returns "unknown". -- --
-- >>> foo :: HasCallStack => String; foo = ownName -- -- >>> foo -- "foo" -- -- >>> bar :: HasCallStack => String; bar = foo -- -- >>> bar -- "foo" --ownName :: HasCallStack => String -- | This function returns the name of its caller of the caller function, -- but it requires that the caller function and caller of the caller -- function have HasCallStack constraint. Otherwise, it returns -- "unkown". It's useful for logging: -- --
-- >>> log :: HasCallStack => String -> IO (); log s = putStrLn $ callerName ++ ":" ++ s -- -- >>> greeting :: HasCallStack => IO (); greeting = log "Starting..." >> putStrLn "Hello!" >> log "Ending..." -- -- >>> greeting -- greeting:Starting... -- Hello! -- greeting:Ending... --callerName :: HasCallStack => String -- | Useful combinators for bifunctors inside functors. This set of -- functions is useful when you want to work with types like these ones: -- --
-- foo :: IO (Either a b) -- bar :: IO (a, b) -- -- baz :: Maybe (Either a b) -- qux :: Maybe (a, b) --module Relude.Extra.Bifunctor -- | Fmaps functions for nested bifunctor. Short for fmap (bimap f -- g). -- --
-- >>> bimapF not length $ Just (False, ['a', 'b']) -- Just (True,2) --bimapF :: (Functor f, Bifunctor p) => (a -> c) -> (b -> d) -> f (p a b) -> f (p c d) -- | Short for fmap . first. -- --
-- >>> firstF not $ Just (False, ['a', 'b']) -- Just (True,"ab") --firstF :: (Functor f, Bifunctor p) => (a -> c) -> f (p a b) -> f (p c b) -- | Short for fmap . second. -- --
-- >>> secondF length $ Just (False, ['a', 'b']) -- Just (False,2) --secondF :: (Functor f, Bifunctor p) => (b -> d) -> f (p a b) -> f (p a d) -- | Unsafe functions to work with lists and Maybe. Sometimes -- unavoidable but it's better not to use them. This module is intended -- to be imported qualified and it's not even included in default prelude -- exports. -- --
-- import qualified Relude.Unsafe as Unsafe -- -- foo :: [a] -> a -- foo = Unsafe.head --module Relude.Unsafe -- | 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 !! -- | 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] -- | Extract the first element of a list, which must be non-empty. head :: () => [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 -- | Similar to !! but with flipped arguments. at :: Int -> [a] -> a