Safe Haskell | None |
---|---|
Language | Haskell2010 |
Synopsis
- module RIO.Prelude.Types
- (||) :: 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
- 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
- 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
- (>>=) :: 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 ()
- fail :: MonadFail m => String -> m a
- 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 ()
- 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
- first :: Arrow a => a b c -> a (b, d) (c, d)
- second :: Arrow a => a b c -> a (d, b) (d, c)
- (&&&) :: 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')
- (>>>) :: 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
Documentation
module RIO.Prelude.Types
Bool
Re-exported from Data.Bool:
Case analysis for the Bool
type.
evaluates to bool
x y px
when p
is False
, and evaluates to y
when p
is True
.
This is equivalent to if p then y else x
; that is, one can
think of it as an if-then-else construct with its arguments
reordered.
Examples
Basic usage:
>>>
bool "foo" "bar" True
"bar">>>
bool "foo" "bar" False
"foo"
Confirm that
and bool
x y pif p then y else x
are
equivalent:
>>>
let p = True; x = "bar"; y = "foo"
>>>
bool x y p == if p then y else x
True>>>
let p = False
>>>
bool x y p == if p then y else x
True
Since: base-4.7.0.0
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 Nothing
False
Read an integer from a string using readMaybe
. If we succeed,
return twice the integer; that is, apply (*2)
to it. If instead
we fail to parse an integer, return 0
by default:
>>>
import Text.Read ( readMaybe )
>>>
maybe 0 (*2) (readMaybe "5")
10>>>
maybe 0 (*2) (readMaybe "")
0
Apply show
to a Maybe Int
. If we have Just n
, we want to show
the underlying Int
n
. But if we have Nothing
, we return the
empty string instead of (for example) "Nothing":
>>>
maybe "" show (Just 5)
"5">>>
maybe "" show Nothing
""
fromMaybe :: a -> Maybe a -> a #
The fromMaybe
function takes a default value and and Maybe
value. If the Maybe
is Nothing
, it returns the default values;
otherwise, it returns the value contained in the Maybe
.
Examples
Basic usage:
>>>
fromMaybe "" (Just "Hello, World!")
"Hello, World!"
>>>
fromMaybe "" Nothing
""
Read an integer from a string using readMaybe
. If we fail to
parse an integer, we want to return 0
by default:
>>>
import Text.Read ( readMaybe )
>>>
fromMaybe 0 (readMaybe "5")
5>>>
fromMaybe 0 (readMaybe "")
0
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 not given Nothing
.
Examples
Basic usage:
>>>
maybeToList (Just 7)
[7]
>>>
maybeToList Nothing
[]
One can use maybeToList
to avoid pattern matching when combined
with a function that (safely) works on lists:
>>>
import Text.Read ( readMaybe )
>>>
sum $ maybeToList (readMaybe "3")
3>>>
sum $ maybeToList (readMaybe "")
0
catMaybes :: [Maybe a] -> [a] #
The catMaybes
function takes a list of Maybe
s and returns
a list of all the Just
values.
Examples
Basic usage:
>>>
catMaybes [Just 1, Nothing, Just 3]
[1,3]
When constructing a list of Maybe
values, catMaybes
can be used
to return all of the "success" results (if the list is the result
of a map
, then mapMaybe
would be more appropriate):
>>>
import Text.Read ( readMaybe )
>>>
[readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
[Just 1,Nothing,Just 3]>>>
catMaybes $ [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
[1,3]
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 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]
forMaybeA :: Applicative f => [a] -> (a -> f (Maybe b)) -> f [b] Source #
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
Int
Left
constructor and another using the Right
constructor. Then
we apply "either" the length
function (if we have a String
)
or the "times-two" function (if we have an Int
):
>>>
let s = Left "foo" :: Either String Int
>>>
let n = Right 3 :: Either String Int
>>>
either length (*2) s
3>>>
either length (*2) n
6
isLeft :: Either a b -> Bool #
Return True
if the given value is a Left
-value, False
otherwise.
Examples
Basic usage:
>>>
isLeft (Left "foo")
True>>>
isLeft (Right 3)
False
Assuming a Left
value signifies some sort of error, we can use
isLeft
to write a very simple error-reporting function that does
absolutely nothing in the case of success, and outputs "ERROR" if
any error occurred.
This example shows how isLeft
might be used to avoid pattern
matching when one does not care about the value contained in the
constructor:
>>>
import Control.Monad ( when )
>>>
let report e = when (isLeft e) $ putStrLn "ERROR"
>>>
report (Right 1)
>>>
report (Left "parse error")
ERROR
Since: base-4.7.0.0
isRight :: Either a b -> Bool #
Return True
if the given value is a Right
-value, False
otherwise.
Examples
Basic usage:
>>>
isRight (Left "foo")
False>>>
isRight (Right 3)
True
Assuming a Left
value signifies some sort of error, we can use
isRight
to write a very simple reporting function that only
outputs "SUCCESS" when a computation has succeeded.
This example shows how isRight
might be used to avoid pattern
matching when one does not care about the value contained in the
constructor:
>>>
import Control.Monad ( when )
>>>
let report e = when (isRight e) $ putStrLn "SUCCESS"
>>>
report (Left "parse error")
>>>
report (Right 1)
SUCCESS
Since: base-4.7.0.0
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:
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) ...
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 #
the rational equivalent of its real argument with full precision
Integral
Re-exported from Prelude:
rem :: Integral a => a -> a -> a infixl 7 #
integer remainder, satisfying
(x `quot` y)*y + (x `rem` y) == x
mod :: Integral a => a -> a -> a infixl 7 #
integer modulus, satisfying
(x `div` y)*y + (x `mod` y) == x
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 minBound
0
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
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
Integer
fromRational
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
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:
n
is an integral number with the same sign asx
; andf
is 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 #
Swap 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:
Monoid
Re-exported from Data.Monoid:
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.mappend
= '(<>)'
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.
Functor
Re-exported from Data.Functor:
(<$>) :: 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
String
show
:
>>>
show <$> Nothing
Nothing>>>
show <$> Just 3
Just "3"
Convert from an
to an Either
Int
Int
Either
Int
String
using show
:
>>>
show <$> Left 17
Left 17>>>
show <$> Right 17
Right "17"
Double each element of a list:
>>>
(*2) <$> [1,2,3]
[2,4,6]
Apply even
to the second element of a pair:
>>>
even <$> (2,2)
(2,True)
($>) :: Functor f => f a -> b -> f b infixl 4 #
Flipped version of <$
.
Examples
Replace the contents of a
with a constant Maybe
Int
String
:
>>>
Nothing $> "foo"
Nothing>>>
Just 90210 $> "foo"
Just "foo"
Replace the contents of an
with a constant
Either
Int
Int
String
, resulting in an
:Either
Int
String
>>>
Left 8675309 $> "foo"
Left 8675309>>>
Right 8675309 $> "foo"
Right "foo"
Replace each element of a list with a constant String
:
>>>
[1,2,3] $> "foo"
["foo","foo","foo"]
Replace the second element of a pair with a constant String
:
>>>
(1,2) $> "foo"
(1,"foo")
Since: base-4.7.0.0
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 Nothing
Nothing>>>
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.
(<*>) :: 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.
(<*) :: 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.
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 #
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,
Handle
s, 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
traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f () #
Map each element of a structure to an action, evaluate these
actions from left to right, and ignore the results. For a version
that doesn't ignore the results see traverse
.
for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f () #
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
.
filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a] #
This generalizes the list-based filter
function.
replicateM_ :: Applicative m => Int -> m a -> m () #
Like replicateM
, but discards the result.
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:
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.
Examples
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.
(>>) :: Monad m => m a -> m b -> m b infixl 1 #
Sequentially compose two actions, discarding any value produced by the first, like sequencing operators (such as the semicolon) in imperative languages.
(=<<) :: Monad m => (a -> m b) -> m a -> m b infixr 1 #
Same as >>=
, but with the arguments interchanged.
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 #
Left-to-right composition of Kleisli arrows.
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. For example,
liftM2 (+) [0,1] [0,2] = [0,2,1,3] liftM2 (+) (Just 1) Nothing = Nothing
whenM :: Monad m => m Bool -> m () -> m () Source #
Run the second value if the first value returns True
unlessM :: Monad m => m Bool -> m () -> m () Source #
Run the second value if the first value returns False
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
.
As of base 4.8.0.0, sequence_
is just sequenceA_
, specialized
to Monad
.
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.
MonadFail
Re-exported from Control.Monad.Fail:
Foldable
Re-exported from Data.Foldable:
foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b #
Right-associative fold of a structure.
In the case of lists, foldr
, when applied to a binary operator, a
starting value (typically the right-identity of the operator), and a
list, reduces the list using the binary operator, from right to left:
foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)
Note that, since the head of the resulting expression is produced by
an application of the operator to the first element of the list,
foldr
can produce a terminating expression from an infinite list.
For a general Foldable
structure this should be semantically identical
to,
foldr f z =foldr
f z .toList
foldl' :: Foldable t => (b -> a -> b) -> b -> t a -> b #
Left-associative fold of a structure but with strict application of the operator.
This ensures that each step of the fold is forced to weak head normal
form before being applied, avoiding the collection of thunks that would
otherwise occur. This is often what you want to strictly reduce a finite
list to a single, monolithic result (e.g. length
).
For a general Foldable
structure this should be semantically identical
to,
foldl f z =foldl'
f z .toList
foldMap :: (Foldable t, Monoid m) => (a -> m) -> t a -> m #
Map each element of the structure to a monoid, and combine the results.
foldMapM :: (Monad m, Monoid w, Foldable t) => (a -> m w) -> t a -> m w Source #
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
null :: Foldable t => t a -> Bool #
Test whether the structure is empty. The default implementation is optimized for structures that are similar to cons-lists, because there is no general way to do better.
length :: Foldable t => t a -> Int #
Returns the size/length of a finite structure as an Int
. The
default implementation is optimized for structures that are similar to
cons-lists, because there is no general way to do better.
sum :: (Foldable t, Num a) => t a -> a #
The sum
function computes the sum of the numbers of a structure.
product :: (Foldable t, Num a) => t a -> a #
The product
function computes the product of the numbers of a
structure.
all :: Foldable t => (a -> Bool) -> t a -> Bool #
Determines whether all elements of the structure satisfy the predicate.
any :: Foldable t => (a -> Bool) -> t a -> Bool #
Determines whether any element of the structure satisfies the predicate.
concat :: Foldable t => t [a] -> [a] #
The concatenation of all the elements of a container of lists.
concatMap :: Foldable t => (a -> [b]) -> t a -> [b] #
Map a function over all the elements of a container and concatenate the resulting lists.
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_
.
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_
.
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_
.
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_
.
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.
many :: Alternative f => f a -> f [a] #
Zero or more.
optional :: Alternative f => f a -> f (Maybe a) #
One or none.
asum :: (Foldable t, Alternative f) => t (f a) -> f a #
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 signaling an error in
an error monad and conditionally rejecting the current choice in an
Alternative
-based parser.
As an example of signaling an error in the error monad Maybe
,
consider a safe division function safeDiv x y
that returns
Nothing
when the denominator y
is zero and
otherwise. For example:Just
(x `div`
y)
>>> safeDiv 4 0 Nothing >>> safeDiv 4 2 Just 2
A definition of safeDiv
using guards, but not guard
:
safeDiv :: Int -> Int -> Maybe Int safeDiv x y | y /= 0 = Just (x `div` y) | otherwise = Nothing
A definition of safeDiv
using guard
and Monad
do
-notation:
safeDiv :: Int -> Int -> Maybe Int safeDiv x y = do guard (y /= 0) return (x `div` y)
when :: Applicative f => Bool -> f () -> f () #
Conditional execution of Applicative
expressions. For example,
when debug (putStrLn "Debugging")
will output the string Debugging
if the Boolean value debug
is True
, and otherwise do nothing.
unless :: Applicative f => Bool -> f () -> f () #
The reverse of when
.
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:
first :: Arrow a => a b c -> a (b, d) (c, d) #
Send the first component of the input through the argument arrow, and copy the rest unchanged to the output.
second :: Arrow a => a b c -> a (d, b) (d, c) #
A mirror image of first
.
The default definition may be overridden with a more efficient version if desired.
(&&&) :: Arrow a => a b c -> a b c' -> a b (c, c') infixr 3 #
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.
Function
Re-exported from Data.Function:
const x
is a unary function which evaluates to x
for all inputs.
>>>
const 42 "hello"
42
>>>
map (const 42) [0..3]
[42,42,42,42]
($) :: (a -> b) -> a -> b infixr 0 #
Application operator. This operator is redundant, since ordinary
application (f x)
means the same as (f
. However, $
x)$
has
low, right-associative binding precedence, so it sometimes allows
parentheses to be omitted; for example:
f $ g $ h x = f (g (h x))
It is also useful in higher-order situations, such as
,
or map
($
0) xs
.zipWith
($
) fs xs
Note that ($)
is levity-polymorphic in its result type, so that
foo $ True where foo :: Bool -> Int#
is well-typed
flip :: (a -> b -> c) -> b -> a -> c #
takes its (first) two arguments in the reverse order of flip
ff
.
>>>
flip (++) "hello" "world"
"worldhello"
is the least fixed point of the function fix
ff
,
i.e. the least defined x
such that f x = x
.
For example, we can write the factorial function using direct recursion as
>>>
let fac n = if n <= 1 then 1 else n * fac (n-1) in fac 5
120
This uses the fact that Haskell’s let
introduces recursive bindings. We can
rewrite this definition using fix
,
>>>
fix (\rec n -> if n <= 1 then 1 else n * rec (n-1)) 5
120
Instead of making a recursive call, we introduce a dummy parameter rec
;
when used within fix
, this parameter then refers to fix'
argument, hence
the recursion is reintroduced.
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 seq a b
is bottom if a
is bottom, and
otherwise equal to b
. In other words, it evaluates the first
argument a
to weak head normal form (WHNF). seq
is usually
introduced to improve performance by avoiding unneeded laziness.
A note on evaluation order: the expression seq a b
does
not guarantee that a
will be evaluated before b
.
The only guarantee given by seq
is that the both a
and b
will be evaluated before seq
returns a value.
In particular, this means that b
may be evaluated before
a
. If you need to guarantee a specific order of evaluation,
you must use the function pseq
from the "parallel" package.
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 #
Append two lists, i.e.,
[x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn] [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]
If the first list is not finite, the result is the first list.
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 (> 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
drop 6 "Hello World!" == "World!" drop 3 [1,2,3,4,5] == [4,5] drop 3 [1,2] == [] drop 3 [] == [] drop (-1) [1,2] == [1,2] drop 0 [1,2] == [1,2]
It is an instance of the more general genericDrop
,
in which n
may be of any integral type.
filter :: (a -> Bool) -> [a] -> [a] #
filter
, applied to a predicate and a list, returns the list of
those elements that satisfy the predicate; i.e.,
filter p xs = [ x | x <- xs, p x]
lookup :: Eq a => a -> [(a, b)] -> Maybe b #
lookup
key assocs
looks up a key in an association list.
map :: (a -> b) -> [a] -> [b] #
map
f xs
is the list obtained by applying f
to each element
of xs
, i.e.,
map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn] map f [x1, x2, ...] == [f x1, f x2, ...]
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.
span :: (a -> Bool) -> [a] -> ([a], [a]) #
span
, applied to a predicate p
and a list xs
, returns a tuple where
first element is longest prefix (possibly empty) of xs
of elements that
satisfy p
and second element is the remainder of the list:
span (< 3) [1,2,3,4,1,2,3,4] == ([1,2],[3,4,1,2,3,4]) span (< 9) [1,2,3] == ([1,2,3],[]) span (< 0) [1,2,3] == ([],[1,2,3])
take
n
, applied to a list xs
, returns the prefix of xs
of length n
, or xs
itself if n >
:length
xs
take 5 "Hello World!" == "Hello" take 3 [1,2,3,4,5] == [1,2,3] take 3 [1,2] == [1,2] take 3 [] == [] take (-1) [1,2] == [] take 0 [1,2] == []
It is an instance of the more general genericTake
,
in which n
may be of any integral type.
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
:
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] == []
String
Re-exported from Data.String:
fromString :: IsString a => String -> a #
lines
breaks a string up into a list of strings at newline
characters. The resulting strings do not contain newlines.
Note that after splitting the string at newline characters, the last part of the string is considered a line even if it doesn't end with a newline. For example,
>>>
lines ""
[]
>>>
lines "\n"
[""]
>>>
lines "one"
["one"]
>>>
lines "one\n"
["one"]
>>>
lines "one\n\n"
["one",""]
>>>
lines "one\ntwo"
["one","two"]
>>>
lines "one\ntwo\n"
["one","two"]
Thus
contains at least as many elements as newlines in lines
ss
.
words
breaks a string up into a list of words, which were delimited
by white space.
>>>
words "Lorem ipsum\ndolor"
["Lorem","ipsum","dolor"]
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 Int
Just 123
>>>
readMaybe "hello" :: Maybe Int
Nothing
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 Colour
Starting with GHC 7.10, the example above can be written more
concisely by enabling the new DeriveAnyClass
extension:
{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-} import GHC.Generics (Generic) import Control.DeepSeq data Foo a = Foo a String deriving (Eq, Generic, Generic1, NFData, NFData1) data Colour = Red | Green | Blue deriving (Generic, NFData)
Compatibility with previous deepseq
versions
Prior to version 1.4.0.0, the default implementation of the rnf
method was defined as
rnf
a =seq
a ()
However, starting with deepseq-1.4.0.0
, the default
implementation is based on DefaultSignatures
allowing for
more accurate auto-derived NFData
instances. If you need the
previously used exact default rnf
method implementation
semantics, use
instance NFData Colour where rnf x = seq x ()
or alternatively
instance NFData Colour where rnf = rwhnf
or
{-# LANGUAGE BangPatterns #-} instance NFData Colour where rnf !_ = ()
deepseq :: NFData a => a -> b -> b #
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 h
Since: 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.
:: MonadReader r m | |
=> (r -> a) | The selector function to apply to the environment. |
-> m a |
Retrieves a function of the current environment.
:: MonadReader r m | |
=> (r -> r) | The function to modify the environment. |
-> m a |
|
-> m a |
Executes a computation in a modified environment.
:: 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 ByteString
s
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 Source #
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.
NOTE: The replacement character returned by OnDecodeError
MUST be within the BMP plane; surrogate code points will
automatically be remapped to the replacement char U+FFFD
(since 0.11.3.0), whereas code points beyond the BMP will throw an
error
(since 1.2.3.1); For earlier versions of text
using
those unsupported code points would result in undefined behavior.
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: