-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | Total Prelude with Text and Monad transformers -- -- Modern Prelude which provides safe alternatives for most of the -- partial functions. Text is preferred over String. Container types and -- Monad transformers are provided. Most important - this Prelude avoids -- fanciness. This means it just reexports from base and commonly used -- libraries and doesn't invent its own stuff. Everything is in one file. @package intro @version 0.0.2.2 -- | Modern Prelude which provides safe alternatives for most of the -- partial functions. Text is preferred over String. -- Container types and Monad transformers are provided. Most important - -- this Prelude avoids fanciness. This means it just reexports from base -- and commonly used libraries and doesn't invent its own stuff. -- Everything is in one file. -- -- Some Prelude functions are missing from Intro. More -- general variants are available for the following functions: -- --
-- >>> map (const 42) [0..3] -- [42,42,42,42] --const :: a -> b -> a -- | flip f takes its (first) two arguments in the reverse -- order of f. flip :: (a -> b -> c) -> b -> a -> c -- | Application operator. This operator is redundant, since ordinary -- application (f x) means the same as (f $ x). -- However, $ has low, right-associative binding precedence, so it -- sometimes allows parentheses to be omitted; for example: -- --
-- f $ g $ h x = f (g (h x)) ---- -- It is also useful in higher-order situations, such as map -- ($ 0) xs, or zipWith ($) fs xs. ($) :: (a -> b) -> a -> b infixr 0 $ -- | Strict (call-by-value) application operator. It takes a function and -- an argument, evaluates the argument to weak head normal form (WHNF), -- then calls the function with that value. ($!) :: (a -> b) -> a -> b infixr 0 $! -- | & is a reverse application operator. This provides -- notational convenience. Its precedence is one higher than that of the -- forward application operator $, which allows & to be -- nested in $. (&) :: a -> (a -> b) -> b infixl 1 & -- | fix f is the least fixed point of the function -- f, i.e. the least defined x such that f x = -- x. fix :: (a -> a) -> a -- | (*) `on` f = \x y -> f x * f y. -- -- Typical usage: sortBy (compare `on` -- fst). -- -- Algebraic properties: -- --
((*) `on` f) `on` g = (*) `on` (f . g)
flip on f . flip on g = flip on (g . -- f)
-- >>> 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 "not" not :: Bool -> Bool -- | otherwise is defined as the value True. It helps to make -- guards more readable. eg. -- --
-- f x | x < 0 = ... -- | otherwise = ... --otherwise :: Bool -- | The 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 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 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 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 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 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 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 IsList class and its methods are intended to be used in -- conjunction with the OverloadedLists extension. class IsList l where type Item l :: * where { type family Item l :: *; } -- | The fromList function constructs the structure l from -- the given list of Item l fromList :: IsList l => [Item l] -> l -- | 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]) -- | drop n xs returns the suffix of xs after the -- first n elements, or [] if n > length -- xs: -- --
-- drop 6 "Hello World!" == "World!" -- drop 3 [1,2,3,4,5] == [4,5] -- drop 3 [1,2] == [] -- drop 3 [] == [] -- drop (-1) [1,2] == [1,2] -- drop 0 [1,2] == [1,2] ---- -- It is an instance of the more general genericDrop, in which -- n may be of any integral type. drop :: Int -> [a] -> [a] -- | Drop a number of elements from the end of the list. -- --
-- dropEnd 3 "hello" == "he" -- dropEnd 5 "bye" == "" -- dropEnd (-1) "bye" == "bye" -- \i xs -> dropEnd i xs `isPrefixOf` xs -- \i xs -> length (dropEnd i xs) == max 0 (length xs - max 0 i) -- \i -> take 3 (dropEnd 5 [i..]) == take 3 [i..] --dropEnd :: Int -> [a] -> [a] -- | dropWhile p xs returns the suffix remaining after -- takeWhile p xs: -- --
-- dropWhile (< 3) [1,2,3,4,5,1,2,3] == [3,4,5,1,2,3] -- dropWhile (< 9) [1,2,3] == [] -- dropWhile (< 0) [1,2,3] == [1,2,3] --dropWhile :: (a -> Bool) -> [a] -> [a] -- | The dropWhileEnd function drops the largest suffix of a list in -- which the given predicate holds for all elements. For example: -- --
-- dropWhileEnd isSpace "foo\n" == "foo"
-- dropWhileEnd isSpace "foo bar" == "foo bar"
-- dropWhileEnd isSpace ("foo\n" ++ undefined) == "foo" ++ undefined
--
dropWhileEnd :: (a -> Bool) -> [a] -> [a]
-- | filter, applied to a predicate and a list, returns the list of
-- those elements that satisfy the predicate; i.e.,
--
-- -- filter p xs = [ x | x <- xs, p x] --filter :: (a -> Bool) -> [a] -> [a] -- | The group function takes a list and returns a list of lists -- such that the concatenation of the result is equal to the argument. -- Moreover, each sublist in the result contains only equal elements. For -- example, -- --
-- group "Mississippi" = ["M","i","ss","i","ss","i","pp","i"] ---- -- It is a special case of groupBy, which allows the programmer to -- supply their own equality test. group :: Eq a => [a] -> [[a]] -- | The groupBy function is the non-overloaded version of -- group. groupBy :: (a -> a -> Bool) -> [a] -> [[a]] -- | A version of group where the equality is done on some extracted -- value. groupOn :: Eq b => (a -> b) -> [a] -> [[a]] -- | 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]] -- | 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 :: [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. isPrefixOf :: Eq a => [a] -> [a] -> Bool -- | The isSuffixOf function takes two lists and returns True -- iff the first list is a suffix of the second. The second list must be -- finite. isSuffixOf :: Eq a => [a] -> [a] -> Bool -- | iterate f x returns an infinite list of repeated -- applications of f to x: -- --
-- iterate f x == [x, f x, f (f x), ...] --iterate :: (a -> a) -> a -> [a] -- | lookup key assocs looks up a key in an association -- list. lookup :: Eq a => a -> [(a, b)] -> Maybe b -- | O(n log n). The nubOrd function removes duplicate -- elements from a list. In particular, it keeps only the first -- occurrence of each element. Unlike the standard nub operator, -- this version requires an Ord instance and consequently runs -- asymptotically faster. -- --
-- nubOrd "this is a test" == "this ae"
-- nubOrd (take 4 ("this" ++ undefined)) == "this"
-- \xs -> nubOrd xs == nub xs
--
nubOrd :: Ord a => [a] -> [a]
-- | A version of nubOrd with a custom predicate.
--
-- -- nubOrdBy (compare `on` length) ["a","test","of","this"] == ["a","test","of"] --nubOrdBy :: (a -> a -> Ordering) -> [a] -> [a] -- | A version of nubOrd which operates on a portion of the value. -- --
-- nubOrdOn length ["a","test","of","this"] == ["a","test","of"] --nubOrdOn :: Ord b => (a -> b) -> [a] -> [a] -- | The permutations function returns the list of all permutations -- of the argument. -- --
-- permutations "abc" == ["abc","bac","cba","bca","cab","acb"] --permutations :: [a] -> [[a]] -- | repeat x is an infinite list, with x the -- value of every element. repeat :: a -> [a] -- | replicate n x is a list of length n with -- x the value of every element. It is an instance of the more -- general genericReplicate, in which n may be of any -- integral type. replicate :: Int -> a -> [a] -- | reverse xs returns the elements of xs in -- reverse order. xs must be finite. reverse :: [a] -> [a] -- | scanl is similar to foldl, but returns a list of -- successive reduced values from the left: -- --
-- scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...] ---- -- Note that -- --
-- last (scanl f z xs) == foldl f z xs. --scanl :: (b -> a -> b) -> b -> [a] -> [b] -- | 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] -- | 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. sort :: Ord a => [a] -> [a] -- | The sortBy function is the non-overloaded version of -- sort. sortBy :: (a -> a -> Ordering) -> [a] -> [a] -- | Sort a list by comparing the results of a key function applied to each -- element. sortOn f is equivalent to sortBy (comparing -- f), but has the performance advantage of only evaluating -- f once for each element in the input list. This is called the -- decorate-sort-undecorate paradigm, or Schwartzian transform. sortOn :: Ord b => (a -> b) -> [a] -> [a] -- | span, applied to a predicate p and a list xs, -- returns a tuple where first element is longest prefix (possibly empty) -- of xs of elements that satisfy p and second element -- is the remainder of the list: -- --
-- span (< 3) [1,2,3,4,1,2,3,4] == ([1,2],[3,4,1,2,3,4]) -- span (< 9) [1,2,3] == ([1,2,3],[]) -- span (< 0) [1,2,3] == ([],[1,2,3]) ---- -- span p xs is equivalent to (takeWhile p xs, -- dropWhile p xs) span :: (a -> Bool) -> [a] -> ([a], [a]) -- | 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])
-- | The subsequences function returns the list of all subsequences
-- of the argument.
--
-- -- subsequences "abc" == ["","a","b","ab","c","ac","bc","abc"] --subsequences :: [a] -> [[a]] -- | The tails function returns all final segments of the argument, -- longest first. For example, -- --
-- tails "abc" == ["abc", "bc", "c",""] ---- -- Note that tails has the following strictness property: -- tails _|_ = _|_ : _|_ tails :: [a] -> [[a]] -- | take n, applied to a list xs, returns the -- prefix of xs of length n, or xs itself if -- n > length xs: -- --
-- take 5 "Hello World!" == "Hello" -- take 3 [1,2,3,4,5] == [1,2,3] -- take 3 [1,2] == [1,2] -- take 3 [] == [] -- take (-1) [1,2] == [] -- take 0 [1,2] == [] ---- -- It is an instance of the more general genericTake, in which -- n may be of any integral type. take :: Int -> [a] -> [a] -- | Take a number of elements from the end of the list. -- --
-- takeEnd 3 "hello" == "llo" -- takeEnd 5 "bye" == "bye" -- takeEnd (-1) "bye" == "" -- \i xs -> takeEnd i xs `isSuffixOf` xs -- \i xs -> length (takeEnd i xs) == min (max 0 i) (length xs) --takeEnd :: Int -> [a] -> [a] -- | takeWhile, applied to a predicate p and a list -- xs, returns the longest prefix (possibly empty) of -- xs of elements that satisfy p: -- --
-- takeWhile (< 3) [1,2,3,4,1,2,3,4] == [1,2] -- takeWhile (< 9) [1,2,3] == [1,2,3] -- takeWhile (< 0) [1,2,3] == [] --takeWhile :: (a -> Bool) -> [a] -> [a] -- | 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]] -- | 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] -- | unzip transforms a list of pairs into a list of first -- components and a list of second components. unzip :: [(a, b)] -> ([a], [b]) -- | The unzip3 function takes a list of triples and returns three -- lists, analogous to unzip. unzip3 :: [(a, b, c)] -> ([a], [b], [c]) -- | zip takes two lists and returns a list of corresponding pairs. -- If one input list is short, excess elements of the longer list are -- discarded. -- -- zip is right-lazy: -- --
-- zip [] _|_ = [] --zip :: [a] -> [b] -> [(a, b)] -- | zip3 takes three lists and returns a list of triples, analogous -- to zip. zip3 :: [a] -> [b] -> [c] -> [(a, b, c)] -- | zipWith generalises zip by zipping with the function -- given as the first argument, instead of a tupling function. For -- example, zipWith (+) is applied to two lists to -- produce the list of corresponding sums. -- -- zipWith is right-lazy: -- --
-- zipWith f [] _|_ = [] --zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] -- | The zipWith3 function takes a function which combines three -- elements, as well as three lists and returns a list of their -- point-wise combination, analogous to zipWith. zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d] headDef :: a -> [a] -> a headMay :: [a] -> Maybe a initDef :: [a] -> [a] -> [a] initMay :: [a] -> Maybe [a] lastDef :: a -> [a] -> a lastMay :: [a] -> Maybe a -- |
-- tailDef [12] [] = [12] -- tailDef [12] [1,3,4] = [3,4] --tailDef :: [a] -> [a] -> [a] -- |
-- tailMay [] = Nothing -- tailMay [1,3,4] = Just [3,4] --tailMay :: [a] -> Maybe [a] cycleMay :: [a] -> Maybe [a] cycleDef :: [a] -> [a] -> [a] -- | Non-empty (and non-strict) list type. data NonEmpty a :: * -> * (:|) :: a -> [a] -> NonEmpty a -- | scanl1 is a variant of scanl that has no starting value -- argument: -- --
-- scanl1 f [x1, x2, ...] == x1 :| [x1 `f` x2, x1 `f` (x2 `f` x3), ...] --scanl1 :: (a -> a -> a) -> NonEmpty a -> NonEmpty a -- | scanr1 is a variant of scanr that has no starting value -- argument. scanr1 :: (a -> a -> a) -> NonEmpty a -> NonEmpty a -- | Extract the first component of a pair. fst :: (a, b) -> a -- | Extract the second component of a pair. snd :: (a, b) -> b -- | curry converts an uncurried function to a curried function. curry :: ((a, b) -> c) -> a -> b -> c -- | uncurry converts a curried function to a function on pairs. uncurry :: (a -> b -> c) -> (a, b) -> c -- | Swap the components of a pair. swap :: (a, b) -> (b, a) -- | The Either type represents values with two possibilities: a -- value of type Either a b is either Left -- a or Right b. -- -- The Either type is sometimes used to represent a value which is -- either correct or an error; by convention, the Left constructor -- is used to hold an error value and the Right constructor is -- used to hold a correct value (mnemonic: "right" also means "correct"). -- --
-- >>> let s = Left "foo" :: Either String Int -- -- >>> s -- Left "foo" -- -- >>> let n = Right 3 :: Either String Int -- -- >>> n -- Right 3 -- -- >>> :type s -- s :: Either String Int -- -- >>> :type n -- n :: Either String Int ---- -- The fmap from our Functor instance will ignore -- Left values, but will apply the supplied function to values -- contained in a Right: -- --
-- >>> let s = Left "foo" :: Either String Int -- -- >>> let n = Right 3 :: Either String Int -- -- >>> fmap (*2) s -- Left "foo" -- -- >>> fmap (*2) n -- Right 6 ---- -- The Monad instance for Either allows us to chain -- together multiple actions which may fail, and fail overall if any of -- the individual steps failed. First we'll write a function that can -- either parse an Int from a Char, or fail. -- --
-- >>> import Data.Char ( digitToInt, isDigit )
--
-- >>> :{
-- let parseEither :: Char -> Either String Int
-- parseEither c
-- | isDigit c = Right (digitToInt c)
-- | otherwise = Left "parse error"
--
-- >>> :}
--
--
-- The following should work, since both '1' and '2'
-- can be parsed as Ints.
--
--
-- >>> :{
-- let parseMultiple :: Either String Int
-- parseMultiple = do
-- x <- parseEither '1'
-- y <- parseEither '2'
-- return (x + y)
--
-- >>> :}
--
--
-- -- >>> parseMultiple -- Right 3 ---- -- But the following should fail overall, since the first operation where -- we attempt to parse 'm' as an Int will fail: -- --
-- >>> :{
-- let parseMultiple :: Either String Int
-- parseMultiple = do
-- x <- parseEither 'm'
-- y <- parseEither '2'
-- return (x + y)
--
-- >>> :}
--
--
-- -- >>> parseMultiple -- Left "parse error" --data Either a b :: * -> * -> * Left :: a -> Either a b Right :: b -> Either a b -- | 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 -- | 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 -- | 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 -- | 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 -- | 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] -- | 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] -- | 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]) -- | Given an Either, convert it to a Maybe, where -- Left becomes Nothing. -- --
-- \x -> eitherToMaybe (Left x) == Nothing -- \x -> eitherToMaybe (Right x) == Just x --eitherToMaybe :: Either a b -> Maybe b -- | Given a Maybe, convert it to an Either, providing a -- suitable value for the Left should the value be Nothing. -- --
-- \a b -> maybeToEither a (Just b) == Right b -- \a -> maybeToEither a Nothing == Left a --maybeToEither :: a -> Maybe b -> Either a b -- | The character type Char is an enumeration whose values -- represent Unicode (or equivalently ISO/IEC 10646) 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 :: * -- | A String is a list of characters. String constants in Haskell -- are values of type String. type String = [Char] -- | A space efficient, packed, unboxed Unicode text type. data Text :: * -- | Alias for lazy Text type LText = Text -- | 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 :: * -- | Alias for lazy ByteString type LByteString = ByteString -- | Class for string-like datastructures; used by the overloaded string -- extension (-XOverloadedStrings in GHC). class IsString a fromString :: IsString a => String -> a class ConvertibleStrings a b convertString :: ConvertibleStrings a b => a -> b -- | A Map from keys k to values a. data Map k a :: * -> * -> * -- | Alias for lazy Map type LMap = Map -- | A set of values a. data Set a :: * -> * -- | A map of integers to values a. data IntMap a :: * -> * -- | A set of integers. data IntSet :: * -- | A map from keys to values. A map cannot contain duplicate keys; each -- key can map to at most one value. data HashMap k v :: * -> * -> * -- | Alias for lazy HashMap type LHashMap = HashMap -- | A set of values. A set cannot contain duplicate values. data HashSet a :: * -> * -- | The class of types that can be converted to a hash value. -- -- Minimal implementation: hashWithSalt. class Hashable a -- | General-purpose finite sequences. data Seq a :: * -> * -- | A difference list is a function that, given a list, returns the -- original contents of the difference list prepended to the given list. -- -- This structure supports O(1) append and snoc operations on -- lists, making it very useful for append-heavy uses (esp. left-nested -- uses of ++), such as logging and pretty printing. -- -- Here is an example using DList as the state type when printing a tree -- with the Writer monad: -- --
-- import Control.Monad.Writer -- import Data.DList -- -- data Tree a = Leaf a | Branch (Tree a) (Tree a) -- -- flatten_writer :: Tree x -> DList x -- flatten_writer = snd . runWriter . flatten -- where -- flatten (Leaf x) = tell (singleton x) -- flatten (Branch x y) = flatten x >> flatten y --data DList a :: * -> * -- | Invariant: Jn# and Jp# are used iff value doesn't fit in -- S# -- -- Useful properties resulting from the invariants: -- -- data Integer :: * -- | Type representing arbitrary-precision non-negative integers. -- -- Operations whose result would be negative throw -- (Underflow :: ArithException). data Natural :: * -- | 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 :: * -- | 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 :: * -- | 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 :: * -- | Rational numbers, with numerator and denominator of some -- Integral type. data Ratio a :: * -> * -- | Arbitrary-precision rational numbers, represented as a ratio of two -- Integer values. A rational number may be constructed using the -- % operator. type Rational = Ratio Integer -- | Forms the ratio of two integral numbers. (%) :: Integral a => a -> a -> Ratio a infixl 7 % -- | Extract the numerator of the ratio in reduced form: the numerator and -- denominator have no common factor and the denominator is positive. numerator :: Ratio a -> a -- | Extract the denominator of the ratio in reduced form: the numerator -- and denominator have no common factor and the denominator is positive. denominator :: Ratio a -> a -- | approxRational, applied to two real fractional numbers -- x and epsilon, returns the simplest rational number -- within epsilon of x. A rational number y is -- said to be simpler than another y' if -- --
-- abs x * signum x == x ---- -- For real numbers, the signum is either -1 (negative), -- 0 (zero) or 1 (positive). signum :: Num a => a -> a -- | Conversion from an Integer. An integer literal represents the -- application of the function fromInteger to the appropriate -- value of type Integer, so such literals have type -- (Num a) => a. fromInteger :: Num a => Integer -> a -- | the same as flip (-). -- -- Because - is treated specially in the Haskell grammar, -- (- e) is not a section, but an application of -- prefix negation. However, (subtract -- exp) is equivalent to the disallowed section. subtract :: Num a => a -> a -> a -- | raise a number to a non-negative integral power (^) :: (Num a, Integral b) => a -> b -> a infixr 8 ^ class (Num a, Ord a) => Real a -- | the rational equivalent of its real argument with full precision toRational :: Real a => a -> Rational -- | general coercion to fractional types realToFrac :: (Real a, Fractional b) => a -> b -- | 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 -- | general coercion from integral types fromIntegral :: (Integral a, Num b) => a -> b even :: Integral a => a -> Bool odd :: Integral a => a -> Bool -- | 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 -- | raise a number to an integral power (^^) :: (Fractional a, Integral b) => a -> b -> a infixr 8 ^^ -- | Trigonometric and hyperbolic functions and related functions. class Fractional a => Floating a pi :: Floating a => a exp :: Floating a => a -> a log :: Floating a => a -> a sqrt :: Floating a => a -> a (**) :: Floating a => a -> a -> a logBase :: Floating a => a -> a -> a sin :: Floating a => a -> a cos :: Floating a => a -> a tan :: Floating a => a -> a asin :: Floating a => a -> a acos :: Floating a => a -> a atan :: Floating a => a -> a sinh :: Floating a => a -> a cosh :: Floating a => a -> a tanh :: Floating a => a -> a asinh :: Floating a => a -> a acosh :: Floating a => a -> a atanh :: Floating a => a -> a -- | 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: -- --
clearBit zeroBits n == -- zeroBits
setBit zeroBits n == bit -- n
testBit zeroBits n == False
popCount zeroBits == 0
-- finiteBitSize = bitSize -- bitSizeMaybe = Just . finiteBitSize --finiteBitSize :: FiniteBits b => b -> Int -- | Count number of zero bits preceding the most significant set bit. -- --
-- countLeadingZeros (zeroBits :: a) = finiteBitSize (zeroBits :: a) ---- -- countLeadingZeros can be used to compute log base 2 via -- --
-- logBase2 x = finiteBitSize x - 1 - countLeadingZeros x ---- -- Note: The default implementation for this method is intentionally -- naive. However, the instances provided for the primitive integral -- types are implemented using CPU specific machine instructions. countLeadingZeros :: FiniteBits b => b -> Int -- | Count number of zero bits following the least significant set bit. -- --
-- countTrailingZeros (zeroBits :: a) = finiteBitSize (zeroBits :: a) -- countTrailingZeros . negate = countTrailingZeros ---- -- The related find-first-set operation can be expressed in terms -- of countTrailingZeros as follows -- --
-- findFirstSet x = 1 + countTrailingZeros x ---- -- Note: The default implementation for this method is intentionally -- naive. However, the instances provided for the primitive integral -- types are implemented using CPU specific machine instructions. countTrailingZeros :: FiniteBits b => b -> Int -- | Conversion of values to readable Strings. -- -- Derived instances of Show have the following properties, which -- are compatible with derived instances of Read: -- --
-- 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, -- --
-- 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 --class Read a -- | Lifting of the Read class to unary type constructors. class Read1 (f :: * -> *) -- | Lifting of the Read class to binary type constructors. class Read2 (f :: * -> * -> *) -- | Parse a string type using the Read instance. Succeeds if there -- is exactly one valid result. readMaybe :: (Read b, ConvertibleStrings a String) => a -> Maybe b -- | 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 -- | Lifting of the Eq class to unary type constructors. class Eq1 (f :: * -> *) -- | Lifting of the Eq class to binary type constructors. class Eq2 (f :: * -> * -> *) -- | 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 -- | Lifting of the Ord class to unary type constructors. class Eq1 f => Ord1 (f :: * -> *) -- | Lifting of the Ord class to binary type constructors. class Eq2 f => Ord2 (f :: * -> * -> *) data Ordering :: * LT :: Ordering EQ :: Ordering GT :: 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 -- -- Provides Show and Read instances (since: -- 4.7.0.0). newtype Down a :: * -> * Down :: a -> Down a -- |
-- comparing p x y = compare (p x) (p y) ---- -- Useful combinator for use in conjunction with the xxxBy -- family of functions from Data.List, for example: -- --
-- ... sortBy (comparing fst) ... --comparing :: Ord a => (b -> a) -> b -> b -> Ordering -- | 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 -- | 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] toEnumMay :: (Enum a, Bounded a) => Int -> Maybe a toEnumDef :: (Enum a, Bounded a) => a -> Int -> a -- | The Bounded class is used to name the upper and lower limits of -- a type. Ord is not a superclass of Bounded since types -- that are not totally ordered may also have upper and lower bounds. -- -- The Bounded class may be derived for any enumeration type; -- minBound is the first constructor listed in the data -- declaration and maxBound is the last. Bounded may also -- be derived for single-constructor datatypes whose constituent types -- are in Bounded. class Bounded a minBound :: Bounded a => a maxBound :: Bounded a => a -- | A class for categories. id and (.) must form a monoid. class Category k (cat :: k -> k -> *) -- | the identity morphism id :: Category k cat => cat a a -- | morphism composition (.) :: Category k cat => cat b c -> cat a b -> cat a c -- | Right-to-left composition (<<<) :: Category k cat => cat b c -> cat a b -> cat a c infixr 1 <<< -- | Left-to-right composition (>>>) :: Category k cat => cat a b -> cat b c -> cat a c infixr 1 >>> -- | The class of semigroups (types with an associative binary operation). class Semigroup a -- | An associative operation. -- --
-- (a <> b) <> c = a <> (b <> c) ---- -- If a is also a Monoid we further require -- --
-- (<>) = mappend --(<>) :: 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 -- | Use Option (First a) to get the behavior of -- First from Data.Monoid. newtype First a :: * -> * First :: a -> First a [getFirst] :: First a -> a -- | Use Option (Last a) to get the behavior of -- Last from Data.Monoid newtype Last a :: * -> * Last :: a -> Last a [getLast] :: Last a -> a newtype Min a :: * -> * Min :: a -> Min a [getMin] :: Min a -> a newtype Max a :: * -> * Max :: a -> Max a [getMax] :: Max a -> a -- | Option is effectively Maybe with a better instance of -- Monoid, built off of an underlying Semigroup instead of -- an underlying Monoid. -- -- Ideally, this type would not exist at all and we would just fix the -- Monoid instance of Maybe newtype Option a :: * -> * Option :: Maybe a -> Option a [getOption] :: Option a -> Maybe a -- | The class of monoids (types with an associative binary operation that -- has an identity). Instances should satisfy the following laws: -- --
mappend mempty x = x
mappend x mempty = x
mappend x (mappend y z) = mappend (mappend x y) z
mconcat = foldr mappend mempty
-- 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 :: * -> *) -- | 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 -- | 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 <$> -- | A synonym for fmap. -- --
-- map = fmap --map :: Functor f => (a -> b) -> f a -> f b -- | 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 () -- | The Const functor. newtype Const k a (b :: k) :: forall k. * -> k -> * Const :: a -> Const k a [getConst] :: Const k a -> a -- | Identity functor and monad. (a non-strict monad) newtype Identity a :: * -> * Identity :: a -> Identity a [runIdentity] :: Identity a -> a -- | 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 ---- -- sum, product, maximum, and minimum -- should all be essentially equivalent to foldMap forms, such -- as -- --
-- sum = getSum . foldMap Sum ---- -- but may be less defined. -- -- If the type is also a Functor instance, it should satisfy -- --
-- foldMap f = fold . fmap f ---- -- which implies that -- --
-- foldMap f . fmap g = foldMap (f . g) --class Foldable (t :: * -> *) -- | Combine the elements of a structure using a monoid. fold :: (Foldable t, Monoid m) => t m -> m -- | Map each element of the structure to a monoid, and combine the -- results. foldMap :: (Foldable t, Monoid m) => (a -> m) -> t a -> m -- | Right-associative fold of a structure. -- -- In the case of lists, foldr, when applied to a binary operator, -- a starting value (typically the right-identity of the operator), and a -- list, reduces the list using the binary operator, from right to left: -- --
-- foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...) ---- -- Note that, since the head of the resulting expression is produced by -- an application of the operator to the first element of the list, -- foldr can produce a terminating expression from an infinite -- list. -- -- For a general Foldable structure this should be semantically -- identical to, -- --
-- foldr f z = foldr f z . toList --foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b -- | Right-associative fold of a structure, but with strict application of -- the operator. foldr' :: Foldable t => (a -> b -> b) -> b -> t a -> b -- | Left-associative fold of a structure but with strict application of -- the operator. -- -- This ensures that each step of the fold is forced to weak head normal -- form before being applied, avoiding the collection of thunks that -- would otherwise occur. This is often what you want to strictly reduce -- a finite list to a single, monolithic result (e.g. length). -- -- For a general Foldable structure this should be semantically -- identical to, -- --
-- foldl f z = foldl' f z . toList --foldl' :: Foldable t => (b -> a -> b) -> b -> t a -> b -- | List of elements of a structure, from left to right. toList :: Foldable t => t a -> [a] -- | Test whether the structure is empty. The default implementation is -- optimized for structures that are similar to cons-lists, because there -- is no general way to do better. null :: Foldable t => t a -> Bool -- | Returns the size/length of a finite structure as an Int. The -- default implementation is optimized for structures that are similar to -- cons-lists, because there is no general way to do better. length :: Foldable t => t a -> Int -- | Does the element occur in the structure? elem :: (Foldable t, Eq a) => a -> t a -> Bool -- | The sum function computes the sum of the numbers of a -- structure. sum :: (Foldable t, Num a) => t a -> a -- | The product function computes the product of the numbers of a -- structure. product :: (Foldable t, Num a) => t a -> a -- | 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 => forall a. 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 => forall a. t a -> Int -- | Monadic fold over the elements of a structure, associating to the -- right, i.e. from right to left. foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b -- | Monadic fold over the elements of a structure, associating to the -- left, i.e. from left to right. foldlM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and ignore the results. For a version that doesn't -- ignore the results see traverse. traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f () -- | for_ is traverse_ with its arguments flipped. For a -- version that doesn't ignore the results see for. -- --
-- >>> for_ [1..4] print -- 1 -- 2 -- 3 -- 4 --for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f () -- | The sum of a collection of actions, generalizing concat. asum :: (Foldable t, Alternative f) => t (f a) -> f a -- | Map a function over all the elements of a container and concatenate -- the resulting lists. concatMap :: Foldable t => (a -> [b]) -> t a -> [b] -- | 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 -- | The find function takes a predicate and a structure and returns -- the leftmost element of the structure matching the predicate, or -- Nothing if there is no such element. find :: Foldable t => (a -> Bool) -> t a -> Maybe a -- | notElem is the negation of elem. notElem :: (Foldable t, Eq a) => a -> t a -> Bool infix 4 `notElem` -- | 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 () foldl1May :: Foldable t => (a -> a -> a) -> t a -> Maybe a foldl1Def :: Foldable t => a -> (a -> a -> a) -> t a -> a foldr1May :: Foldable t => (a -> a -> a) -> t a -> Maybe a foldr1Def :: Foldable t => a -> (a -> a -> a) -> t a -> a maximumByMay :: Foldable t => (a -> a -> Ordering) -> t a -> Maybe a maximumByDef :: Foldable t => a -> (a -> a -> Ordering) -> t a -> a minimumByMay :: Foldable t => (a -> a -> Ordering) -> t a -> Maybe a minimumByDef :: Foldable t => a -> (a -> a -> Ordering) -> t a -> a maximumMay :: (Foldable t, Ord a) => t a -> Maybe a maximumDef :: (Foldable t, Ord a) => a -> t a -> a minimumMay :: (Foldable t, Ord a) => t a -> Maybe a minimumDef :: (Foldable t, Ord a) => a -> t a -> a -- | 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: -- --
pure id <*> -- v = v
pure (.) <*> u -- <*> v <*> w = u <*> (v -- <*> w)
pure f <*> -- pure x = pure (f x)
u <*> pure y = -- pure ($ y) <*> u
-- f <$> ZipList xs1 <*> ... <*> ZipList xsn = ZipList (zipWithn f xs1 ... xsn) --newtype ZipList a :: * -> * ZipList :: [a] -> ZipList a [getZipList] :: ZipList a -> [a] -- | A variant of <*> with the arguments reversed. (<**>) :: Applicative f => f a -> f (a -> b) -> f b infixl 4 <**> -- | Lift a binary function to actions. liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c -- | Lift a ternary function to actions. liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d -- | () lifted to an Applicative. -- --
-- skip = pure () --skip :: Applicative m => m () -- | <> lifted to Applicative (<>^) :: (Applicative f, Semigroup a) => f a -> f a -> f a infixr 6 <>^ -- | A monoid on applicative functors. -- -- If defined, some and many should be the least solutions -- of the equations: -- -- class Applicative f => Alternative (f :: * -> *) -- | The identity of <|> empty :: Alternative f => f a -- | An associative binary operation (<|>) :: Alternative f => f a -> f a -> f a -- | Zero or more. many :: Alternative f => f a -> f [a] -- | One or none. optional :: Alternative f => f a -> f (Maybe a) -- | some1 x sequences x one or more times. some1 :: Alternative f => f a -> f (NonEmpty a) -- | The Monad class defines the basic operations over a -- monad, a concept from a branch of mathematics known as -- category theory. From the perspective of a Haskell programmer, -- however, it is best to think of a monad as an abstract datatype -- of actions. Haskell's do expressions provide a convenient -- syntax for writing monadic expressions. -- -- Instances of Monad should satisfy the following laws: -- -- -- -- Furthermore, the Monad and Applicative operations should -- relate as follows: -- -- -- -- The above laws imply: -- -- -- -- and that pure and (<*>) satisfy the applicative -- functor laws. -- -- The instances of Monad for lists, Maybe and IO -- defined in the Prelude satisfy these laws. class Applicative m => Monad (m :: * -> *) -- | Sequentially compose two actions, passing any value produced by the -- first as an argument to the second. (>>=) :: Monad m => m a -> (a -> m b) -> m b -- | 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 -- | Same as >>=, but with the arguments interchanged. (=<<) :: Monad m => (a -> m b) -> m a -> m b infixr 1 =<< -- | Right-to-left Kleisli composition of monads. -- (>=>), with the arguments flipped. -- -- Note how this operator resembles function composition -- (.): -- --
-- (.) :: (b -> c) -> (a -> b) -> a -> c -- (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c --(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c infixr 1 <=< -- | Left-to-right Kleisli composition of monads. (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c 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 --mzero :: MonadPlus m => m a -- | an associative operation mplus :: MonadPlus m => m a -> m a -> m a -- | The join function is the conventional monad join operator. It -- is used to remove one level of monadic structure, projecting its bound -- argument into the outer level. join :: Monad m => m (m a) -> m a -- | guard b is pure () if b is -- True, and empty if b is False. guard :: Alternative f => Bool -> f () -- | Conditional execution of Applicative expressions. For example, -- --
-- when debug (putStrLn "Debugging") ---- -- will output the string Debugging if the Boolean value -- debug is True, and otherwise do nothing. when :: Applicative f => Bool -> f () -> f () -- | The reverse of when. unless :: Applicative f => Bool -> f () -> f () -- | replicateM n act performs the action n times, -- gathering the results. replicateM :: Applicative m => Int -> m a -> m [a] -- | Like replicateM, but discards the result. replicateM_ :: Applicative m => Int -> m a -> m () -- | Strict version of <$>. (<$!>) :: Monad m => (a -> b) -> m a -> m b infixl 4 <$!> -- | Like when, but where the test can be monadic. whenM :: Monad m => m Bool -> m () -> m () -- | Like unless, but where the test can be monadic. unlessM :: Monad m => m Bool -> m () -> m () -- | Like if, but where the test can be monadic. ifM :: Monad m => m Bool -> m a -> m a -> m a -- | A version of all lifted to a monad. Retains the -- short-circuiting behaviour. -- --
-- allM Just [True,False,undefined] == Just False -- allM Just [True,True ,undefined] == undefined -- \(f :: Int -> Maybe Bool) xs -> anyM f xs == orM (map f xs) --allM :: Monad m => (a -> m Bool) -> [a] -> m Bool -- | A version of any lifted to a monad. Retains the -- short-circuiting behaviour. -- --
-- anyM Just [False,True ,undefined] == Just True -- anyM Just [False,False,undefined] == undefined -- \(f :: Int -> Maybe Bool) xs -> anyM f xs == orM (map f xs) --anyM :: Monad m => (a -> m Bool) -> [a] -> m Bool -- | A version of and lifted to a monad. Retains the -- short-circuiting behaviour. -- --
-- andM [Just True,Just False,undefined] == Just False -- andM [Just True,Just True ,undefined] == undefined -- \xs -> Just (and xs) == andM (map Just xs) --andM :: Monad m => [m Bool] -> m Bool -- | A version of or lifted to a monad. Retains the short-circuiting -- behaviour. -- --
-- orM [Just False,Just True ,undefined] == Just True -- orM [Just False,Just False,undefined] == undefined -- \xs -> Just (or xs) == orM (map Just xs) --orM :: Monad m => [m Bool] -> m Bool -- | A version of concatMap that works with a monadic predicate. concatMapM :: Monad m => (a -> m [b]) -> [a] -> m [b] -- | The lazy && operator lifted to a monad. If the first -- argument evaluates to False the second argument will not be -- evaluated. -- --
-- Just False &&^ undefined == Just False -- Just True &&^ Just True == Just True -- Just True &&^ Just False == Just False --(&&^) :: Monad m => m Bool -> m Bool -> m Bool -- | The lazy || operator lifted to a monad. If the first argument -- evaluates to True the second argument will not be evaluated. -- --
-- Just True ||^ undefined == Just True -- Just False ||^ Just True == Just True -- Just False ||^ Just False == Just False --(||^) :: Monad m => m Bool -> m Bool -> m Bool -- | 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 :: Bifunctor p => (a -> b) -> (c -> d) -> p a c -> p b d -- | Map covariantly over the first argument. -- --
-- first f ≡ bimap f id --first :: Bifunctor p => (a -> b) -> p a c -> p b c -- | Map covariantly over the second argument. -- --
-- second ≡ bimap id --second :: Bifunctor p => (b -> c) -> p a b -> p a c -- | Bifoldable identifies foldable structures with two different -- varieties of elements (as opposed to Foldable, which has one -- variety of element). Common examples are Either and '(,)': -- --
-- instance Bifoldable Either where -- bifoldMap f _ (Left a) = f a -- bifoldMap _ g (Right b) = g b -- -- instance Bifoldable (,) where -- bifoldr f g z (a, b) = f a (g b z) ---- -- A minimal Bifoldable definition consists of either -- bifoldMap or bifoldr. When defining more than this -- minimal set, one should ensure that the following identities hold: -- --
-- bifold ≡ bifoldMap id id -- bifoldMap f g ≡ bifoldr (mappend . f) (mappend . g) mempty -- bifoldr f g z t ≡ appEndo (bifoldMap (Endo . f) (Endo . g) t) z ---- -- If the type is also a Bifunctor instance, it should satisfy: -- --
-- 'bifoldMap' f g ≡ 'bifold' . 'bimap' f g ---- -- which implies that -- --
-- 'bifoldMap' f g . 'bimap' h i ≡ 'bifoldMap' (f . h) (g . i) --class Bifoldable (p :: * -> * -> *) -- | Combines the elements of a structure, given ways of mapping them to a -- common monoid. -- --
-- bifoldMap f g ≡ bifoldr (mappend . f) (mappend . g) mempty --bifoldMap :: (Bifoldable p, Monoid m) => (a -> m) -> (b -> m) -> p a b -> m -- | Combines the elements of a structure in a right associative manner. -- Given a hypothetical function toEitherList :: p a b -> [Either -- a b] yielding a list of all elements of a structure in order, the -- following would hold: -- --
-- bifoldr f g z ≡ foldr (either f g) z . toEitherList --bifoldr :: Bifoldable p => (a -> c -> c) -> (b -> c -> c) -> c -> p a b -> c -- | As bifoldl, but strict in the result of the reduction functions -- at each step. -- -- This ensures that each step of the bifold is forced to weak head -- normal form before being applied, avoiding the collection of thunks -- that would otherwise occur. This is often what you want to strictly -- reduce a finite structure to a single, monolithic result (e.g., -- bilength). bifoldl' :: Bifoldable t => (a -> b -> a) -> (a -> c -> a) -> a -> t b c -> a -- | As bifoldr, but strict in the result of the reduction functions -- at each step. bifoldr' :: Bifoldable t => (a -> c -> c) -> (b -> c -> c) -> c -> t a b -> c -- | Map each element of a structure using one of two actions, evaluate -- these actions from left to right, and ignore the results. For a -- version that doesn't ignore the results, see bitraverse. bitraverse_ :: (Bifoldable t, Applicative f) => (a -> f c) -> (b -> f d) -> t a b -> f () -- | As bisequenceA, but ignores the results of the actions. bisequenceA_ :: (Bifoldable t, Applicative f) => t (f a) (f b) -> f () -- | As bitraverse_, but with the structure as the primary argument. -- For a version that doesn't ignore the results, see bifor. -- --
-- >>> > bifor_ ('a', "bc") print (print . reverse)
-- 'a'
-- "cb"
--
bifor_ :: (Bifoldable t, Applicative f) => t a b -> (a -> f c) -> (b -> f d) -> f ()
-- | Bitraversable identifies bifunctorial data structures whose
-- elements can be traversed in order, performing Applicative or
-- Monad actions at each element, and collecting a result
-- structure with the same shape.
--
-- As opposed to Traversable data structures, which have one
-- variety of element on which an action can be performed,
-- Bitraversable data structures have two such varieties of
-- elements.
--
-- A definition of traverse must satisfy the following laws:
--
-- -- t :: (Applicative f, Applicative g) => f a -> g a ---- -- preserving the Applicative operations: -- --
-- t (pure x) = pure x -- t (f <*> x) = t f <*> t x ---- -- and the identity functor Identity and composition functors -- Compose are defined as -- --
-- newtype Identity a = Identity { runIdentity :: a }
--
-- instance Functor Identity where
-- fmap f (Identity x) = Identity (f x)
--
-- instance Applicative Identity where
-- pure = Identity
-- Identity f <*> Identity x = Identity (f x)
--
-- newtype Compose f g a = Compose (f (g a))
--
-- instance (Functor f, Functor g) => Functor (Compose f g) where
-- fmap f (Compose x) = Compose (fmap (fmap f) x)
--
-- instance (Applicative f, Applicative g) => Applicative (Compose f g) where
-- pure = Compose . pure . pure
-- Compose f <*> Compose x = Compose ((<*>) <$> f <*> x)
--
--
-- Some simple examples are Either and '(,)':
--
-- -- instance Bitraversable Either where -- bitraverse f _ (Left x) = Left <$> f x -- bitraverse _ g (Right y) = Right <$> g y -- -- instance Bitraversable (,) where -- bitraverse f g (x, y) = (,) <$> f x <*> g y ---- -- Bitraversable relates to its superclasses in the following -- ways: -- --
-- bimap f g ≡ runIdentity . bitraverse (Identity . f) (Identity . g) -- bifoldMap f g = getConst . bitraverse (Const . f) (Const . g) ---- -- These are available as bimapDefault and bifoldMapDefault -- respectively. class (Bifunctor t, Bifoldable t) => Bitraversable (t :: * -> * -> *) -- | Evaluates the relevant functions at each element in the structure, -- running the action, and builds a new structure with the same shape, -- using the elements produced from sequencing the actions. -- --
-- bitraverse f g ≡ bisequenceA . bimap f g ---- -- For a version that ignores the results, see bitraverse_. bitraverse :: (Bitraversable t, Applicative f) => (a -> f c) -> (b -> f d) -> t a b -> f (t c d) -- | bifor is bitraverse with the structure as the first -- argument. For a version that ignores the results, see bifor_. bifor :: (Bitraversable t, Applicative f) => t a b -> (a -> f c) -> (b -> f d) -> f (t c d) -- | Sequences all the actions in a structure, building a new structure -- with the same shape using the results of the actions. For a version -- that ignores the results, see bisequenceA_. -- --
-- bisequenceA ≡ bitraverse id id --bisequenceA :: (Bitraversable t, Applicative f) => t (f a) (f b) -> f (t a b) -- | The class of monad transformers. Instances should satisfy the -- following laws, which state that lift is a monad -- transformation: -- -- class MonadTrans (t :: (* -> *) -> * -> *) -- | Lift a computation from the argument monad to the constructed monad. lift :: (MonadTrans t, Monad m) => m a -> t m a -- | The parameterizable maybe monad, obtained by composing an arbitrary -- monad with the Maybe monad. -- -- Computations are actions that may produce a value or exit. -- -- The return function yields a computation that produces that -- value, while >>= sequences two subcomputations, exiting -- if either computation does. newtype MaybeT (m :: * -> *) a :: (* -> *) -> * -> * MaybeT :: m (Maybe a) -> MaybeT a [runMaybeT] :: MaybeT a -> m (Maybe a) -- | Transform the computation inside a MaybeT. -- -- mapMaybeT :: (m (Maybe a) -> n (Maybe b)) -> MaybeT m a -> MaybeT n b -- | The strategy of combining computations that can throw exceptions by -- bypassing bound functions from the point an exception is thrown to the -- point that it is handled. -- -- Is parameterized over the type of error information and the monad type -- constructor. It is common to use Either String as the -- monad type constructor for an error monad in which error descriptions -- take the form of strings. In that case and many other common cases the -- resulting monad is already defined as an instance of the -- MonadError class. You can also define your own error type -- and/or use a monad type constructor other than Either -- String or Either IOError. In -- these cases you will have to explicitly define instances of the -- Error and/or MonadError classes. class Monad m => MonadError e (m :: * -> *) | m -> e -- | Is used within a monadic computation to begin exception processing. throwError :: MonadError e m => e -> m a -- | A handler function to handle previous errors and return to normal -- execution. A common idiom is: -- --
-- do { action1; action2; action3 } `catchError` handler
--
--
-- where the action functions can call throwError. Note
-- that handler and the do-block must have the same return type.
catchError :: MonadError e m => m a -> (e -> m a) -> m a
-- | The parameterizable exception monad.
--
-- Computations are either exceptions or normal values.
--
-- The return function returns a normal value, while
-- >>= exits on the first exception. For a variant that
-- continues after an error and collects all the errors, see
-- Errors.
type Except e = ExceptT e Identity
-- | Extractor for computations in the exception monad. (The inverse of
-- except).
runExcept :: Except e a -> Either e a
-- | Map the unwrapped computation using the given function.
--
--
mapExcept :: (Either e a -> Either e' b) -> Except e a -> Except e' b
-- | Transform any exceptions thrown by the computation using the given
-- function (a specialization of withExceptT).
withExcept :: (e -> e') -> Except e a -> Except e' a
-- | A monad transformer that adds exceptions to other monads.
--
-- ExceptT constructs a monad parameterized over two things:
--
-- runExceptT (mapExceptT f m) = f -- (runExceptT m)
runReader (withReader f m) = runReader m -- . f
runReaderT (mapReaderT f m) = f . -- runReaderT m
runReaderT (withReaderT f m) = -- runReaderT m . f
execWriter m = snd (runWriter -- m)
execWriterT m = liftM snd -- (runWriterT m)
runWriterT (mapWriterT f m) = f -- (runWriterT m)
-- Main> :t modify ((+1) :: Int -> Int) -- modify (...) :: (MonadState Int a) => a () ---- -- This says that modify (+1) acts over any Monad that is a -- member of the MonadState class, with an Int state. modify :: MonadState s m => (s -> s) -> m () -- | A variant of modify in which the computation is strict in the -- new state. modify' :: MonadState s m => (s -> s) -> m () -- | Unwrap a state monad computation as a function. (The inverse of -- state.) runState :: State s a -> s -> (a, s) -- | Evaluate a state computation with the given initial state and return -- the final value, discarding the final state. -- -- evalState :: State s a -> s -> a -- | Evaluate a state computation with the given initial state and return -- the final state, discarding the final value. -- -- execState :: State s a -> s -> s -- | Map both the return value and final state of a computation using the -- given function. -- -- mapState :: ((a, s) -> (b, s)) -> State s a -> State s b -- | withState f m executes action m on a state -- modified by applying f. -- -- withState :: (s -> s) -> State s a -> State s a -- | A state transformer monad parameterized by: -- --
evalStateT m s = liftM fst -- (runStateT m s)
execStateT m s = liftM snd -- (runStateT m s)
withStateT f m = modify f >> m
-- decode . encode == id ---- -- That is, the get and put methods should be the inverse -- of each other. A range of instances are provided for basic Haskell -- types. class Binary t -- | The kind of types with values. For example Int :: Type. type Type = * -- | The kind of constraints, like Show a data Constraint :: * -- | A concrete, poly-kinded proxy type data Proxy k (t :: k) :: forall k. k -> * Proxy :: Proxy k -- | A Tagged s b value is a value b with an -- attached phantom type s. This can be used in place of the -- more traditional but less safe idiom of passing in an undefined value -- with the type, because unlike an (s -> b), a -- Tagged s b can't try to use the argument s as -- a real value. -- -- Moreover, you don't have to rely on the compiler to inline away the -- extra argument, because the newtype is "free" -- -- Tagged has kind k -> * -> * if the compiler -- supports PolyKinds, therefore there is an extra k -- showing in the instance haddocks that may cause confusion. newtype Tagged k (s :: k) b :: forall k. k -> * -> * Tagged :: b -> Tagged k b [unTagged] :: Tagged k b -> b unTagged :: Tagged k s b -> b -- | A value of type IO a is a computation which, when -- performed, does some I/O before returning a value of type a. -- -- There is really only one way to "perform" an I/O action: bind it to -- Main.main in your program. When your program is run, the I/O -- will be performed. It isn't possible to perform I/O from an arbitrary -- function, unless that function is itself in the IO monad and -- called at some point, directly or indirectly, from Main.main. -- -- IO is a monad, so IO actions can be combined using -- either the do-notation or the >> and >>= -- operations from the Monad class. data IO a :: * -> * -- | Monads in which IO computations may be embedded. Any monad -- built by applying a sequence of monad transformers to the IO -- monad will be an instance of this class. -- -- Instances should satisfy the following laws, which state that -- liftIO is a transformer of monads: -- -- class Monad m => MonadIO (m :: * -> *) -- | Lift a computation from the IO monad. liftIO :: MonadIO m => IO a -> m a -- | Read a character from the standard input device. -- -- Note: This function is lifted to the MonadIO class. getChar :: MonadIO m => m Char -- | The getContents operation returns all user input as a strict -- Text. -- -- Note: This function is lifted to the MonadIO class. getContents :: MonadIO m => m Text -- | Read a line from the standard input device as a strict Text. -- -- Note: This function is lifted to the MonadIO class. getLine :: MonadIO m => m Text -- | The print function outputs a value of any printable type to the -- standard output device. Printable types are those that are instances -- of class Show; print converts values to strings for -- output using the show operation and adds a newline. -- -- For example, a program to print the first 20 integers and their powers -- of 2 could be written as: -- --
-- main = print ([(n, 2^n) | n <- [0..19]]) ---- -- Note: This function is lifted to the MonadIO class. print :: (MonadIO m, Show a) => a -> m () -- | Write a character to the standard output device. -- -- Note: This function is lifted to the MonadIO class. putChar :: MonadIO m => Char -> m () -- | Write a strict Text to the standard output device. -- -- Note: This function is lifted to the MonadIO class. putStr :: MonadIO m => Text -> m () -- | The same as putStr, but adds a newline character. -- -- Note: This function is lifted to the MonadIO class. putStrLn :: MonadIO m => Text -> m () -- | File and directory names are values of type String, whose -- precise meaning is operating system dependent. Files can be opened, -- yielding a handle which can then be used to operate on the contents of -- that file. type FilePath = String -- | Read an entire file strictly into a ByteString. -- -- Note: This function is lifted to the MonadIO class. readFile :: MonadIO m => FilePath -> m ByteString -- | Write a ByteString to a file. -- -- Note: This function is lifted to the MonadIO class. writeFile :: MonadIO m => FilePath -> ByteString -> m () -- | Append a ByteString to a file. -- -- Note: This function is lifted to the MonadIO class. appendFile :: MonadIO m => FilePath -> ByteString -> m () -- | Read an entire file strictly into a Text using UTF-8 encoding. -- -- Note: This function is lifted to the MonadIO class. readFileUtf8 :: MonadIO m => FilePath -> m Text -- | Write a Text to a file using UTF-8 encoding. -- -- Note: This function is lifted to the MonadIO class. writeFileUtf8 :: MonadIO m => FilePath -> Text -> m () -- | Append a Text to a file using UTF-8 encoding. -- -- Note: This function is lifted to the MonadIO class. appendFileUtf8 :: MonadIO m => FilePath -> Text -> m () -- | Throw an unhandled error to terminate the program in case of a logic -- error at runtime. Use this function instead of error. A stack -- trace will be provided. -- -- In general, prefer total functions. You can use Maybe, -- Either, ExceptT or MonadError for error handling. panic :: HasCallStack => a -- | Throw an undefined error. Use only for debugging. -- | Warning: undefined remains in code undefined :: HasCallStack => a -- | The trace function outputs the trace message given as its first -- argument, before returning the second argument as its result. -- -- For example, this returns the value of f x but first outputs -- the message. -- --
-- trace ("calling f with x = " ++ show x) (f x)
--
--
-- The trace function should only be used for debugging, or
-- for monitoring execution. The function is not referentially
-- transparent: its type indicates that it is a pure function but it has
-- the side effect of outputting the trace message.
-- | Warning: trace remains in code
trace :: Text -> a -> a
-- | The traceIO function outputs the trace message from the IO
-- monad. This sequences the output with respect to other IO actions.
-- | Warning: traceIO remains in code
traceIO :: MonadIO m => Text -> m ()
-- | Like trace but returning unit in an arbitrary
-- Applicative context. Allows for convenient use in do-notation.
--
-- Note that the application of traceM is not an action in the
-- Applicative context, as traceIO is in the MonadIO
-- type. While the fresh bindings in the following example will force the
-- traceM expressions to be reduced every time the
-- do-block is executed, traceM "not crashed" would
-- only be reduced once, and the message would only be printed once. If
-- your monad is in MonadIO, traceIO may be a better
-- option.
--
-- -- ... = do -- x <- ... -- traceM $ "x: " ++ show x -- y <- ... -- traceM $ "y: " ++ show y ---- | Warning: traceM remains in code traceM :: Applicative m => Text -> m () -- | Like trace, but uses show on the argument to convert -- it to a String. -- -- This makes it convenient for printing the values of interesting -- variables or expressions inside a function. For example here we print -- the value of the variables x and z: -- --
-- f x y = -- traceShow (x, z) $ result -- where -- z = ... -- ... ---- | Warning: traceShow remains in code traceShow :: Show a => a -> b -> b -- | Like traceM, but uses show on the argument to convert -- it to a String. -- --
-- ... = do -- x <- ... -- traceShowM $ x -- y <- ... -- traceShowM $ x + y ---- | Warning: traceShowM remains in code traceShowM :: (Show a, Applicative m) => a -> m () -- | like trace, but additionally prints a call stack if one is -- available. -- -- In the current GHC implementation, the call stack is only available if -- the program was compiled with -prof; otherwise -- traceStack behaves exactly like trace. Entries in the -- call stack correspond to SCC annotations, so it is a good -- idea to use -fprof-auto or -fprof-auto-calls to add -- SCC annotations automatically. -- | Warning: traceStack remains in code traceStack :: Text -> a -> a -- | Like traceStack but returning unit in an arbitrary -- Applicative context. Allows for convenient use in do-notation. -- | Warning: traceStackM remains in code traceStackM :: Applicative m => Text -> m ()