| Safe Haskell | None |
|---|---|
| Language | Haskell2010 |
RIO.Prelude
Contents
Synopsis
- (||) :: Bool -> Bool -> Bool
- (&&) :: Bool -> Bool -> Bool
- not :: Bool -> Bool
- otherwise :: Bool
- bool :: a -> a -> Bool -> a
- maybe :: b -> (a -> b) -> Maybe a -> b
- fromMaybe :: a -> Maybe a -> a
- fromFirst :: a -> First a -> a
- isJust :: Maybe a -> Bool
- isNothing :: Maybe a -> Bool
- listToMaybe :: [a] -> Maybe a
- maybeToList :: Maybe a -> [a]
- catMaybes :: [Maybe a] -> [a]
- mapMaybe :: (a -> Maybe b) -> [a] -> [b]
- mapMaybeA :: Applicative f => (a -> f (Maybe b)) -> [a] -> f [b]
- mapMaybeM :: Monad m => (a -> m (Maybe b)) -> [a] -> m [b]
- forMaybeA :: Applicative f => [a] -> (a -> f (Maybe b)) -> f [b]
- forMaybeM :: Monad m => [a] -> (a -> m (Maybe b)) -> m [b]
- either :: (a -> c) -> (b -> c) -> Either a b -> c
- fromLeft :: a -> Either a b -> a
- fromRight :: b -> Either a b -> b
- isLeft :: Either a b -> Bool
- isRight :: Either a b -> Bool
- mapLeft :: (a1 -> a2) -> Either a1 b -> Either a2 b
- lefts :: [Either a b] -> [a]
- partitionEithers :: [Either a b] -> ([a], [b])
- rights :: [Either a b] -> [b]
- fst :: (a, b) -> a
- snd :: (a, b) -> b
- curry :: ((a, b) -> c) -> a -> b -> c
- uncurry :: (a -> b -> c) -> (a, b) -> c
- (==) :: Eq a => a -> a -> Bool
- (/=) :: Eq a => a -> a -> Bool
- (<) :: 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
- compare :: Ord a => a -> a -> Ordering
- comparing :: Ord a => (b -> a) -> b -> b -> Ordering
- newtype Down a = Down {
- getDown :: a
- fromEnum :: Enum a => a -> Int
- minBound :: Bounded a => a
- maxBound :: Bounded a => a
- (+) :: Num a => a -> a -> a
- (-) :: Num a => a -> a -> a
- (*) :: Num a => a -> a -> a
- (^) :: (Num a, Integral b) => a -> b -> a
- negate :: Num a => a -> a
- abs :: Num a => a -> a
- signum :: Num a => a -> a
- fromInteger :: Num a => Integer -> a
- subtract :: Num a => a -> a -> a
- toRational :: Real a => a -> Rational
- quot :: Integral a => a -> a -> a
- rem :: Integral a => a -> a -> a
- div :: Integral a => a -> a -> a
- mod :: Integral a => a -> a -> a
- quotRem :: Integral a => a -> a -> (a, a)
- divMod :: Integral a => a -> a -> (a, a)
- toInteger :: Integral a => a -> Integer
- even :: Integral a => a -> Bool
- odd :: Integral a => a -> Bool
- gcd :: Integral a => a -> a -> a
- lcm :: Integral a => a -> a -> a
- fromIntegral :: (Integral a, Num b) => a -> b
- (/) :: Fractional a => a -> a -> a
- (^^) :: (Fractional a, Integral b) => a -> b -> a
- recip :: Fractional a => a -> a
- fromRational :: Fractional a => Rational -> a
- realToFrac :: (Real a, Fractional b) => a -> b
- 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
- properFraction :: (RealFrac a, Integral b) => a -> (b, a)
- truncate :: (RealFrac a, Integral b) => a -> b
- round :: (RealFrac a, Integral b) => a -> b
- ceiling :: (RealFrac a, Integral b) => a -> b
- floor :: (RealFrac a, Integral b) => a -> b
- floatRadix :: RealFloat a => a -> Integer
- floatDigits :: RealFloat a => a -> Int
- floatRange :: RealFloat a => a -> (Int, Int)
- decodeFloat :: RealFloat a => a -> (Integer, Int)
- encodeFloat :: RealFloat a => Integer -> Int -> a
- exponent :: RealFloat a => a -> Int
- significand :: RealFloat a => a -> a
- scaleFloat :: RealFloat a => Int -> a -> a
- isNaN :: RealFloat a => a -> Bool
- isInfinite :: RealFloat a => a -> Bool
- isDenormalized :: RealFloat a => a -> Bool
- isNegativeZero :: RealFloat a => a -> Bool
- isIEEE :: RealFloat a => a -> Bool
- atan2 :: RealFloat a => a -> a -> a
- byteSwap16 :: Word16 -> Word16
- byteSwap32 :: Word32 -> Word32
- byteSwap64 :: Word64 -> Word64
- (<>) :: Semigroup a => a -> a -> a
- sappend :: Semigroup s => s -> s -> s
- mempty :: Monoid a => a
- mappend :: Monoid a => a -> a -> a
- mconcat :: Monoid a => [a] -> a
- fmap :: Functor f => (a -> b) -> f a -> f b
- (<$>) :: Functor f => (a -> b) -> f a -> f b
- (<$) :: Functor f => a -> f b -> f a
- ($>) :: Functor f => f a -> b -> f b
- void :: Functor f => f a -> f ()
- (<&>) :: Functor f => f a -> (a -> b) -> f b
- pure :: Applicative f => a -> f a
- (<*>) :: Applicative f => f (a -> b) -> f a -> f b
- (<*) :: Applicative f => f a -> f b -> f a
- (*>) :: Applicative f => f a -> f b -> f b
- liftA :: Applicative f => (a -> b) -> f a -> f b
- liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c
- liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d
- forever :: Applicative f => f a -> f b
- traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()
- for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f ()
- sequenceA_ :: (Foldable t, Applicative f) => t (f a) -> f ()
- filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a]
- replicateM_ :: Applicative m => Int -> m a -> m ()
- zipWithM :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m [c]
- zipWithM_ :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m ()
- return :: Monad m => a -> m a
- join :: Monad m => m (m a) -> m a
- fail :: MonadFail m => String -> m a
- (>>=) :: Monad m => m a -> (a -> m b) -> m b
- (>>) :: Monad m => m a -> m b -> m b
- (=<<) :: Monad m => (a -> m b) -> m a -> m b
- (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
- (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
- (<$!>) :: Monad m => (a -> b) -> m a -> m b
- liftM :: Monad m => (a1 -> r) -> m a1 -> m r
- liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r
- whenM :: Monad m => m Bool -> m () -> m ()
- unlessM :: Monad m => m Bool -> m () -> m ()
- mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()
- forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m ()
- sequence_ :: (Foldable t, Monad m) => t (m a) -> m ()
- foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b
- foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m ()
- foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b
- foldl' :: Foldable t => (b -> a -> b) -> b -> t a -> b
- fold :: (Foldable t, Monoid m) => t m -> m
- foldMap :: (Foldable t, Monoid m) => (a -> m) -> t a -> m
- foldMapM :: (Monad m, Monoid w, Foldable t) => (a -> m w) -> t a -> m w
- elem :: (Foldable t, Eq a) => a -> t a -> Bool
- notElem :: (Foldable t, Eq a) => a -> t a -> Bool
- null :: Foldable t => t a -> Bool
- length :: Foldable t => t a -> Int
- sum :: (Foldable t, Num a) => t a -> a
- product :: (Foldable t, Num a) => t a -> a
- all :: Foldable t => (a -> Bool) -> t a -> Bool
- any :: Foldable t => (a -> Bool) -> t a -> Bool
- and :: Foldable t => t Bool -> Bool
- or :: Foldable t => t Bool -> Bool
- toList :: Foldable t => t a -> [a]
- concat :: Foldable t => t [a] -> [a]
- concatMap :: Foldable t => (a -> [b]) -> t a -> [b]
- traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b)
- for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b)
- sequenceA :: (Traversable t, Applicative f) => t (f a) -> f (t a)
- mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b)
- forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b)
- sequence :: (Traversable t, Monad m) => t (m a) -> m (t a)
- (<|>) :: Alternative f => f a -> f a -> f a
- some :: Alternative f => f a -> f [a]
- many :: Alternative f => f a -> f [a]
- optional :: Alternative f => f a -> f (Maybe a)
- asum :: (Foldable t, Alternative f) => t (f a) -> f a
- guard :: Alternative f => Bool -> f ()
- when :: Applicative f => Bool -> f () -> f ()
- unless :: Applicative f => Bool -> f () -> f ()
- bimap :: Bifunctor p => (a -> b) -> (c -> d) -> p a c -> p b d
- first :: Bifunctor p => (a -> b) -> p a c -> p b c
- second :: Bifunctor p => (b -> c) -> p a b -> p a c
- bifold :: (Bifoldable p, Monoid m) => p m m -> m
- bifoldMap :: (Bifoldable p, Monoid m) => (a -> m) -> (b -> m) -> p a b -> m
- bifoldr :: Bifoldable p => (a -> c -> c) -> (b -> c -> c) -> c -> p a b -> c
- bifoldl :: Bifoldable p => (c -> a -> c) -> (c -> b -> c) -> c -> p a b -> c
- bifoldr' :: Bifoldable t => (a -> c -> c) -> (b -> c -> c) -> c -> t a b -> c
- bifoldr1 :: Bifoldable t => (a -> a -> a) -> t a a -> a
- bifoldrM :: (Bifoldable t, Monad m) => (a -> c -> m c) -> (b -> c -> m c) -> c -> t a b -> m c
- bifoldl' :: Bifoldable t => (a -> b -> a) -> (a -> c -> a) -> a -> t b c -> a
- bifoldl1 :: Bifoldable t => (a -> a -> a) -> t a a -> a
- bifoldlM :: (Bifoldable t, Monad m) => (a -> b -> m a) -> (a -> c -> m a) -> a -> t b c -> m a
- bitraverse_ :: (Bifoldable t, Applicative f) => (a -> f c) -> (b -> f d) -> t a b -> f ()
- bifor_ :: (Bifoldable t, Applicative f) => t a b -> (a -> f c) -> (b -> f d) -> f ()
- bisequence_ :: (Bifoldable t, Applicative f) => t (f a) (f b) -> f ()
- biasum :: (Bifoldable t, Alternative f) => t (f a) (f a) -> f a
- biList :: Bifoldable t => t a a -> [a]
- binull :: Bifoldable t => t a b -> Bool
- bilength :: Bifoldable t => t a b -> Int
- bielem :: (Bifoldable t, Eq a) => a -> t a a -> Bool
- bimaximum :: (Bifoldable t, Ord a) => t a a -> a
- biminimum :: (Bifoldable t, Ord a) => t a a -> a
- bisum :: (Bifoldable t, Num a) => t a a -> a
- biproduct :: (Bifoldable t, Num a) => t a a -> a
- biconcat :: Bifoldable t => t [a] [a] -> [a]
- biconcatMap :: Bifoldable t => (a -> [c]) -> (b -> [c]) -> t a b -> [c]
- biand :: Bifoldable t => t Bool Bool -> Bool
- bior :: Bifoldable t => t Bool Bool -> Bool
- biany :: Bifoldable t => (a -> Bool) -> (b -> Bool) -> t a b -> Bool
- biall :: Bifoldable t => (a -> Bool) -> (b -> Bool) -> t a b -> Bool
- bimaximumBy :: Bifoldable t => (a -> a -> Ordering) -> t a a -> a
- biminimumBy :: Bifoldable t => (a -> a -> Ordering) -> t a a -> a
- binotElem :: (Bifoldable t, Eq a) => a -> t a a -> Bool
- bifind :: Bifoldable t => (a -> Bool) -> t a a -> Maybe a
- bitraverse :: (Bitraversable t, Applicative f) => (a -> f c) -> (b -> f d) -> t a b -> f (t c d)
- bisequence :: (Bitraversable t, Applicative f) => t (f a) (f b) -> f (t a b)
- bifor :: (Bitraversable t, Applicative f) => t a b -> (a -> f c) -> (b -> f d) -> f (t c d)
- bimapAccumL :: Bitraversable t => (a -> b -> (a, c)) -> (a -> d -> (a, e)) -> a -> t b d -> (a, t c e)
- bimapAccumR :: Bitraversable t => (a -> b -> (a, c)) -> (a -> d -> (a, e)) -> a -> t b d -> (a, t c e)
- mzero :: MonadPlus m => m a
- mplus :: MonadPlus m => m a -> m a -> m a
- msum :: (Foldable t, MonadPlus m) => t (m a) -> m a
- mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a
- (&&&) :: Arrow a => a b c -> a b c' -> a b (c, c')
- (***) :: Arrow a => a b c -> a b' c' -> a (b, b') (c, c')
- (>>>) :: forall {k} cat (a :: k) (b :: k) (c :: k). Category cat => cat a b -> cat b c -> cat a c
- id :: a -> a
- const :: a -> b -> a
- (.) :: (b -> c) -> (a -> b) -> a -> c
- ($) :: (a -> b) -> a -> b
- (&) :: a -> (a -> b) -> b
- flip :: (a -> b -> c) -> b -> a -> c
- fix :: (a -> a) -> a
- on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
- ($!) :: (a -> b) -> a -> b
- seq :: a -> b -> b
- error :: HasCallStack => [Char] -> a
- undefined :: HasCallStack => a
- asTypeOf :: a -> a -> a
- asIO :: IO a -> IO a
- (++) :: [a] -> [a] -> [a]
- break :: (a -> Bool) -> [a] -> ([a], [a])
- drop :: Int -> [a] -> [a]
- dropWhile :: (a -> Bool) -> [a] -> [a]
- filter :: (a -> Bool) -> [a] -> [a]
- lookup :: Eq a => a -> [(a, b)] -> Maybe b
- map :: (a -> b) -> [a] -> [b]
- replicate :: Int -> a -> [a]
- reverse :: [a] -> [a]
- span :: (a -> Bool) -> [a] -> ([a], [a])
- take :: Int -> [a] -> [a]
- takeWhile :: (a -> Bool) -> [a] -> [a]
- zip :: [a] -> [b] -> [(a, b)]
- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
- nubOrd :: Ord a => [a] -> [a]
- fromString :: IsString a => String -> a
- lines :: String -> [String]
- unlines :: [String] -> String
- unwords :: [String] -> String
- words :: String -> [String]
- show :: Show a => a -> String
- readMaybe :: Read a => String -> Maybe a
- ($!!) :: NFData a => (a -> b) -> a -> b
- rnf :: NFData a => a -> ()
- deepseq :: NFData a => a -> b -> b
- force :: NFData a => a -> a
- absurd :: Void -> a
- lift :: (MonadTrans t, Monad m) => m a -> t m a
- ask :: MonadReader r m => m r
- asks :: MonadReader r m => (r -> a) -> m a
- local :: MonadReader r m => (r -> r) -> m a -> m a
- runReader :: Reader r a -> r -> a
- runReaderT :: ReaderT r m a -> r -> m a
- toStrictBytes :: LByteString -> ByteString
- fromStrictBytes :: ByteString -> LByteString
- toShort :: ByteString -> ShortByteString
- fromShort :: ShortByteString -> ByteString
- tshow :: Show a => a -> Text
- decodeUtf8Lenient :: ByteString -> Text
- decodeUtf8' :: ByteString -> Either UnicodeException Text
- decodeUtf8With :: OnDecodeError -> ByteString -> Text
- encodeUtf8 :: Text -> ByteString
- encodeUtf8Builder :: Text -> Builder
- lenientDecode :: OnDecodeError
- primitive :: PrimMonad m => (State# (PrimState m) -> (# State# (PrimState m), a #)) -> m a
- runST :: (forall s. ST s a) -> a
Bool
Re-exported from Data.Bool:
Case analysis for the Bool type. evaluates to bool f t pf
when p is False, and evaluates to t when p is True.
This is equivalent to if p then t else f; that is, one can
think of it as an if-then-else construct with its arguments
reordered.
@since base-4.7.0.0
Examples
Basic usage:
>>>bool "foo" "bar" True"bar">>>bool "foo" "bar" False"foo"
Confirm that and bool f t pif p then t else f are
equivalent:
>>>let p = True; f = "bar"; t = "foo">>>bool f t p == if p then t else fTrue>>>let p = False>>>bool f t p == if p then t else fTrue
Maybe
Re-exported from Data.Maybe:
maybe :: b -> (a -> b) -> Maybe a -> b #
The maybe function takes a default value, a function, and a Maybe
value. If the Maybe value is Nothing, the function returns the
default value. Otherwise, it applies the function to the value inside
the Just and returns the result.
Examples
Basic usage:
>>>maybe False odd (Just 3)True
>>>maybe False odd NothingFalse
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 GHC.Internal.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""
fromMaybe :: a -> Maybe a -> a #
The fromMaybe function takes a default value and a Maybe
value. If the Maybe is Nothing, it returns the default value;
otherwise, it returns the value contained in the Maybe.
Examples
Basic usage:
>>>fromMaybe "" (Just "Hello, World!")"Hello, World!"
>>>fromMaybe "" Nothing""
Read an integer from a string using readMaybe. If we fail to
parse an integer, we want to return 0 by default:
>>>import GHC.Internal.Text.Read ( readMaybe )>>>fromMaybe 0 (readMaybe "5")5>>>fromMaybe 0 (readMaybe "")0
listToMaybe :: [a] -> Maybe a #
The listToMaybe function returns Nothing on an empty list
or where Just aa is the first element of the list.
Examples
Basic usage:
>>>listToMaybe []Nothing
>>>listToMaybe [9]Just 9
>>>listToMaybe [1,2,3]Just 1
Composing maybeToList with listToMaybe should be the identity
on singleton/empty lists:
>>>maybeToList $ listToMaybe [5][5]>>>maybeToList $ listToMaybe [][]
But not on lists with more than one element:
>>>maybeToList $ listToMaybe [1,2,3][1]
maybeToList :: Maybe a -> [a] #
The maybeToList function returns an empty list when given
Nothing or a singleton list when given Just.
Examples
Basic usage:
>>>maybeToList (Just 7)[7]
>>>maybeToList Nothing[]
One can use maybeToList to avoid pattern matching when combined
with a function that (safely) works on lists:
>>>import GHC.Internal.Text.Read ( readMaybe )>>>sum $ maybeToList (readMaybe "3")3>>>sum $ maybeToList (readMaybe "")0
catMaybes :: [Maybe a] -> [a] #
The catMaybes function takes a list of Maybes and returns
a list of all the Just values.
Examples
Basic usage:
>>>catMaybes [Just 1, Nothing, Just 3][1,3]
When constructing a list of Maybe values, catMaybes can be used
to return all of the "success" results (if the list is the result
of a map, then mapMaybe would be more appropriate):
>>>import GHC.Internal.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]
mapMaybe :: (a -> Maybe b) -> [a] -> [b] #
The mapMaybe function is a version of map which can throw
out elements. In particular, the functional argument returns
something of type . If this is Maybe bNothing, no element
is added on to the result list. If it is , then Just bb is
included in the result list.
Examples
Using is a shortcut for mapMaybe f x
in most cases:catMaybes $ map f x
>>>import GHC.Internal.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]
mapMaybeA :: Applicative f => (a -> f (Maybe b)) -> [a] -> f [b] #
Applicative mapMaybe.
Either
Re-exported from Data.Either:
either :: (a -> c) -> (b -> c) -> Either a b -> c #
Case analysis for the Either type.
If the value is , apply the first function to Left aa;
if it is , apply the second function to Right bb.
Examples
We create two values of type , one using the
Either String IntLeft constructor and another using the Right constructor. Then
we apply "either" the length function (if we have a String)
or the "times-two" function (if we have an Int):
>>>let s = Left "foo" :: Either String Int>>>let n = Right 3 :: Either String Int>>>either length (*2) s3>>>either length (*2) n6
fromLeft :: a -> Either a b -> a #
Return the contents of a Left-value or a default value otherwise.
@since base-4.10.0.0
Examples
Basic usage:
>>>fromLeft 1 (Left 3)3>>>fromLeft 1 (Right "foo")1
fromRight :: b -> Either a b -> b #
Return the contents of a Right-value or a default value otherwise.
@since base-4.10.0.0
Examples
Basic usage:
>>>fromRight 1 (Right 3)3>>>fromRight 1 (Left "foo")1
isLeft :: Either a b -> Bool #
Return True if the given value is a Left-value, False otherwise.
@since base-4.7.0.0
Examples
Basic usage:
>>>isLeft (Left "foo")True>>>isLeft (Right 3)False
Assuming a Left value signifies some sort of error, we can use
isLeft to write a very simple error-reporting function that does
absolutely nothing in the case of success, and outputs "ERROR" if
any error occurred.
This example shows how isLeft might be used to avoid pattern
matching when one does not care about the value contained in the
constructor:
>>>import Control.Monad ( when )>>>let report e = when (isLeft e) $ putStrLn "ERROR">>>report (Right 1)>>>report (Left "parse error")ERROR
isRight :: Either a b -> Bool #
Return True if the given value is a Right-value, False otherwise.
@since base-4.7.0.0
Examples
Basic usage:
>>>isRight (Left "foo")False>>>isRight (Right 3)True
Assuming a Left value signifies some sort of error, we can use
isRight to write a very simple reporting function that only
outputs "SUCCESS" when a computation has succeeded.
This example shows how isRight might be used to avoid pattern
matching when one does not care about the value contained in the
constructor:
>>>import Control.Monad ( when )>>>let report e = when (isRight e) $ putStrLn "SUCCESS">>>report (Left "parse error")>>>report (Right 1)SUCCESS
partitionEithers :: [Either a b] -> ([a], [b]) #
Partitions a list of Either into two lists.
All the Left elements are extracted, in order, to the first
component of the output. Similarly the Right elements are extracted
to the second component of the output.
Examples
Basic usage:
>>>let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]>>>partitionEithers list(["foo","bar","baz"],[3,7])
The pair returned by should be the same
pair as partitionEithers x(:lefts x, rights x)
>>>let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]>>>partitionEithers list == (lefts list, rights list)True
Tuples
Re-exported from Data.Tuple:
curry :: ((a, b) -> c) -> a -> b -> c #
Convert an uncurried function to a curried function.
Examples
>>>curry fst 1 21
uncurry :: (a -> b -> c) -> (a, b) -> c #
uncurry converts a curried function to a function on pairs.
Examples
>>>uncurry (+) (1,2)3
>>>uncurry ($) (show, 1)"1"
>>>map (uncurry max) [(1,2), (3,4), (6,8)][2,4,8]
Eq
Re-exported from Data.Eq:
Ord
Re-exported from Data.Ord:
comparing :: Ord a => (b -> a) -> b -> b -> 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) ...
The Down type allows you to reverse sort order conveniently. A value of type
contains a value of type Down aa (represented as ).Down a
If a has an 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: Ordthen sortWith by .Down x
>>>compare True FalseGT
>>>compare (Down True) (Down False)LT
If a has a instance then the wrapped instance also respects
the reversed ordering by exchanging the values of Bounded and
minBound.maxBound
>>>minBound :: Int-9223372036854775808
>>>minBound :: Down IntDown 9223372036854775807
All other instances of behave as they do for Down aa.
@since base-4.6.0.0
Instances
| MonadZip Down | Since: base-4.12.0.0 | ||||
| Foldable1 Down | Since: base-4.18.0.0 | ||||
Defined in Data.Foldable1 Methods fold1 :: Semigroup m => Down m -> m # foldMap1 :: Semigroup m => (a -> m) -> Down a -> m # foldMap1' :: Semigroup m => (a -> m) -> Down a -> m # toNonEmpty :: Down a -> NonEmpty a # maximum :: Ord a => Down a -> a # minimum :: Ord a => Down a -> a # foldrMap1 :: (a -> b) -> (a -> b -> b) -> Down a -> b # foldlMap1' :: (a -> b) -> (b -> a -> b) -> Down a -> b # foldlMap1 :: (a -> b) -> (b -> a -> b) -> Down a -> b # foldrMap1' :: (a -> b) -> (a -> b -> b) -> Down a -> b # | |||||
| Eq1 Down | Since: base-4.12.0.0 | ||||
| Ord1 Down | Since: base-4.12.0.0 | ||||
Defined in Data.Functor.Classes | |||||
| Read1 Down | Since: base-4.12.0.0 | ||||
Defined in Data.Functor.Classes | |||||
| Show1 Down | Since: base-4.12.0.0 | ||||
| NFData1 Down | Since: deepseq-1.4.3.0 | ||||
Defined in Control.DeepSeq | |||||
| Applicative Down | @since base-4.11.0.0 | ||||
| Functor Down | @since base-4.11.0.0 | ||||
| Monad Down | @since base-4.11.0.0 | ||||
| Foldable Down | @since base-4.12.0.0 | ||||
Defined in GHC.Internal.Data.Foldable Methods fold :: Monoid m => Down m -> m # foldMap :: Monoid m => (a -> m) -> Down a -> m # foldMap' :: Monoid m => (a -> m) -> Down a -> m # foldr :: (a -> b -> b) -> b -> Down a -> b # foldr' :: (a -> b -> b) -> b -> Down a -> b # foldl :: (b -> a -> b) -> b -> Down a -> b # foldl' :: (b -> a -> b) -> b -> Down a -> b # foldr1 :: (a -> a -> a) -> Down a -> a # foldl1 :: (a -> a -> a) -> Down a -> a # elem :: Eq a => a -> Down a -> Bool # maximum :: Ord a => Down a -> a # | |||||
| Traversable Down | @since base-4.12.0.0 | ||||
| Generic1 Down | |||||
Defined in GHC.Internal.Generics Associated Types
| |||||
| Unbox a => Vector Vector (Down a) | |||||
Defined in Data.Vector.Unboxed.Base Methods basicUnsafeFreeze :: Mutable Vector s (Down a) -> ST s (Vector (Down a)) # basicUnsafeThaw :: Vector (Down a) -> ST s (Mutable Vector s (Down a)) # basicLength :: Vector (Down a) -> Int # basicUnsafeSlice :: Int -> Int -> Vector (Down a) -> Vector (Down a) # basicUnsafeIndexM :: Vector (Down a) -> Int -> Box (Down a) # basicUnsafeCopy :: Mutable Vector s (Down a) -> Vector (Down a) -> ST s () # | |||||
| Unbox a => MVector MVector (Down a) | |||||
Defined in Data.Vector.Unboxed.Base Methods basicLength :: MVector s (Down a) -> Int basicUnsafeSlice :: Int -> Int -> MVector s (Down a) -> MVector s (Down a) basicOverlaps :: MVector s (Down a) -> MVector s (Down a) -> Bool basicUnsafeNew :: Int -> ST s (MVector s (Down a)) basicInitialize :: MVector s (Down a) -> ST s () basicUnsafeReplicate :: Int -> Down a -> ST s (MVector s (Down a)) basicUnsafeRead :: MVector s (Down a) -> Int -> ST s (Down a) basicUnsafeWrite :: MVector s (Down a) -> Int -> Down a -> ST s () basicClear :: MVector s (Down a) -> ST s () basicSet :: MVector s (Down a) -> Down a -> ST s () basicUnsafeCopy :: MVector s (Down a) -> MVector s (Down a) -> ST s () basicUnsafeMove :: MVector s (Down a) -> MVector s (Down a) -> ST s () basicUnsafeGrow :: MVector s (Down a) -> Int -> ST s (MVector s (Down a)) | |||||
| NFData a => NFData (Down a) | Since: deepseq-1.4.0.0 | ||||
Defined in Control.DeepSeq | |||||
| Monoid a => Monoid (Down a) | @since base-4.11.0.0 | ||||
| Semigroup a => Semigroup (Down a) | @since base-4.11.0.0 | ||||
| Bits a => Bits (Down a) | @since base-4.14.0.0 | ||||
Defined in GHC.Internal.Data.Ord Methods (.&.) :: Down a -> Down a -> Down a # (.|.) :: Down a -> Down a -> Down a # xor :: Down a -> Down a -> Down a # complement :: Down a -> Down a # shift :: Down a -> Int -> Down a # rotate :: Down a -> Int -> Down a # setBit :: Down a -> Int -> Down a # clearBit :: Down a -> Int -> Down a # complementBit :: Down a -> Int -> Down a # testBit :: Down a -> Int -> Bool # bitSizeMaybe :: Down a -> Maybe Int # shiftL :: Down a -> Int -> Down a # unsafeShiftL :: Down a -> Int -> Down a # shiftR :: Down a -> Int -> Down a # unsafeShiftR :: Down a -> Int -> Down a # rotateL :: Down a -> Int -> Down a # | |||||
| FiniteBits a => FiniteBits (Down a) | @since base-4.14.0.0 | ||||
Defined in GHC.Internal.Data.Ord Methods finiteBitSize :: Down a -> Int # countLeadingZeros :: Down a -> Int # countTrailingZeros :: Down a -> Int # | |||||
| Data a => Data (Down a) | @since base-4.12.0.0 | ||||
Defined in GHC.Internal.Data.Data Methods gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Down a -> c (Down a) # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c (Down a) # toConstr :: Down a -> Constr # dataTypeOf :: Down a -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c (Down a)) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c (Down a)) # gmapT :: (forall b. Data b => b -> b) -> Down a -> Down a # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Down a -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Down a -> r # gmapQ :: (forall d. Data d => d -> u) -> Down a -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Down a -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Down a -> m (Down a) # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Down a -> m (Down a) # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Down a -> m (Down a) # | |||||
| Bounded a => Bounded (Down a) | Swaps @since base-4.14.0.0 | ||||
| (Enum a, Bounded a, Eq a) => Enum (Down a) | Swaps @since base-4.18.0.0 | ||||
Defined in GHC.Internal.Data.Ord | |||||
| Floating a => Floating (Down a) | @since base-4.14.0.0 | ||||
| RealFloat a => RealFloat (Down a) | @since base-4.14.0.0 | ||||
Defined in GHC.Internal.Data.Ord Methods floatRadix :: Down a -> Integer # floatDigits :: Down a -> Int # floatRange :: Down a -> (Int, Int) # decodeFloat :: Down a -> (Integer, Int) # encodeFloat :: Integer -> Int -> Down a # significand :: Down a -> Down a # scaleFloat :: Int -> Down a -> Down a # isInfinite :: Down a -> Bool # isDenormalized :: Down a -> Bool # isNegativeZero :: Down a -> Bool # | |||||
| Storable a => Storable (Down a) | @since base-4.14.0.0 | ||||
| Generic (Down a) | |||||
Defined in GHC.Internal.Generics Associated Types
| |||||
| Ix a => Ix (Down a) | @since base-4.14.0.0 | ||||
Defined in GHC.Internal.Data.Ord | |||||
| Num a => Num (Down a) | @since base-4.11.0.0 | ||||
| Read a => Read (Down a) | This instance would be equivalent to the derived instances of the
@since base-4.7.0.0 | ||||
| Fractional a => Fractional (Down a) | @since base-4.14.0.0 | ||||
| Real a => Real (Down a) | @since base-4.14.0.0 | ||||
Defined in GHC.Internal.Data.Ord Methods toRational :: Down a -> Rational # | |||||
| RealFrac a => RealFrac (Down a) | @since base-4.14.0.0 | ||||
| Show a => Show (Down a) | This instance would be equivalent to the derived instances of the
@since base-4.7.0.0 | ||||
| Eq a => Eq (Down a) | @since base-4.6.0.0 | ||||
| Ord a => Ord (Down a) | @since base-4.6.0.0 | ||||
| Prim a => Prim (Down a) | Since: primitive-0.6.5.0 | ||||
Defined in Data.Primitive.Types Methods sizeOfType# :: Proxy (Down a) -> Int# # alignmentOfType# :: Proxy (Down a) -> Int# # alignment# :: Down a -> Int# # indexByteArray# :: ByteArray# -> Int# -> Down a # readByteArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s, Down a #) # writeByteArray# :: MutableByteArray# s -> Int# -> Down a -> State# s -> State# s # setByteArray# :: MutableByteArray# s -> Int# -> Int# -> Down a -> State# s -> State# s # indexOffAddr# :: Addr# -> Int# -> Down a # readOffAddr# :: Addr# -> Int# -> State# s -> (# State# s, Down a #) # writeOffAddr# :: Addr# -> Int# -> Down a -> State# s -> State# s # setOffAddr# :: Addr# -> Int# -> Int# -> Down a -> State# s -> State# s # | |||||
| Unbox a => Unbox (Down a) | |||||
Defined in Data.Vector.Unboxed.Base | |||||
| type Rep1 Down | @since base-4.12.0.0 | ||||
Defined in GHC.Internal.Generics | |||||
| newtype MVector s (Down a) | |||||
Defined in Data.Vector.Unboxed.Base | |||||
| type Rep (Down a) | @since base-4.12.0.0 | ||||
Defined in GHC.Internal.Generics | |||||
| newtype Vector (Down a) | |||||
Defined in Data.Vector.Unboxed.Base | |||||
Enum
Re-exported from Prelude:
Bounded
Re-exported from Prelude:
Num
Re-exported from Prelude:
fromInteger :: Num a => Integer -> 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
Real
Re-exported from Prelude:
toRational :: Real a => a -> Rational #
Rational equivalent of its real argument with full precision.
Integral
Re-exported from Prelude:
quot :: Integral a => a -> a -> a infixl 7 #
Integer division truncated toward zero.
WARNING: This function is partial (because it throws when 0 is passed as
the divisor) for all the integer types in base.
rem :: Integral a => a -> a -> a infixl 7 #
Integer remainder, satisfying
(x `quot` y)*y + (x `rem` y) == x
WARNING: This function is partial (because it throws when 0 is passed as
the divisor) for all the integer types in base.
div :: Integral a => a -> a -> a infixl 7 #
Integer division truncated toward negative infinity.
WARNING: This function is partial (because it throws when 0 is passed as
the divisor) for all the integer types in base.
mod :: Integral a => a -> a -> a infixl 7 #
Integer modulus, satisfying
(x `div` y)*y + (x `mod` y) == x
WARNING: This function is partial (because it throws when 0 is passed as
the divisor) for all the integer types in base.
gcd :: Integral a => a -> a -> a #
is the non-negative factor of both gcd x yx and y of which
every common factor of x and y is also a factor; for example
, gcd 4 2 = 2, gcd (-4) 6 = 2 = gcd 0 44. = gcd 0 00.
(That is, the common divisor that is "greatest" in the divisibility
preordering.)
Note: Since for signed fixed-width integer types, ,
the result may be negative if one of the arguments is abs minBound < 0 (and
necessarily is if the other is minBound0 or ) for such types.minBound
lcm :: Integral a => a -> a -> a #
is the smallest positive integer that both lcm x yx and y divide.
fromIntegral :: (Integral a, Num b) => a -> b #
General coercion from Integral types.
WARNING: This function performs silent truncation if the result type is not at least as big as the argument's type.
Fractional
Re-exported from Prelude:
(/) :: Fractional a => a -> a -> a infixl 7 #
Fractional division.
(^^) :: (Fractional a, Integral b) => a -> b -> a infixr 8 #
raise a number to an integral power
recip :: Fractional a => a -> a #
Reciprocal fraction.
fromRational :: Fractional a => Rational -> a #
Conversion from a Rational (that is ).
A floating literal stands for an application of Ratio IntegerfromRational
to a value of type Rational, so such literals have type
(.Fractional a) => a
realToFrac :: (Real a, Fractional b) => a -> b #
General coercion to Fractional types.
WARNING: This function goes through the Rational type, which does not have values for NaN for example.
This means it does not round-trip.
For Double it also behaves differently with or without -O0:
Prelude> realToFrac nan -- With -O0 -Infinity Prelude> realToFrac nan NaN
Floating
Re-exported from Prelude:
RealFrac
Re-exported from Prelude:
properFraction :: (RealFrac a, Integral b) => a -> (b, a) #
The function properFraction takes a real fractional number x
and returns a pair (n,f) such that x = n+f, and:
nis an integral number with the same sign asx; andfis a fraction with the same type and sign asx, and with absolute value less than1.
The default definitions of the ceiling, floor, truncate
and round functions are in terms of properFraction.
truncate :: (RealFrac a, Integral b) => a -> b #
returns the integer nearest truncate xx between zero and x
round :: (RealFrac a, Integral b) => a -> b #
returns the nearest integer to round xx;
the even integer if x is equidistant between two integers
floor :: (RealFrac a, Integral b) => a -> b #
returns the greatest integer not greater than floor xx
RealFloat
Re-exported from Prelude:
floatRadix :: RealFloat a => a -> Integer #
a constant function, returning the radix of the representation
(often 2)
floatDigits :: RealFloat a => a -> Int #
a constant function, returning the number of digits of
floatRadix in the significand
floatRange :: RealFloat a => a -> (Int, Int) #
a constant function, returning the lowest and highest values the exponent may assume
decodeFloat :: RealFloat a => a -> (Integer, Int) #
The function decodeFloat applied to a real floating-point
number returns the significand expressed as an Integer and an
appropriately scaled exponent (an Int). If
yields decodeFloat x(m,n), then x is equal in value to m*b^^n, where b
is the floating-point radix, and furthermore, either m and n
are both zero or else b^(d-1) <= , where abs m < b^dd is
the value of .
In particular, floatDigits x. If the type
contains a negative zero, also decodeFloat 0 = (0,0).
The result of decodeFloat (-0.0) = (0,0) is unspecified if either of
decodeFloat x or isNaN x is isInfinite xTrue.
encodeFloat :: RealFloat a => Integer -> Int -> a #
encodeFloat performs the inverse of decodeFloat in the
sense that for finite x with the exception of -0.0,
.
uncurry encodeFloat (decodeFloat x) = x is one of the two closest representable
floating-point numbers to encodeFloat m nm*b^^n (or ±Infinity if overflow
occurs); usually the closer, but if m contains too many bits,
the result may be rounded in the wrong direction.
exponent :: RealFloat a => a -> Int #
exponent corresponds to the second component of decodeFloat.
and for finite nonzero exponent 0 = 0x,
.
If exponent x = snd (decodeFloat x) + floatDigits xx is a finite floating-point number, it is equal in value to
, where significand x * b ^^ exponent xb is the
floating-point radix.
The behaviour is unspecified on infinite or NaN values.
significand :: RealFloat a => a -> a #
The first component of decodeFloat, scaled to lie in the open
interval (-1,1), either 0.0 or of absolute value >= 1/b,
where b is the floating-point radix.
The behaviour is unspecified on infinite or NaN values.
scaleFloat :: RealFloat a => Int -> a -> a #
multiplies a floating-point number by an integer power of the radix
isInfinite :: RealFloat a => a -> Bool #
True if the argument is an IEEE infinity or negative infinity
isDenormalized :: RealFloat a => a -> Bool #
True if the argument is too small to be represented in
normalized format
isNegativeZero :: RealFloat a => a -> Bool #
True if the argument is an IEEE negative zero
atan2 :: RealFloat a => a -> a -> a #
a version of arctangent taking two real floating-point arguments.
For real floating x and y, computes the angle
(from the positive x-axis) of the vector from the origin to the
point atan2 y x(x,y). returns a value in the range [atan2 y x-pi,
pi]. It follows the Common Lisp semantics for the origin when
signed zeroes are supported. , with atan2 y 1y in a type
that is RealFloat, should return the same value as .
A default definition of atan yatan2 is provided, but implementors
can provide a more accurate implementation.
Word
Re-exported from Data.Word:
byteSwap16 :: Word16 -> Word16 #
Reverse order of bytes in Word16.
@since base-4.7.0.0
byteSwap32 :: Word32 -> Word32 #
Reverse order of bytes in Word32.
@since base-4.7.0.0
byteSwap64 :: Word64 -> Word64 #
Reverse order of bytes in Word64.
@since base-4.7.0.0
Semigroup
Re-exported from Data.Semigroup:
(<>) :: Semigroup a => a -> a -> a infixr 6 #
An associative operation.
Examples
>>>[1,2,3] <> [4,5,6][1,2,3,4,5,6]
>>>Just [1, 2, 3] <> Just [4, 5, 6]Just [1,2,3,4,5,6]
>>>putStr "Hello, " <> putStrLn "World!"Hello, World!
Monoid
Re-exported from Data.Monoid:
Identity of mappend
Examples
>>>"Hello world" <> mempty"Hello world"
>>>mempty <> [1, 2, 3][1,2,3]
mappend :: Monoid a => a -> a -> a #
An associative operation
NOTE: This method is redundant and has the default
implementation since base-4.11.0.0.
Should it be implemented manually, since mappend = (<>)mappend is a synonym for
(<>), it is expected that the two functions are defined the same
way. In a future GHC release mappend will be removed from Monoid.
mconcat :: Monoid a => [a] -> a #
Fold a list using the monoid.
For most types, the default definition for mconcat will be
used, but the function is included in the class definition so
that an optimized version can be provided for specific types.
>>>mconcat ["Hello", " ", "Haskell", "!"]"Hello Haskell!"
Functor
Re-exported from Data.Functor:
fmap :: Functor f => (a -> b) -> f a -> f b #
fmap is used to apply a function of type (a -> b) to a value of type f a,
where f is a functor, to produce a value of type f b.
Note that for any type constructor with more than one parameter (e.g., Either),
only the last type parameter can be modified with fmap (e.g., b in `Either a b`).
Some type constructors with two parameters or more have a instance that allows
both the last and the penultimate parameters to be mapped over.Bifunctor
Examples
Convert from a to a Maybe IntMaybe String
using show:
>>>fmap show NothingNothing>>>fmap show (Just 3)Just "3"
Convert from an to an
Either Int IntEither Int String using show:
>>>fmap show (Left 17)Left 17>>>fmap show (Right 17)Right "17"
Double each element of a list:
>>>fmap (*2) [1,2,3][2,4,6]
Apply even to the second element of a pair:
>>>fmap even (2,2)(2,True)
It may seem surprising that the function is only applied to the last element of the tuple
compared to the list example above which applies it to every element in the list.
To understand, remember that tuples are type constructors with multiple type parameters:
a tuple of 3 elements (a,b,c) can also be written (,,) a b c and its Functor instance
is defined for Functor ((,,) a b) (i.e., only the third parameter is free to be mapped over
with fmap).
It explains why fmap can be used with tuples containing values of different types as in the
following example:
>>>fmap even ("hello", 1.0, 4)("hello",1.0,True)
(<$>) :: Functor f => (a -> b) -> f a -> 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.
Examples
Convert from a to a Maybe Int using Maybe
Stringshow:
>>>show <$> NothingNothing
>>>show <$> Just 3Just "3"
Convert from an to an
Either Int IntEither IntString using show:
>>>show <$> Left 17Left 17
>>>show <$> Right 17Right "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 => f a -> b -> f b infixl 4 #
Flipped version of <$.
@since base-4.7.0.0
Examples
Replace the contents of a with a constant
Maybe IntString:
>>>Nothing $> "foo"Nothing
>>>Just 90210 $> "foo"Just "foo"
Replace the contents of an
with a constant Either Int IntString, 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")
void :: Functor f => f a -> f () #
discards or ignores the result of evaluation, such
as the return value of an void valueIO action.
Examples
Replace the contents of a with unit:Maybe Int
>>>void NothingNothing
>>>void (Just 3)Just ()
Replace the contents of an
with unit, resulting in an Either Int Int: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
Applicative
Re-exported from Control.Applicative:
pure :: Applicative f => a -> f a #
Lift a value into the Structure.
Examples
>>>pure 1 :: Maybe IntJust 1
>>>pure 'z' :: [Char]"z"
>>>pure (pure ":D") :: Maybe [String]Just [":D"]
(<*>) :: Applicative f => f (a -> b) -> f a -> f b infixl 4 #
Sequential application.
A few functors support an implementation of <*> that is more
efficient than the default one.
Example
Used in combination with , (<$>) can be used to build a record.(<*>)
>>>data MyState = MyState {arg1 :: Foo, arg2 :: Bar, arg3 :: Baz}
>>>produceFoo :: Applicative f => f Foo>>>produceBar :: Applicative f => f Bar>>>produceBaz :: Applicative f => f Baz
>>>mkState :: Applicative f => f MyState>>>mkState = MyState <$> produceFoo <*> produceBar <*> produceBaz
(<*) :: Applicative f => f a -> f b -> f a infixl 4 #
Sequence actions, discarding the value of the second argument.
(*>) :: Applicative f => f a -> f b -> f b infixl 4 #
Sequence actions, discarding the value of the first argument.
Examples
If used in conjunction with the Applicative instance for Maybe,
you can chain Maybe computations, with a possible "early return"
in case of Nothing.
>>>Just 2 *> Just 3Just 3
>>>Nothing *> Just 3Nothing
Of course a more interesting use case would be to have effectful computations instead of just returning pure values.
>>>import Data.Char>>>import GHC.Internal.Text.ParserCombinators.ReadP>>>let p = string "my name is " *> munch1 isAlpha <* eof>>>readP_to_S p "my name is Simon"[("Simon","")]
liftA :: Applicative f => (a -> b) -> f a -> f b #
Lift a function to actions.
Equivalent to Functor's fmap but implemented using only Applicative's methods:
liftA f a = pure f <*> a
As such this function may be used to implement a Functor instance from an Applicative one.
Examples
Using the Applicative instance for Lists:
>>>liftA (+1) [1, 2][2,3]
Or the Applicative instance for Maybe
>>>liftA (+1) (Just 3)Just 4
liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c #
Lift a binary function to actions.
Some functors support an implementation of liftA2 that is more
efficient than the default one. In particular, if fmap is an
expensive operation, it is likely better to use liftA2 than to
fmap over the structure and then use <*>.
This became a typeclass method in 4.10.0.0. Prior to that, it was
a function defined in terms of <*> and fmap.
Example
>>>liftA2 (,) (Just 3) (Just 5)Just (3,5)
>>>liftA2 (+) [1, 2, 3] [4, 5, 6][5,6,7,6,7,8,7,8,9]
liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d #
Lift a ternary function to actions.
forever :: Applicative f => f a -> f b #
Repeat an action indefinitely.
Examples
A common use of forever is to process input from network sockets,
Handles, and channels
(e.g. MVar and
Chan).
For example, here is how we might implement an echo
server, using
forever both to listen for client connections on a network socket
and to echo client input on client connection handles:
echoServer :: Socket -> IO () echoServer socket =forever$ do client <- accept socketforkFinally(echo client) (\_ -> hClose client) where echo :: Handle -> IO () echo client =forever$ hGetLine client >>= hPutStrLn client
Note that "forever" isn't necessarily non-terminating.
If the action is in a and short-circuits after some number of iterations.
then MonadPlus actually returns forevermzero, effectively short-circuiting its caller.
traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f () #
Map each element of a structure to an Applicative action, evaluate these
actions from left to right, and ignore the results. For a version that
doesn't ignore the results see traverse.
traverse_ is just like mapM_, but generalised to Applicative actions.
Examples
Basic usage:
>>>traverse_ print ["Hello", "world", "!"]"Hello" "world" "!"
for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f () #
for_ is traverse_ with its arguments flipped. For a version
that doesn't ignore the results see for. This
is forM_ generalised to Applicative actions.
for_ is just like forM_, but generalised to Applicative actions.
Examples
Basic usage:
>>>for_ [1..4] print1 2 3 4
sequenceA_ :: (Foldable t, Applicative f) => t (f a) -> f () #
Evaluate each action in the structure from left to right, and
ignore the results. For a version that doesn't ignore the results
see sequenceA.
sequenceA_ is just like sequence_, but generalised to Applicative
actions.
Examples
Basic usage:
>>>sequenceA_ [print "Hello", print "world", print "!"]"Hello" "world" "!"
filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a] #
This generalizes the list-based filter function.
runIdentity (filterM (Identity . p) xs) == filter p xs
Examples
>>>filterM (\x -> doputStrLn ("Keep: " ++ show x ++ "?") answer <- getLine pure (answer == "y")) [1, 2, 3] Keep: 1? y Keep: 2? n Keep: 3? y [1,3]
>>>filterM (\x -> doputStr (show x) x' <- readLn pure (x == x')) [1, 2, 3] 12 22 33 [2,3]
replicateM_ :: Applicative m => Int -> m a -> m () #
zipWithM :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m [c] #
zipWithM_ :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m () #
Monad
Re-exported from Control.Monad:
return :: Monad m => a -> m a #
Inject a value into the monadic type.
This function should not be different from its default implementation
as pure. The justification for the existence of this function is
merely historic.
join :: Monad m => m (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.
'' can be understood as the join bssdo expression
do bs <- bss bs
Examples
>>>join [[1, 2, 3], [4, 5, 6], [7, 8, 9]][1,2,3,4,5,6,7,8,9]
>>>join (Just (Just 3))Just 3
A common use of join is to run an IO computation returned from
an STM transaction, since STM transactions
can't perform IO directly. Recall that
atomically :: STM a -> IO a
is used to run STM transactions atomically. So, by
specializing the types of atomically and join to
atomically:: STM (IO b) -> IO (IO b)join:: IO (IO b) -> IO b
we can compose them as
join.atomically:: STM (IO b) -> IO b
(>>=) :: Monad m => m a -> (a -> m b) -> m b infixl 1 #
Sequentially compose two actions, passing any value produced by the first as an argument to the second.
'as ' can be understood as the >>= bsdo expression
do a <- as bs a
An alternative name for this function is 'bind', but some people may refer to it as 'flatMap', which results from it being equivialent to
\x f ->join(fmapf x) :: Monad m => m a -> (a -> m b) -> m b
which can be seen as mapping a value with
Monad m => m a -> m (m b) and then 'flattening' m (m b) to m b using join.
(=<<) :: Monad m => (a -> m b) -> m a -> m b infixr 1 #
Same as >>=, but with the arguments interchanged.
as >>= f == f =<< as
liftM :: Monad m => (a1 -> r) -> m a1 -> m r #
Promote a function to a monad.
This is equivalent to fmap but specialised to Monads.
liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r #
Promote a function to a monad, scanning the monadic arguments from left to right.
Examples
>>>liftM2 (+) [0,1] [0,2][0,2,1,3]
>>>liftM2 (+) (Just 1) NothingNothing
>>>liftM2 (+) (+ 3) (* 2) 518
sequence_ :: (Foldable t, Monad m) => t (m a) -> m () #
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.
sequence_ is just like sequenceA_, but specialised to monadic
actions.
foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b #
The foldM function is analogous to foldl, except that its result is
encapsulated in a monad. Note that foldM works from left-to-right over
the list arguments. This could be an issue where ( and the `folded
function' are not commutative.>>)
foldM f a1 [x1, x2, ..., xm] == do a2 <- f a1 x1 a3 <- f a2 x2 ... f am xm
If right-to-left evaluation is required, the input list should be reversed.
foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m () #
Like foldM, but discards the result.
Foldable
Re-exported from Data.Foldable:
foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b #
Right-associative fold of a structure, lazy in the accumulator.
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, given an
operator lazy in its right argument, foldr can produce a terminating
expression from an unbounded list.
For a general Foldable structure this should be semantically identical
to,
foldr f z =foldrf z .toList
Examples
Basic usage:
>>>foldr (||) False [False, True, False]True
>>>foldr (||) False []False
>>>foldr (\c acc -> acc ++ [c]) "foo" ['a', 'b', 'c', 'd']"foodcba"
Infinite structures
⚠️ Applying foldr to infinite structures usually doesn't terminate.
It may still terminate under one of the following conditions:
- the folding function is short-circuiting
- the folding function is lazy on its second argument
Short-circuiting
( short-circuits on ||)True values, so the following terminates
because there is a True value finitely far from the left side:
>>>foldr (||) False (True : repeat False)True
But the following doesn't terminate:
>>>foldr (||) False (repeat False ++ [True])* Hangs forever *
Laziness in the second argument
Applying foldr to infinite structures terminates when the operator is
lazy in its second argument (the initial accumulator is never used in
this case, and so could be left undefined, but [] is more clear):
>>>take 5 $ foldr (\i acc -> i : fmap (+3) acc) [] (repeat 1)[1,4,7,10,13]
foldl' :: Foldable t => (b -> a -> b) -> b -> t a -> b #
Left-associative fold of a structure but with strict application of the operator.
This ensures that each step of the fold is forced to Weak Head Normal
Form before being applied, avoiding the collection of thunks that would
otherwise occur. This is often what you want to strictly reduce a
finite structure to a single strict result (e.g. sum).
For a general Foldable structure this should be semantically identical
to,
foldl' f z =foldl'f z .toList
@since base-4.6.0.0
fold :: (Foldable t, Monoid m) => t m -> m #
Given a structure with elements whose type is a Monoid, combine them
via the monoid's ( operator. This fold is right-associative and
lazy in the accumulator. When you need a strict left-associative fold,
use <>)foldMap' instead, with id as the map.
Examples
Basic usage:
>>>fold [[1, 2, 3], [4, 5], [6], []][1,2,3,4,5,6]
>>>fold $ Node (Leaf (Sum 1)) (Sum 3) (Leaf (Sum 5))Sum {getSum = 9}
Folds of unbounded structures do not terminate when the monoid's
( operator is strict:<>)
>>>fold (repeat Nothing)* Hangs forever *
Lazy corecursive folds of unbounded structures are fine:
>>>take 12 $ fold $ map (\i -> [i..i+2]) [0..][0,1,2,1,2,3,2,3,4,3,4,5]>>>sum $ take 4000000 $ fold $ map (\i -> [i..i+2]) [0..]2666668666666
foldMap :: (Foldable t, Monoid m) => (a -> m) -> t a -> m #
Map each element of the structure into a monoid, and combine the
results with (. This fold is right-associative and lazy in the
accumulator. For strict left-associative folds consider <>)foldMap'
instead.
Examples
Basic usage:
>>>foldMap Sum [1, 3, 5]Sum {getSum = 9}
>>>foldMap Product [1, 3, 5]Product {getProduct = 15}
>>>foldMap (replicate 3) [1, 2, 3][1,1,1,2,2,2,3,3,3]
When a Monoid's ( is lazy in its second argument, <>)foldMap can
return a result even from an unbounded structure. For example, lazy
accumulation enables Data.ByteString.Builder to efficiently serialise
large data structures and produce the output incrementally:
>>>import qualified Data.ByteString.Lazy as L>>>import qualified Data.ByteString.Builder as B>>>let bld :: Int -> B.Builder; bld i = B.intDec i <> B.word8 0x20>>>let lbs = B.toLazyByteString $ foldMap bld [0..]>>>L.take 64 lbs"0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24"
foldMapM :: (Monad m, Monoid w, Foldable t) => (a -> m w) -> t a -> m w #
Extend foldMap to allow side effects.
Internally, this is implemented using a strict left fold. This is used for
performance reasons. It also necessitates that this function has a Monad
constraint and not just an Applicative constraint. For more information,
see
https://github.com/commercialhaskell/rio/pull/99#issuecomment-394179757.
Since: 0.1.3.0
elem :: (Foldable t, Eq a) => a -> t a -> Bool infix 4 #
Does the element occur in the structure?
Note: elem is often used in infix form.
Examples
Basic usage:
>>>3 `elem` []False
>>>3 `elem` [1,2]False
>>>3 `elem` [1,2,3,4,5]True
For infinite structures, the default implementation of elem
terminates if the sought-after value exists at a finite distance
from the left side of the structure:
>>>3 `elem` [1..]True
>>>3 `elem` ([4..] ++ [3])* Hangs forever *
@since base-4.8.0.0
notElem :: (Foldable t, Eq a) => a -> t a -> Bool infix 4 #
notElem is the negation of elem.
Examples
Basic usage:
>>>3 `notElem` []True
>>>3 `notElem` [1,2]True
>>>3 `notElem` [1,2,3,4,5]False
For infinite structures, notElem terminates if the value exists at a
finite distance from the left side of the structure:
>>>3 `notElem` [1..]False
>>>3 `notElem` ([4..] ++ [3])* Hangs forever *
null :: Foldable t => t a -> Bool #
Test whether the structure is empty. The default implementation is Left-associative and lazy in both the initial element and the accumulator. Thus optimised for structures where the first element can be accessed in constant time. Structures where this is not the case should have a non-default implementation.
Examples
Basic usage:
>>>null []True
>>>null [1]False
null is expected to terminate even for infinite structures.
The default implementation terminates provided the structure
is bounded on the left (there is a leftmost element).
>>>null [1..]False
@since base-4.8.0.0
length :: Foldable t => t a -> Int #
Returns the size/length of a finite structure as an Int. The
default implementation just counts elements starting with the leftmost.
Instances for structures that can compute the element count faster
than via element-by-element counting, should provide a specialised
implementation.
Examples
Basic usage:
>>>length []0
>>>length ['a', 'b', 'c']3>>>length [1..]* Hangs forever *
@since base-4.8.0.0
sum :: (Foldable t, Num a) => t a -> a #
The sum function computes the sum of the numbers of a structure.
Examples
Basic usage:
>>>sum []0
>>>sum [42]42
>>>sum [1..10]55
>>>sum [4.1, 2.0, 1.7]7.8
>>>sum [1..]* Hangs forever *
@since base-4.8.0.0
product :: (Foldable t, Num a) => t a -> a #
The product function computes the product of the numbers of a
structure.
Examples
Basic usage:
>>>product []1
>>>product [42]42
>>>product [1..10]3628800
>>>product [4.1, 2.0, 1.7]13.939999999999998
>>>product [1..]* Hangs forever *
@since base-4.8.0.0
all :: Foldable t => (a -> Bool) -> t a -> Bool #
Determines whether all elements of the structure satisfy the predicate.
Examples
Basic usage:
>>>all (> 3) []True
>>>all (> 3) [1,2]False
>>>all (> 3) [1,2,3,4,5]False
>>>all (> 3) [1..]False
>>>all (> 3) [4..]* Hangs forever *
any :: Foldable t => (a -> Bool) -> t a -> Bool #
Determines whether any element of the structure satisfies the predicate.
Examples
Basic usage:
>>>any (> 3) []False
>>>any (> 3) [1,2]False
>>>any (> 3) [1,2,3,4,5]True
>>>any (> 3) [1..]True
>>>any (> 3) [0, -1..]* Hangs forever *
and :: 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.
Examples
Basic usage:
>>>and []True
>>>and [True]True
>>>and [False]False
>>>and [True, True, False]False
>>>and (False : repeat True) -- Infinite list [False,True,True,True,...False
>>>and (repeat True)* Hangs forever *
or :: Foldable t => t Bool -> Bool #
or returns the disjunction of a container of Bools. For the
result to be False, the container must be finite; True, however,
results from a True value finitely far from the left end.
Examples
Basic usage:
>>>or []False
>>>or [True]True
>>>or [False]False
>>>or [True, True, False]True
>>>or (True : repeat False) -- Infinite list [True,False,False,False,...True
>>>or (repeat False)* Hangs forever *
toList :: Foldable t => t a -> [a] #
List of elements of a structure, from left to right. If the entire list is intended to be reduced via a fold, just fold the structure directly bypassing the list.
Examples
Basic usage:
>>>toList Nothing[]
>>>toList (Just 42)[42]
>>>toList (Left "foo")[]
>>>toList (Node (Leaf 5) 17 (Node Empty 12 (Leaf 8)))[5,17,12,8]
For lists, toList is the identity:
>>>toList [1, 2, 3][1,2,3]
@since base-4.8.0.0
concat :: Foldable t => t [a] -> [a] #
The concatenation of all the elements of a container of lists.
Examples
Basic usage:
>>>concat (Just [1, 2, 3])[1,2,3]
>>>concat (Left 42)[]
>>>concat [[1, 2, 3], [4, 5], [6], []][1,2,3,4,5,6]
concatMap :: Foldable t => (a -> [b]) -> t a -> [b] #
Map a function over all the elements of a container and concatenate the resulting lists.
Examples
Basic usage:
>>>concatMap (take 3) [[1..], [10..], [100..], [1000..]][1,2,3,10,11,12,100,101,102,1000,1001,1002]
>>>concatMap (take 3) (Just [1..])[1,2,3]
Traversable
Re-exported from Data.Traversable:
traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b) #
Map each element of a structure to an action, evaluate these actions
from left to right, and collect the results. For a version that ignores
the results see traverse_.
Examples
Basic usage:
In the first two examples we show each evaluated action mapping to the output structure.
>>>traverse Just [1,2,3,4]Just [1,2,3,4]
>>>traverse id [Right 1, Right 2, Right 3, Right 4]Right [1,2,3,4]
In the next examples, we show that Nothing and Left values short
circuit the created structure.
>>>traverse (const Nothing) [1,2,3,4]Nothing
>>>traverse (\x -> if odd x then Just x else Nothing) [1,2,3,4]Nothing
>>>traverse id [Right 1, Right 2, Right 3, Right 4, Left 0]Left 0
for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b) #
sequenceA :: (Traversable t, Applicative f) => t (f a) -> f (t a) #
Evaluate each action in the structure from left to right, and
collect the results. For a version that ignores the results
see sequenceA_.
Examples
Basic usage:
For the first two examples we show sequenceA fully evaluating a a structure and collecting the results.
>>>sequenceA [Just 1, Just 2, Just 3]Just [1,2,3]
>>>sequenceA [Right 1, Right 2, Right 3]Right [1,2,3]
The next two example show Nothing and Just will short circuit
the resulting structure if present in the input. For more context,
check the Traversable instances for Either and Maybe.
>>>sequenceA [Just 1, Just 2, Just 3, Nothing]Nothing
>>>sequenceA [Right 1, Right 2, Right 3, Left 4]Left 4
mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b) #
Map each element of a structure to a monadic action, evaluate
these actions from left to right, and collect the results. For
a version that ignores the results see mapM_.
Examples
forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b) #
sequence :: (Traversable t, Monad m) => t (m a) -> m (t a) #
Evaluate each monadic action in the structure from left to
right, and collect the results. For a version that ignores the
results see sequence_.
Examples
Basic usage:
The first two examples are instances where the input and
and output of sequence are isomorphic.
>>>sequence $ Right [1,2,3,4][Right 1,Right 2,Right 3,Right 4]
>>>sequence $ [Right 1,Right 2,Right 3,Right 4]Right [1,2,3,4]
The following examples demonstrate short circuit behavior
for sequence.
>>>sequence $ Left [1,2,3,4]Left [1,2,3,4]
>>>sequence $ [Left 0, Right 1,Right 2,Right 3,Right 4]Left 0
Alternative
Re-exported from Control.Applicative:
(<|>) :: Alternative f => f a -> f a -> f a infixl 3 #
An associative binary operation
some :: Alternative f => f a -> f [a] #
One or more.
Examples
>>>some (putStr "la")lalalalalalalalala... * goes on forever *
>>>some Nothingnothing
>>>take 5 <$> some (Just 1)* hangs forever *
Note that this function can be used with Parsers based on
Applicatives. In that case some parser will attempt to
parse parser one or more times until it fails.
many :: Alternative f => f a -> f [a] #
Zero or more.
Examples
>>>many (putStr "la")lalalalalalalalala... * goes on forever *
>>>many NothingJust []
>>>take 5 <$> many (Just 1)* hangs forever *
Note that this function can be used with Parsers based on
Applicatives. In that case many parser will attempt to
parse parser zero or more times until it fails.
optional :: Alternative f => f a -> f (Maybe a) #
One or none.
It is useful for modelling any computation that is allowed to fail.
Examples
Using the Alternative instance of Control.Monad.Except, the following functions:
>>>import Control.Monad.Except
>>>canFail = throwError "it failed" :: Except String Int>>>final = return 42 :: Except String Int
Can be combined by allowing the first function to fail:
>>>runExcept $ canFail *> finalLeft "it failed"
>>>runExcept $ optional canFail *> finalRight 42
asum :: (Foldable t, Alternative f) => t (f a) -> f a #
The sum of a collection of actions using (<|>), generalizing concat.
asum is just like msum, but generalised to Alternative.
Examples
Basic usage:
>>>asum [Just "Hello", Nothing, Just "World"]Just "Hello"
guard :: Alternative f => Bool -> f () #
Conditional failure of Alternative computations. Defined by
guard True =pure() guard False =empty
Examples
Common uses of guard include conditionally signalling an error in
an error monad and conditionally rejecting the current choice in an
Alternative-based parser.
As an example of signalling an error in the error monad Maybe,
consider a safe division function safeDiv x y that returns
Nothing when the denominator y is zero and otherwise. For example:Just (x `div`
y)
>>>safeDiv 4 0Nothing
>>>safeDiv 4 2Just 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)
when :: Applicative f => Bool -> f () -> f () #
Conditional execution of Applicative expressions. For example,
Examples
when debug (putStrLn "Debugging")
will output the string Debugging if the Boolean value debug
is True, and otherwise do nothing.
>>>putStr "pi:" >> when False (print 3.14159)pi:
unless :: Applicative f => Bool -> f () -> f () #
The reverse of when.
Examples
>>>do x <- getLineunless (x == "hi") (putStrLn "hi!") comingupwithexamplesisdifficult hi!
>>>unless (pi > exp 1) NothingJust ()
Bifunctor
Re-exported from Data.Bifunctor:
Bifoldable
Re-exported from Data.Bifoldable:
bifold :: (Bifoldable p, Monoid m) => p m m -> m #
Combines the elements of a structure using a monoid.
bifold≡bifoldMapidid
Examples
Basic usage:
>>>bifold (Right [1, 2, 3])[1,2,3]
>>>bifold (Left [5, 6])[5,6]
>>>bifold ([1, 2, 3], [4, 5])[1,2,3,4,5]
>>>bifold (Product 6, Product 7)Product {getProduct = 42}
>>>bifold (Sum 6, Sum 7)Sum {getSum = 13}
Since: base-4.10.0.0
bifoldMap :: (Bifoldable p, Monoid m) => (a -> m) -> (b -> m) -> p a b -> m #
Combines the elements of a structure, given ways of mapping them to a common monoid.
bifoldMapf g ≡bifoldr(mappend. f) (mappend. g)mempty
Examples
Basic usage:
>>>bifoldMap (take 3) (fmap digitToInt) ([1..], "89")[1,2,3,8,9]
>>>bifoldMap (take 3) (fmap digitToInt) (Left [1..])[1,2,3]
>>>bifoldMap (take 3) (fmap digitToInt) (Right "89")[8,9]
Since: base-4.10.0.0
bifoldr :: Bifoldable p => (a -> c -> c) -> (b -> c -> c) -> c -> p a b -> c #
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:
bifoldrf g z ≡foldr(eitherf g) z . toEitherList
Examples
Basic usage:
> bifoldr (+) (*) 3 (5, 7) 26 -- 5 + (7 * 3) > bifoldr (+) (*) 3 (7, 5) 22 -- 7 + (5 * 3) > bifoldr (+) (*) 3 (Right 5) 15 -- 5 * 3 > bifoldr (+) (*) 3 (Left 5) 8 -- 5 + 3
Since: base-4.10.0.0
bifoldl :: Bifoldable p => (c -> a -> c) -> (c -> b -> c) -> c -> p a b -> c #
Combines the elements of a structure in a left 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:
bifoldlf g z ≡foldl(acc ->either(f acc) (g acc)) z . toEitherList
Note that if you want an efficient left-fold, you probably want to use
bifoldl' instead of bifoldl. The reason is that the latter does not
force the "inner" results, resulting in a thunk chain which then must be
evaluated from the outside-in.
Examples
Basic usage:
> bifoldl (+) (*) 3 (5, 7) 56 -- (5 + 3) * 7 > bifoldl (+) (*) 3 (7, 5) 50 -- (7 + 3) * 5 > bifoldl (+) (*) 3 (Right 5) 15 -- 5 * 3 > bifoldl (+) (*) 3 (Left 5) 8 -- 5 + 3
Since: base-4.10.0.0
bifoldr' :: Bifoldable t => (a -> c -> c) -> (b -> c -> c) -> c -> t a b -> c #
As bifoldr, but strict in the result of the reduction functions at each
step.
Since: base-4.10.0.0
bifoldr1 :: Bifoldable t => (a -> a -> a) -> t a a -> a #
A variant of bifoldr that has no base case,
and thus may only be applied to non-empty structures.
Examples
Basic usage:
>>>bifoldr1 (+) (5, 7)12
>>>bifoldr1 (+) (Right 7)7
>>>bifoldr1 (+) (Left 5)5
> bifoldr1 (+) (BiList [1, 2] [3, 4]) 10 -- 1 + (2 + (3 + 4))
>>>bifoldr1 (+) (BiList [1, 2] [])3
On empty structures, this function throws an exception:
>>>bifoldr1 (+) (BiList [] [])*** Exception: bifoldr1: empty structure ...
Since: base-4.10.0.0
bifoldrM :: (Bifoldable t, Monad m) => (a -> c -> m c) -> (b -> c -> m c) -> c -> t a b -> m c #
Right associative monadic bifold over a structure.
Since: base-4.10.0.0
bifoldl' :: Bifoldable t => (a -> b -> a) -> (a -> c -> a) -> a -> t b c -> a #
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).
Since: base-4.10.0.0
bifoldl1 :: Bifoldable t => (a -> a -> a) -> t a a -> a #
A variant of bifoldl that has no base case,
and thus may only be applied to non-empty structures.
Examples
Basic usage:
>>>bifoldl1 (+) (5, 7)12
>>>bifoldl1 (+) (Right 7)7
>>>bifoldl1 (+) (Left 5)5
> bifoldl1 (+) (BiList [1, 2] [3, 4]) 10 -- ((1 + 2) + 3) + 4
>>>bifoldl1 (+) (BiList [1, 2] [])3
On empty structures, this function throws an exception:
>>>bifoldl1 (+) (BiList [] [])*** Exception: bifoldl1: empty structure ...
Since: base-4.10.0.0
bifoldlM :: (Bifoldable t, Monad m) => (a -> b -> m a) -> (a -> c -> m a) -> a -> t b c -> m a #
Left associative monadic bifold over a structure.
Examples
Basic usage:
>>>bifoldlM (\a b -> print b >> pure a) (\a c -> print (show c) >> pure a) 42 ("Hello", True)"Hello" "True" 42
>>>bifoldlM (\a b -> print b >> pure a) (\a c -> print (show c) >> pure a) 42 (Right True)"True" 42
>>>bifoldlM (\a b -> print b >> pure a) (\a c -> print (show c) >> pure a) 42 (Left "Hello")"Hello" 42
Since: base-4.10.0.0
bitraverse_ :: (Bifoldable t, Applicative f) => (a -> f c) -> (b -> f d) -> t a b -> f () #
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.
Examples
Basic usage:
>>>bitraverse_ print (print . show) ("Hello", True)"Hello" "True"
>>>bitraverse_ print (print . show) (Right True)"True"
>>>bitraverse_ print (print . show) (Left "Hello")"Hello"
Since: base-4.10.0.0
bifor_ :: (Bifoldable t, Applicative f) => t a b -> (a -> f c) -> (b -> f d) -> f () #
As bitraverse_, but with the structure as the primary argument. For a
version that doesn't ignore the results, see bifor.
Examples
Basic usage:
>>>bifor_ ("Hello", True) print (print . show)"Hello" "True"
>>>bifor_ (Right True) print (print . show)"True"
>>>bifor_ (Left "Hello") print (print . show)"Hello"
Since: base-4.10.0.0
bisequence_ :: (Bifoldable t, Applicative f) => t (f a) (f b) -> f () #
Evaluate each action in the structure from left to right, and ignore the
results. For a version that doesn't ignore the results, see
bisequence.
Examples
Basic usage:
>>>bisequence_ (print "Hello", print "World")"Hello" "World"
>>>bisequence_ (Left (print "Hello"))"Hello"
>>>bisequence_ (Right (print "World"))"World"
Since: base-4.10.0.0
biasum :: (Bifoldable t, Alternative f) => t (f a) (f a) -> f a #
The sum of a collection of actions, generalizing biconcat.
Examples
Basic usage:
>>>biasum (Nothing, Nothing)Nothing
>>>biasum (Nothing, Just 42)Just 42
>>>biasum (Just 18, Nothing)Just 18
>>>biasum (Just 18, Just 42)Just 18
Since: base-4.10.0.0
biList :: Bifoldable t => t a a -> [a] #
Collects the list of elements of a structure, from left to right.
Examples
Basic usage:
>>>biList (18, 42)[18,42]
>>>biList (Left 18)[18]
Since: base-4.10.0.0
binull :: Bifoldable t => t a b -> Bool #
Test whether the structure is empty.
Examples
Basic usage:
>>>binull (18, 42)False
>>>binull (Right 42)False
>>>binull (BiList [] [])True
Since: base-4.10.0.0
bilength :: Bifoldable t => t a b -> Int #
Returns the size/length of a finite structure as an Int.
Examples
Basic usage:
>>>bilength (True, 42)2
>>>bilength (Right 42)1
>>>bilength (BiList [1,2,3] [4,5])5
>>>bilength (BiList [] [])0
On infinite structures, this function hangs:
> bilength (BiList [1..] []) * Hangs forever *
Since: base-4.10.0.0
bielem :: (Bifoldable t, Eq a) => a -> t a a -> Bool #
Does the element occur in the structure?
Examples
Basic usage:
>>>bielem 42 (17, 42)True
>>>bielem 42 (17, 43)False
>>>bielem 42 (Left 42)True
>>>bielem 42 (Right 13)False
>>>bielem 42 (BiList [1..5] [1..100])True
>>>bielem 42 (BiList [1..5] [1..41])False
Since: base-4.10.0.0
bimaximum :: (Bifoldable t, Ord a) => t a a -> a #
The largest element of a non-empty structure.
Examples
Basic usage:
>>>bimaximum (42, 17)42
>>>bimaximum (Right 42)42
>>>bimaximum (BiList [13, 29, 4] [18, 1, 7])29
>>>bimaximum (BiList [13, 29, 4] [])29
On empty structures, this function throws an exception:
>>>bimaximum (BiList [] [])*** Exception: bimaximum: empty structure ...
Since: base-4.10.0.0
biminimum :: (Bifoldable t, Ord a) => t a a -> a #
The least element of a non-empty structure.
Examples
Basic usage:
>>>biminimum (42, 17)17
>>>biminimum (Right 42)42
>>>biminimum (BiList [13, 29, 4] [18, 1, 7])1
>>>biminimum (BiList [13, 29, 4] [])4
On empty structures, this function throws an exception:
>>>biminimum (BiList [] [])*** Exception: biminimum: empty structure ...
Since: base-4.10.0.0
bisum :: (Bifoldable t, Num a) => t a a -> a #
The bisum function computes the sum of the numbers of a structure.
Examples
Basic usage:
>>>bisum (42, 17)59
>>>bisum (Right 42)42
>>>bisum (BiList [13, 29, 4] [18, 1, 7])72
>>>bisum (BiList [13, 29, 4] [])46
>>>bisum (BiList [] [])0
Since: base-4.10.0.0
biproduct :: (Bifoldable t, Num a) => t a a -> a #
The biproduct function computes the product of the numbers of a
structure.
Examples
Basic usage:
>>>biproduct (42, 17)714
>>>biproduct (Right 42)42
>>>biproduct (BiList [13, 29, 4] [18, 1, 7])190008
>>>biproduct (BiList [13, 29, 4] [])1508
>>>biproduct (BiList [] [])1
Since: base-4.10.0.0
biconcat :: Bifoldable t => t [a] [a] -> [a] #
Reduces a structure of lists to the concatenation of those lists.
Examples
Basic usage:
>>>biconcat ([1, 2, 3], [4, 5])[1,2,3,4,5]
>>>biconcat (Left [1, 2, 3])[1,2,3]
>>>biconcat (BiList [[1, 2, 3, 4, 5], [6, 7, 8]] [[9]])[1,2,3,4,5,6,7,8,9]
Since: base-4.10.0.0
biconcatMap :: Bifoldable t => (a -> [c]) -> (b -> [c]) -> t a b -> [c] #
Given a means of mapping the elements of a structure to lists, computes the concatenation of all such lists in order.
Examples
Basic usage:
>>>biconcatMap (take 3) (fmap digitToInt) ([1..], "89")[1,2,3,8,9]
>>>biconcatMap (take 3) (fmap digitToInt) (Left [1..])[1,2,3]
>>>biconcatMap (take 3) (fmap digitToInt) (Right "89")[8,9]
Since: base-4.10.0.0
biand :: Bifoldable t => t Bool Bool -> Bool #
biand returns the conjunction of a container of Bools. For the
result to be True, the container must be finite; False, however,
results from a False value finitely far from the left end.
Examples
Basic usage:
>>>biand (True, False)False
>>>biand (True, True)True
>>>biand (Left True)True
Empty structures yield True:
>>>biand (BiList [] [])True
A False value finitely far from the left end yields False (short circuit):
>>>biand (BiList [True, True, False, True] (repeat True))False
A False value infinitely far from the left end hangs:
> biand (BiList (repeat True) [False]) * Hangs forever *
An infinitely True value hangs:
> biand (BiList (repeat True) []) * Hangs forever *
Since: base-4.10.0.0
bior :: Bifoldable t => t Bool Bool -> Bool #
bior returns the disjunction of a container of Bools. For the
result to be False, the container must be finite; True, however,
results from a True value finitely far from the left end.
Examples
Basic usage:
>>>bior (True, False)True
>>>bior (False, False)False
>>>bior (Left True)True
Empty structures yield False:
>>>bior (BiList [] [])False
A True value finitely far from the left end yields True (short circuit):
>>>bior (BiList [False, False, True, False] (repeat False))True
A True value infinitely far from the left end hangs:
> bior (BiList (repeat False) [True]) * Hangs forever *
An infinitely False value hangs:
> bior (BiList (repeat False) []) * Hangs forever *
Since: base-4.10.0.0
biany :: Bifoldable t => (a -> Bool) -> (b -> Bool) -> t a b -> Bool #
Determines whether any element of the structure satisfies its appropriate
predicate argument. Empty structures yield False.
Examples
Basic usage:
>>>biany even isDigit (27, 't')False
>>>biany even isDigit (27, '8')True
>>>biany even isDigit (26, 't')True
>>>biany even isDigit (Left 27)False
>>>biany even isDigit (Left 26)True
>>>biany even isDigit (BiList [27, 53] ['t', '8'])True
Empty structures yield False:
>>>biany even isDigit (BiList [] [])False
Since: base-4.10.0.0
biall :: Bifoldable t => (a -> Bool) -> (b -> Bool) -> t a b -> Bool #
Determines whether all elements of the structure satisfy their appropriate
predicate argument. Empty structures yield True.
Examples
Basic usage:
>>>biall even isDigit (27, 't')False
>>>biall even isDigit (26, '8')True
>>>biall even isDigit (Left 27)False
>>>biall even isDigit (Left 26)True
>>>biall even isDigit (BiList [26, 52] ['3', '8'])True
Empty structures yield True:
>>>biall even isDigit (BiList [] [])True
Since: base-4.10.0.0
bimaximumBy :: Bifoldable t => (a -> a -> Ordering) -> t a a -> a #
The largest element of a non-empty structure with respect to the given comparison function.
Examples
Basic usage:
>>>bimaximumBy compare (42, 17)42
>>>bimaximumBy compare (Left 17)17
>>>bimaximumBy compare (BiList [42, 17, 23] [-5, 18])42
On empty structures, this function throws an exception:
>>>bimaximumBy compare (BiList [] [])*** Exception: bifoldr1: empty structure ...
Since: base-4.10.0.0
biminimumBy :: Bifoldable t => (a -> a -> Ordering) -> t a a -> a #
The least element of a non-empty structure with respect to the given comparison function.
Examples
Basic usage:
>>>biminimumBy compare (42, 17)17
>>>biminimumBy compare (Left 17)17
>>>biminimumBy compare (BiList [42, 17, 23] [-5, 18])-5
On empty structures, this function throws an exception:
>>>biminimumBy compare (BiList [] [])*** Exception: bifoldr1: empty structure ...
Since: base-4.10.0.0
binotElem :: (Bifoldable t, Eq a) => a -> t a a -> Bool #
bifind :: Bifoldable t => (a -> Bool) -> t a a -> Maybe a #
The bifind function takes a predicate and a structure and returns
the leftmost element of the structure matching the predicate, or
Nothing if there is no such element.
Examples
Basic usage:
>>>bifind even (27, 53)Nothing
>>>bifind even (27, 52)Just 52
>>>bifind even (26, 52)Just 26
Empty structures always yield Nothing:
>>>bifind even (BiList [] [])Nothing
Since: base-4.10.0.0
Bitraverse
Re-exported from Data.Bitraversable:
bitraverse :: (Bitraversable t, Applicative f) => (a -> f c) -> (b -> f d) -> t a b -> f (t c d) #
Evaluates the relevant functions at each element in the structure, running the action, and builds a new structure with the same shape, using the results produced from sequencing the actions.
bitraversef g ≡bisequenceA.bimapf g
For a version that ignores the results, see bitraverse_.
Examples
Basic usage:
>>>bitraverse listToMaybe (find odd) (Left [])Nothing
>>>bitraverse listToMaybe (find odd) (Left [1, 2, 3])Just (Left 1)
>>>bitraverse listToMaybe (find odd) (Right [4, 5])Just (Right 5)
>>>bitraverse listToMaybe (find odd) ([1, 2, 3], [4, 5])Just (1,5)
>>>bitraverse listToMaybe (find odd) ([], [4, 5])Nothing
Since: base-4.10.0.0
bisequence :: (Bitraversable t, Applicative f) => t (f a) (f b) -> f (t a b) #
Sequences all the actions in a structure, building a new structure with
the same shape using the results of the actions. For a version that ignores
the results, see bisequence_.
bisequence≡bitraverseidid
Examples
Basic usage:
>>>bisequence (Just 4, Nothing)Nothing
>>>bisequence (Just 4, Just 5)Just (4,5)
>>>bisequence ([1, 2, 3], [4, 5])[(1,4),(1,5),(2,4),(2,5),(3,4),(3,5)]
Since: base-4.10.0.0
bifor :: (Bitraversable t, Applicative f) => t a b -> (a -> f c) -> (b -> f d) -> f (t c d) #
bifor is bitraverse with the structure as the first argument. For a
version that ignores the results, see bifor_.
Examples
Basic usage:
>>>bifor (Left []) listToMaybe (find even)Nothing
>>>bifor (Left [1, 2, 3]) listToMaybe (find even)Just (Left 1)
>>>bifor (Right [4, 5]) listToMaybe (find even)Just (Right 4)
>>>bifor ([1, 2, 3], [4, 5]) listToMaybe (find even)Just (1,4)
>>>bifor ([], [4, 5]) listToMaybe (find even)Nothing
Since: base-4.10.0.0
bimapAccumL :: Bitraversable t => (a -> b -> (a, c)) -> (a -> d -> (a, e)) -> a -> t b d -> (a, t c e) #
The bimapAccumL function behaves like a combination of bimap and
bifoldl; it traverses a structure from left to right, threading a state
of type a and using the given actions to compute new elements for the
structure.
Examples
Basic usage:
>>>bimapAccumL (\acc bool -> (acc + 1, show bool)) (\acc string -> (acc * 2, reverse string)) 3 (True, "foo")(8,("True","oof"))
Since: base-4.10.0.0
bimapAccumR :: Bitraversable t => (a -> b -> (a, c)) -> (a -> d -> (a, e)) -> a -> t b d -> (a, t c e) #
The bimapAccumR function behaves like a combination of bimap and
bifoldr; it traverses a structure from right to left, threading a state
of type a and using the given actions to compute new elements for the
structure.
Examples
Basic usage:
>>>bimapAccumR (\acc bool -> (acc + 1, show bool)) (\acc string -> (acc * 2, reverse string)) 3 (True, "foo")(7,("True","oof"))
Since: base-4.10.0.0
MonadPlus
Re-exported from Control.Monad:
mplus :: MonadPlus m => m a -> m a -> m a #
An associative operation. The default definition is
mplus = (<|>)
Arrow
Re-exported from Control.Arrow and Control.Category:
(&&&) :: Arrow a => a b c -> a b c' -> a b (c, c') infixr 3 #
Fanout: send the input to both argument arrows and combine their output.
The default definition may be overridden with a more efficient version if desired.
(***) :: Arrow a => a b c -> a b' c' -> a (b, b') (c, c') infixr 3 #
Split the input between the two argument arrows and combine their output. Note that this is in general not a functor.
The default definition may be overridden with a more efficient version if desired.
(>>>) :: forall {k} cat (a :: k) (b :: k) (c :: k). Category cat => cat a b -> cat b c -> cat a c infixr 1 #
Left-to-right composition
Function
Re-exported from Data.Function:
Identity function.
id x = x
This function might seem useless at first glance, but it can be very useful in a higher order context.
Examples
>>>length $ filter id [True, True, False, True]3
>>>Just (Just 3) >>= idJust 3
>>>foldr id 0 [(^3), (*5), (+2)]1000
const x y always evaluates to x, ignoring its second argument.
const x = \_ -> x
This function might seem useless at first glance, but it can be very useful in a higher order context.
Examples
>>>const 42 "hello"42
>>>map (const 42) [0..3][42,42,42,42]
(.) :: (b -> c) -> (a -> b) -> a -> c infixr 9 #
Right to left function composition.
(f . g) x = f (g x)
f . id = f = id . f
Examples
>>>map ((*2) . length) [[], [0, 1, 2], [0]][0,6,2]
>>>foldr (.) id [(+1), (*3), (^3)] 225
>>>let (...) = (.).(.) in ((*2)...(+)) 5 1030
($) :: (a -> b) -> a -> b infixr 0 #
is the function application operator.($)
Applying to a function ($)f and an argument x gives the same result as applying f to x directly. The definition is akin to this:
($) :: (a -> b) -> a -> b ($) f x = f x
This is specialized from ida -> a to (a -> b) -> (a -> b) which by the associativity of (->)
is the same as (a -> b) -> a -> b.
On the face of it, this may appear pointless! But it's actually one of the most useful and important operators in Haskell.
The order of operations is very different between ($) and normal function application. Normal function application has precedence 10 - higher than any operator - and associates to the left. So these two definitions are equivalent:
expr = min 5 1 + 5 expr = ((min 5) 1) + 5
($) has precedence 0 (the lowest) and associates to the right, so these are equivalent:
expr = min 5 $ 1 + 5 expr = (min 5) (1 + 5)
Examples
A common use cases of ($) is to avoid parentheses in complex expressions.
For example, instead of using nested parentheses in the following Haskell function:
-- | Sum numbers in a string: strSum "100 5 -7" == 98 strSum ::String->IntstrSum s =sum(mapMaybereadMaybe(wordss))
we can deploy the function application operator:
-- | Sum numbers in a string: strSum "100 5 -7" == 98 strSum ::String->IntstrSum s =sum$mapMaybereadMaybe$wordss
($) is also used as a section (a partially applied operator), in order to indicate that we wish to apply some yet-unspecified function to a given value. For example, to apply the argument 5 to a list of functions:
applyFive :: [Int] applyFive = map ($ 5) [(+1), (2^)] >>> [6, 32]
Technical Remark (Representation Polymorphism)
($) is fully representation-polymorphic. This allows it to also be used with arguments of unlifted and even unboxed kinds, such as unboxed integers:
fastMod :: Int -> Int -> Int fastMod (I# x) (I# m) = I# $ remInt# x m
(&) :: a -> (a -> b) -> b infixl 1 #
& 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 $.
This is a version of , where flip idid is specialized from a -> a to (a -> b) -> (a -> b)
which by the associativity of (->) is (a -> b) -> a -> b.
flipping this yields a -> (a -> b) -> b which is the type signature of &
Examples
>>>5 & (+1) & show"6"
>>>sqrt $ [1 / n^2 | n <- [1..1000]] & sum & (*6)3.1406380562059946
@since base-4.8.0.0
flip :: (a -> b -> c) -> b -> a -> c #
takes its (first) two arguments in the reverse order of flip ff.
flip f x y = f y x
flip . flip = id
Examples
>>>flip (++) "hello" "world""worldhello"
>>>let (.>) = flip (.) in (+1) .> show $ 5"6"
is the least fixed point of the function fix ff,
i.e. the least defined x such that f x = x.
When f is strict, this means that because, by the definition of strictness,
f ⊥ = ⊥ and such the least defined fixed point of any strict function is ⊥.
Examples
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 5120
This uses the fact that Haskell’s let introduces recursive bindings. We can
rewrite this definition using fix,
Instead of making a recursive call, we introduce a dummy parameter rec;
when used within fix, this parameter then refers to fix’s argument, hence
the recursion is reintroduced.
>>>fix (\rec n -> if n <= 1 then 1 else n * rec (n-1)) 5120
Using fix, we can implement versions of repeat as
and fix . (:)cycle as fix . (++)
>>>take 10 $ fix (0:)[0,0,0,0,0,0,0,0,0,0]
>>>map (fix (\rec n -> if n < 2 then n else rec (n - 1) + rec (n - 2))) [1..10][1,1,2,3,5,8,13,21,34,55]
Implementation Details
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c infixl 0 #
runs the binary function on b u x yb on the results of applying
unary function u to two arguments x and y. From the opposite
perspective, it transforms two inputs and combines the outputs.
(op `on` f) x y = f x `op` f y
Examples
>>>sortBy (compare `on` length) [[0, 1, 2], [0, 1], [], [0]][[],[0],[0,1],[0,1,2]]
>>>((+) `on` length) [1, 2, 3] [-1]4
>>>((,) `on` (*2)) 2 3(4,6)
Algebraic properties
Miscellaneous functions
($!) :: (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.
The value of is bottom if seq a ba 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 does
not guarantee that seq a ba 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.
error :: HasCallStack => [Char] -> a #
error stops execution and displays an error message.
undefined :: HasCallStack => a #
Helper function to force an action to run in IO. Especially
useful for overly general contexts, like hspec tests.
Since: 0.1.3.0
List
Re-exported from Data.List:
(++) :: [a] -> [a] -> [a] infixr 5 #
(++) appends 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.
Performance considerations
This function takes linear time in the number of elements of the
first list. Thus it is better to associate repeated
applications of (++) to the right (which is the default behaviour):
xs ++ (ys ++ zs) or simply xs ++ ys ++ zs, but not (xs ++ ys) ++ zs.
For the same reason concat = foldr (++) []
has linear performance, while foldl (++) [] is prone
to quadratic slowdown
Examples
>>>[1, 2, 3] ++ [4, 5, 6][1,2,3,4,5,6]
>>>[] ++ [1, 2, 3][1,2,3]
>>>[3, 2, 1] ++ [][3,2,1]
break :: (a -> Bool) -> [a] -> ([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 p is equivalent to
and consequently to span (not . p)(,
even if takeWhile (not . p) xs, dropWhile (not . p) xs)p is _|_.
Laziness
>>>break undefined []([],[])
>>>fst (break (const True) undefined)*** Exception: Prelude.undefined
>>>fst (break (const True) (undefined : undefined))[]
>>>take 1 (fst (break (const False) (1 : undefined)))[1]
break produces the first component of the tuple lazily:
>>>take 10 (fst (break (const False) [1..]))[1,2,3,4,5,6,7,8,9,10]
Examples
>>>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],[])
drop n xs returns the suffix of xs
after the first n elements, or [] if n >= .length xs
It is an instance of the more general genericDrop,
in which n may be of any integral type.
Examples
>>>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]
filter :: (a -> Bool) -> [a] -> [a] #
\(\mathcal{O}(n)\). 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]
Examples
>>>filter odd [1, 2, 3][1,3]
>>>filter (\l -> length l > 3) ["Hello", ", ", "World", "!"]["Hello","World"]
>>>filter (/= 3) [1, 2, 3, 4, 3, 2, 1][1,2,4,2,1]
map :: (a -> b) -> [a] -> [b] #
\(\mathcal{O}(n)\). 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, ...]
this means that map id == id
Examples
>>>map (+1) [1, 2, 3][2,3,4]
>>>map id [1, 2, 3][1,2,3]
>>>map (\n -> 3 * n + 1) [1, 2, 3][4,7,10]
replicate :: Int -> 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.
Examples
>>>replicate 0 True[]
>>>replicate (-1) True[]
>>>replicate 4 True[True,True,True,True]
\(\mathcal{O}(n)\). reverse xs returns the elements of xs in reverse order.
xs must be finite.
Laziness
reverse is lazy in its elements.
>>>head (reverse [undefined, 1])1
>>>reverse (1 : 2 : undefined)*** Exception: Prelude.undefined
Examples
>>>reverse [][]
>>>reverse [42][42]
>>>reverse [2,5,7][7,5,2]
>>>reverse [1..]* Hangs forever *
span :: (a -> Bool) -> [a] -> ([a], [a]) #
span, applied to a predicate p and a list xs, returns a tuple where
first element is the longest prefix (possibly empty) of xs of elements that
satisfy p and second element is the remainder of the list:
span p xs is equivalent to (, even if takeWhile p xs, dropWhile p xs)p is _|_.
Laziness
>>>span undefined []([],[])>>>fst (span (const False) undefined)*** Exception: Prelude.undefined>>>fst (span (const False) (undefined : undefined))[]>>>take 1 (fst (span (const True) (1 : undefined)))[1]
span produces the first component of the tuple lazily:
>>>take 10 (fst (span (const True) [1..]))[1,2,3,4,5,6,7,8,9,10]
Examples
>>>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])
take n, applied to a list xs, returns the prefix of xs
of length n, or xs itself if n >= .length xs
It is an instance of the more general genericTake,
in which n may be of any integral type.
Laziness
>>>take 0 undefined[]>>>take 2 (1 : 2 : undefined)[1,2]
Examples
>>>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][]
takeWhile :: (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.
Laziness
>>>takeWhile (const False) undefined*** Exception: Prelude.undefined
>>>takeWhile (const False) (undefined : undefined)[]
>>>take 1 (takeWhile (const True) (1 : undefined))[1]
Examples
>>>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][]
zip :: [a] -> [b] -> [(a, b)] #
\(\mathcal{O}(\min(m,n))\). zip takes two lists and returns a list of
corresponding pairs.
zip is right-lazy:
>>>zip [] undefined[]>>>zip undefined []*** Exception: Prelude.undefined ...
zip is capable of list fusion, but it is restricted to its
first list argument and its resulting list.
Examples
>>>zip [1, 2, 3] ['a', 'b', 'c'][(1,'a'),(2,'b'),(3,'c')]
If one input list is shorter than the other, excess elements of the longer list are discarded, even if one of the lists is infinite:
>>>zip [1] ['a', 'b'][(1,'a')]
>>>zip [1, 2] ['a'][(1,'a')]
>>>zip [] [1..][]
>>>zip [1..] [][]
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] #
\(\mathcal{O}(\min(m,n))\). zipWith generalises zip by zipping with the
function given as the first argument, instead of a tupling function.
zipWith (,) xs ys == zip xs ys zipWith f [x1,x2,x3..] [y1,y2,y3..] == [f x1 y1, f x2 y2, f x3 y3..]
zipWith is right-lazy:
>>>let f = undefined>>>zipWith f [] undefined[]
zipWith is capable of list fusion, but it is restricted to its
first list argument and its resulting list.
Examples
String
Re-exported from Data.String:
fromString :: IsString a => String -> a #
Splits the argument into a list of lines stripped of their terminating
\n characters. The \n terminator is optional in a final non-empty
line of the argument string.
When the argument string is empty, or ends in a \n character, it can be
recovered by passing the result of lines to the unlines function.
Otherwise, unlines appends the missing terminating \n. This makes
unlines . lines idempotent:
(unlines . lines) . (unlines . lines) = (unlines . lines)
Examples
>>>lines "" -- empty input contains no lines[]
>>>lines "\n" -- single empty line[""]
>>>lines "one" -- single unterminated line["one"]
>>>lines "one\n" -- single non-empty line["one"]
>>>lines "one\n\n" -- second line is empty["one",""]
>>>lines "one\ntwo" -- second line is unterminated["one","two"]
>>>lines "one\ntwo\n" -- two non-empty lines["one","two"]
Show
Re-exported from Text.Show:
Read
Re-exported from Text.Read:
readMaybe :: Read a => String -> Maybe a #
Parse a string using the Read instance.
Succeeds if there is exactly one valid result.
>>>readMaybe "123" :: Maybe IntJust 123
>>>readMaybe "hello" :: Maybe IntNothing
@since base-4.6.0.0
NFData
Re-exported from Control.DeepSeq:
($!!) :: NFData a => (a -> b) -> a -> b infixr 0 #
the deep analogue of $!. In the expression f $!! x, x is
fully evaluated before the function f is applied to it.
Since: deepseq-1.2.0.0
rnf should reduce its argument to normal form (that is, fully
evaluate all sub-components), and then return ().
Generic NFData deriving
Starting with GHC 7.2, you can automatically derive instances
for types possessing a Generic instance.
Note: Generic1 can be auto-derived starting with GHC 7.4
{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics (Generic, Generic1)
import Control.DeepSeq
data Foo a = Foo a String
deriving (Eq, Generic, Generic1)
instance NFData a => NFData (Foo a)
instance NFData1 Foo
data Colour = Red | Green | Blue
deriving Generic
instance NFData ColourStarting with GHC 7.10, the example above can be written more
concisely by enabling the new DeriveAnyClass extension:
{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
import GHC.Generics (Generic)
import Control.DeepSeq
data Foo a = Foo a String
deriving (Eq, Generic, Generic1, NFData, NFData1)
data Colour = Red | Green | Blue
deriving (Generic, NFData)
Compatibility with previous deepseq versions
Prior to version 1.4.0.0, the default implementation of the rnf
method was defined as
rnfa =seqa ()
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 !_ = ()deepseq :: NFData a => a -> b -> 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.
Since: deepseq-1.1.0.0
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 hSince: deepseq-1.2.0.0
Void
Re-exported from Data.Void:
Since Void values logically don't exist, this witnesses the
logical reasoning tool of "ex falso quodlibet".
>>>let x :: Either Void Int; x = Right 5>>>:{case x of Right r -> r Left l -> absurd l :} 5
@since base-4.8.0.0
Reader
Re-exported from Control.Monad.Reader:
lift :: (MonadTrans t, Monad m) => m a -> t m a #
Lift a computation from the argument monad to the constructed monad.
ask :: MonadReader r m => m r #
Retrieves the monad environment.
Arguments
| :: MonadReader r m | |
| => (r -> a) | The selector function to apply to the environment. |
| -> m a |
Retrieves a function of the current environment.
Arguments
| :: MonadReader r m | |
| => (r -> r) | The function to modify the environment. |
| -> m a |
|
| -> m a |
Executes a computation in a modified environment.
Arguments
| :: Reader r a | A |
| -> r | An initial environment. |
| -> a |
Runs a Reader and extracts the final value from it.
(The inverse of reader.)
runReaderT :: ReaderT r m a -> r -> m a #
ByteString
Helper synonyms for converting bewteen lazy and strict ByteStrings
toStrictBytes :: LByteString -> ByteString #
ShortByteString
Re-exported from Data.ByteString.Short:
toShort :: ByteString -> ShortByteString #
O(n). Convert a ByteString into a ShortByteString.
This makes a copy, so does not retain the input string.
fromShort :: ShortByteString -> ByteString #
O(n). Convert a ShortByteString into a ByteString.
Text
decodeUtf8Lenient :: ByteString -> Text #
Re-exported from Data.Text.Encoding:
decodeUtf8' :: ByteString -> Either UnicodeException 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.
decodeUtf8With :: OnDecodeError -> ByteString -> Text #
Decode a ByteString containing UTF-8 encoded text.
Surrogate code points in replacement character returned by OnDecodeError
will be automatically remapped to the replacement char U+FFFD.
encodeUtf8 :: Text -> ByteString #
Encode text using UTF-8 encoding.
encodeUtf8Builder :: Text -> Builder #
Encode text to a ByteString Builder using UTF-8 encoding.
Since: text-1.1.0.0
lenientDecode :: OnDecodeError #
Replace an invalid input byte with the Unicode replacement character U+FFFD.
PrimMonad
Re-exported from Control.Monad.Primitive:
primitive :: PrimMonad m => (State# (PrimState m) -> (# State# (PrimState m), a #)) -> m a #
Execute a primitive operation.
Re-exported from Control.Monad.ST: