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.
vvalueeither :: (a -> c) -> (b -> c) -> Eitherab -> c
Case analysis for the Either type.
If the value is Left a, apply the first function to a;
if it is Right b, apply the second function to b.
Examples
We create two values of type EitherStringInt, one using the
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):
Example4 expressions
>>> let s = Left "foo" :: Either String Int>>> let n = Right 3 :: Either String Int>>> either length (*2) s3>>> either length (*2) n6
This provides an Iso for the lens package that witnesses the
isomorphism between Procompose p (Procompose q r) a b and
Procompose (Procompose p q) r a b, which arises because
Prof is only a bicategory, rather than a strict 2-category.
The group function takes a list and returns a list of lists such
that the concatenation of the result is equal to the argument. Moreover,
each sublist in the result is non-empty, all elements are equal to the
first one, and consecutive equal elements of the input end up in the
same element of the output list.
group is a special case of groupBy, which allows the programmer to supply
their own equality test.
It's often preferable to use Data.List.NonEmpty.group,
which provides type-level guarantees of non-emptiness of inner lists.
A common idiom to squash repeating elements maphead.group
is better served by
mapData.List.NonEmpty.head.Data.List.NonEmpty.group
because it avoids partial functions.
Examples
Example1 expression
>>> group "Mississippi"["M","i","ss","i","ss","i","pp","i"]
Introduces a recursive binding to the continuation.
Due to the use of callCC, calling the continuation will interrupt execution
of the current block creating an effect similar to goto/setjmp in C.
Allow asynchronous exceptions to be raised even inside mask, making
the operation interruptible (see the discussion of "Interruptible operations"
in Control.Exception).
Unicode General Categories (column 2 of the UnicodeData table) in
the order they are listed in the Unicode standard (the Unicode
Character Database, in particular).
>>> import GHC.Internal.Data.Ix ( index )>>> index (OtherLetter,Control) FinalQuote12>>> index (OtherLetter,Control) Format*** Exception: Error in array index
sequence computations and combine their results (<*> and liftA2).
A minimal complete definition must include implementations of pure
and of either <*> or liftA2. If it defines both, then they must behave
the same as their default definitions:
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.
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.
Example1 expression
>>> Just 2 *> Just 3Just 3
Example1 expression
>>> Nothing *> Just 3Nothing
Of course a more interesting use case would be to have effectful
computations instead of just returning pure values.
Example4 expressions
>>> 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","")]
These laws are directly analogous to the laws for monads
and perhaps can be made clearer by viewing them as laws stating
that Cokleisli composition must be associative, and has extract for
a unit:
An MVar (pronounced "em-var") is a synchronising variable, used
for communication between concurrent threads. It can be thought of
as a box, which may be empty or full.
Instances3NFData1, Eq, NFData
NFData1MVarDefined in deepseq-1.5.0.0 · Control.DeepSeq
Eq (MVara)Defined in ghc-internal-9.1003.0 · GHC.Internal.MVar
Compares the underlying pointers.
NFData (MVara)Defined in deepseq-1.5.0.0 · Control.DeepSeq
NOTE: Only strict in the reference and not the referenced value.
QSem is a quantity semaphore in which the resource is acquired
and released in units of one. It provides guaranteed FIFO ordering
for satisfying blocked waitQSem calls.
QSemN is a quantity semaphore in which the resource is acquired
and released in arbitrary amounts. It provides guaranteed FIFO ordering
for satisfying blocked waitQSemN calls.
Any type that you wish to throw or catch as an exception must be an
instance of the Exception class. The simplest case is a new exception
type directly below the root:
data MyException = ThisException | ThatException
deriving Show
instance Exception MyException
The default method definitions in the Exception class do what we need
in this case. You can now throw and catch ThisException and
ThatException as exceptions:
*Main> throw ThisException `catch` \e -> putStrLn ("Caught " ++ show (e :: MyException))
Caught ThisException
In more complicated examples, you may wish to define a whole hierarchy
of exceptions:
---------------------------------------------------------------------
-- Make the root exception type for all the exceptions in a compiler
data SomeCompilerException = forall e . Exception e => SomeCompilerException e
instance Show SomeCompilerException where
show (SomeCompilerException e) = show e
instance Exception SomeCompilerException
compilerExceptionToException :: Exception e => e -> SomeException
compilerExceptionToException = toException . SomeCompilerException
compilerExceptionFromException :: Exception e => SomeException -> Maybe e
compilerExceptionFromException x = do
SomeCompilerException a <- fromException x
cast a
---------------------------------------------------------------------
-- Make a subhierarchy for exceptions in the frontend of the compiler
data SomeFrontendException = forall e . Exception e => SomeFrontendException e
instance Show SomeFrontendException where
show (SomeFrontendException e) = show e
instance Exception SomeFrontendException where
toException = compilerExceptionToException
fromException = compilerExceptionFromException
frontendExceptionToException :: Exception e => e -> SomeException
frontendExceptionToException = toException . SomeFrontendException
frontendExceptionFromException :: Exception e => SomeException -> Maybe e
frontendExceptionFromException x = do
SomeFrontendException a <- fromException x
cast a
---------------------------------------------------------------------
-- Make an exception type for a particular frontend compiler exception
data MismatchedParentheses = MismatchedParentheses
deriving Show
instance Exception MismatchedParentheses where
toException = frontendExceptionToException
fromException = frontendExceptionFromException
We can now catch a MismatchedParentheses exception as
MismatchedParentheses, SomeFrontendException or
SomeCompilerException, but not other types, e.g. IOException:
*Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: MismatchedParentheses))
Caught MismatchedParentheses
*Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeFrontendException))
Caught MismatchedParentheses
*Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeCompilerException))
Caught MismatchedParentheses
*Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: IOException))
*** Exception: MismatchedParentheses
The Monad class defines the basic operations over a monad,
a concept from a branch of mathematics known as category theory.
From the perspective of a Haskell programmer, however, it is best to
think of a monad as an abstract datatype of actions.
Haskell's do expressions provide a convenient syntax for writing
monadic expressions.
Sequentially compose two actions, discarding any value produced
by the first, like sequencing operators (such as the semicolon)
in imperative languages.
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.
Instances112Monad, …
MonadComplexDefined in base-4.20.2.0 · Data.Complex
MonadFirstDefined in base-4.20.2.0 · Data.Semigroup
MonadLastDefined in base-4.20.2.0 · Data.Semigroup
Continuation monad.
Cont r a is a CPS ("continuation-passing style") computation that produces an
intermediate result of type a within a CPS computation whose final result type
is r.
The return function simply creates a continuation which passes the value on.
The >>= operator adds the bound function into the continuation chain.
The strict ST monad.
The ST monad allows for destructive updates, but is escapable (unlike IO).
A computation of type ST s a returns a value of type a, and
execute in "thread" s. The s parameter is either
an uninstantiated type variable (inside invocations of runST), or
Computations are either exceptions or normal values.
The return function returns a normal value, while >>= exits on
the first exception. For a variant that continues after an error
and collects all the errors, see Errors.
The Maybe type encapsulates an optional value. A value of type
Maybe a either contains a value of type a (represented as Just a),
or it is empty (represented as Nothing). Using Maybe is a good way to
deal with errors or exceptional cases without resorting to drastic
measures such as error.
The Maybe type is also a monad. It is a simple kind of error
monad, where all errors are represented by Nothing. A richer
error monad can be built using the Either type.
Semigroupa => Monoid (Maybea)Defined in ghc-internal-9.1003.0 · GHC.Internal.Base
Lift a semigroup into Maybe forming a Monoid according to
http://en.wikipedia.org/wiki/Monoid: "Any semigroup S may be
turned into a monoid simply by adjoining an element e not in S
and defining e*e = e and e*s = s = s*e for all s ∈ S."
Since 4.11.0: constraint on inner a value generalised from
Monoid to Semigroup.
SingKinda => SingKind (Maybea)Defined in ghc-internal-9.1003.0 · GHC.Internal.Generics
NFDataa => NFData (Maybea)Defined in deepseq-1.5.0.0 · Control.DeepSeq
Prettya => Pretty (Maybea)Defined in pretty-1.1.3.6 · Text.PrettyPrint.Annotated.HughesPJClass
Prettya => Pretty (Maybea)Defined in pretty-1.1.3.6 · Text.PrettyPrint.HughesPJClass
Finitea => Finite (Maybea)Defined in random-1.2.1.3 · System.Random.GFinite
Binarya => Binary (Maybea)Defined in binary-0.8.9.3 · Data.Binary.Class
Selective applicative functors. You can think of select as a selective
function application: when given a value of type Lefta, you must apply
the given function, but when given a Rightb, you may skip the
function and associated effects, and simply return the b.
Note that it is not a requirement for selective functors to skip unnecessary
effects. It may be counterintuitive, but this makes them more useful. Why?
Typically, when executing a selective computation, you would want to skip the
effects (saving work); but on the other hand, if your goal is to statically
analyse a given selective computation and extract the set of all possible
effects (without actually executing them), then you do not want to skip any
effects, because that defeats the purpose of static analysis.
The type signature of select is reminiscent of both <*> and >>=, and
indeed a selective functor is in some sense a composition of an applicative
functor and the Either monad.
Laws:
Identity:
x <*? pure id = either id id <$> x
Distributivity; note that y and z have the same type f (a -> b):
pure x <*? (y *> z) = (pure x <*? y) *> (pure x <*? z)
Associativity:
x <*? (y <*? z) = (f <$> x) <*? (g <$> y) <*? (h <$> z)
where
f x = Right <$> x
g y = a -> bimap (,a) ($a) y
h z = uncurry z
Monadic select (for selective functors that are also monads):
select = selectM
There are also a few useful theorems:
Apply a pure function to the result:
f <$> select x y = select (fmap f <$> x) (fmap f <$> y)
Apply a pure function to the Left case of the first argument:
The Data class comprehends a fundamental primitive gfoldl for
folding over constructor applications, say terms. This primitive can
be instantiated in several ways to map over the immediate subterms
of a term; see the gmap combinators later in this class. Indeed, a
generic programmer does not necessarily need to use the ingenious gfoldl
primitive but rather the intuitive gmap combinators. The gfoldl
primitive is completed by means to query top-level constructors, to
turn constructor representations into proper terms, and to list all
possible datatype constructors. This completion allows us to serve
generic programming scenarios like read, show, equality, term generation.
The combinators gmapT, gmapQ, gmapM, etc are all provided with
default definitions in terms of gfoldl, leaving open the opportunity
to provide datatype-specific definitions.
(The inclusion of the gmap combinators as members of class Data
allows the programmer or the compiler to derive specialised, and maybe
more efficient code per datatype. Note: gfoldl is more higher-order
than the gmap combinators. This is subject to ongoing benchmarking
experiments. It might turn out that the gmap combinators will be
moved out of the class Data.)
Conceptually, the definition of the gmap combinators in terms of the
primitive gfoldl requires the identification of the gfoldl function
arguments. Technically, we also need to identify the type constructor
c for the construction of the result type from the folded term type.
In the definition of gmapQx combinators, we use phantom type
constructors for the c in the type of gfoldl because the result type
of a query does not involve the (polymorphic) type of the term argument.
In the definition of gmapQl we simply use the plain constant type
constructor because gfoldl is left-associative anyway and so it is
readily suited to fold a left-associative binary operation over the
immediate subterms. In the definition of gmapQr, extra effort is
needed. We use a higher-order accumulation trick to mediate between
left-associative constructor application vs. right-associative binary
operation (e.g., (:)). When the query is meant to compute a value
of type r, then the result type within generic folding is r -> r.
So the result of folding is a function to which we finally pass the
right unit.
With the -XDeriveDataTypeable option, GHC can generate instances of the
Data class automatically. For example, given the declaration
data T a b = C1 a b | C2 deriving (Typeable, Data)
GHC will generate an instance that is equivalent to
instance (Data a, Data b) => Data (T a b) where
gfoldl k z (C1 a b) = z C1 `k` a `k` b
gfoldl k z C2 = z C2
gunfold k z c = case constrIndex c of
1 -> k (k (z C1))
2 -> z C2
toConstr (C1 _ _) = con_C1
toConstr C2 = con_C2
dataTypeOf _ = ty_T
con_C1 = mkConstr ty_T "C1" [] Prefix
con_C2 = mkConstr ty_T "C2" [] Prefix
ty_T = mkDataType "Module.T" [con_C1, con_C2]
This is suitable for datatypes that are exported transparently.
Methods
gfoldl :: (foralldb. Datad => c (d -> b) -> d -> cb) -> (forallg. g -> cg) -> a -> ca
Left-associative fold operation for constructor applications.
The type of gfoldl is a headache, but operationally it is a simple
generalisation of a list fold.
The default definition for gfoldl is constid, which is
suitable for abstract datatypes with no substructures.
gunfold :: (forallbr. Datab => c (b -> r) -> cr) -> (forallr. r -> cr) -> Constr -> ca
Obtaining the constructor from a given datum.
For proper terms, this is meant to be the top-level constructor.
Primitive datatypes are here viewed as potentially infinite sets of
values (i.e., constructors).
A generic transformation that maps over the immediate subterms
The default definition instantiates the type constructor c in the
type of gfoldl to an identity datatype constructor, using the
isomorphism pair as injection and projection.
gmapQl :: (r -> r' -> r) -> r -> (foralld. Datad => d -> r') -> a -> r
A generic query with a left-associative binary operator
gmapQr :: (r' -> r -> r) -> r -> (foralld. Datad => d -> r') -> a -> r
A generic query with a right-associative binary operator
A generic query that processes the immediate subterms and returns a list
of results. The list is given in the same order as originally specified
in the declaration of the data constructors.
gmapQi :: Int -> (foralld. Datad => d -> u) -> a -> u
A generic query that processes one child by index (zero-based)
gmapM :: Monadm => (foralld. Datad => d -> md) -> a -> ma
A generic monadic transformation that maps over the immediate subterms
The default definition instantiates the type constructor c in
the type of gfoldl to the monad datatype constructor, defining
injection and projection using return and >>=.
DataSpecificityDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
DataStmtDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
DataTyLitDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
DataTySynEqnDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
DataTypeDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
DataTypeFamilyHeadDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
DataTextDefined in text-2.1.3 · Data.Text · orphan
This instance preserves data abstraction at the cost of inefficiency.
We omit reflection services for the sake of data abstraction.
This instance was created by copying the updated behavior of
Data.Set.Set and Data.Map.Data.Map.Map. If you
feel a mistake has been made, please feel free to submit
improvements.
A bifunctor is a type constructor that takes
two type arguments and is a functor in both arguments. That
is, unlike with Functor, a type constructor such as Either
does not need to be partially applied for a Bifunctor
instance, and the methods in this class permit mapping
functions over the Left value or the Right value,
or both at the same time.
Formally, the class Bifunctor represents a bifunctor
from Hask -> Hask.
Intuitively it is a bifunctor where both the first and second
arguments are covariant.
The class definition of a Bifunctorp uses the
QuantifiedConstraints
language extension to quantify over the first type
argument a in its context. The context requires that p a
must be a Functor for all a. In other words a partially
applied Bifunctor must be a Functor. This makes Functor a
superclass of Bifunctor such that a function with a
Bifunctor constraint may use fmap in its implementation.
Functor has been a quantified superclass of
Bifunctor since base-4.18.0.0.
The laws imply that .> and <. really ignore their
left and right results, respectively, and really
return their right and left results, respectively.
Specifically,
shift x i shifts x left by i bits if i is positive,
or right by -i bits otherwise.
Right shifts perform sign extension on signed number types;
i.e. they fill the top bits with 1 if the x is negative
and with 0 otherwise.
An instance can define either this unified shift or shiftL and
shiftR, depending on which is more convenient for the type in
question.
Return the number of bits in the type of the argument. The actual
value of the argument is ignored. Returns Nothing
for types that do not have a fixed bitsize, like Integer.
Return the number of bits in the type of the argument. The actual
value of the argument is ignored. The function bitSize is
undefined for types that do not have a fixed bitsize, like Integer.
Default implementation based upon bitSizeMaybe provided since
4.12.0.0.
Shift the argument left by the specified number of bits
(which must be non-negative). Some instances may throw an
Overflow exception if given a negative input.
An instance can define either this and shiftR or the unified
shift, depending on which is more convenient for the type in
question.
Shift the argument left by the specified number of bits. The
result is undefined for negative shift amounts and shift amounts
greater or equal to the bitSize.
Defaults to shiftL unless defined explicitly by an instance.
Shift the first argument right by the specified number of bits. The
result is undefined for negative shift amounts and shift amounts
greater or equal to the bitSize. Some instances may throw an
Overflow exception if given a negative input.
Right shifts perform sign extension on signed number types;
i.e. they fill the top bits with 1 if the x is negative
and with 0 otherwise.
An instance can define either this and shiftL or the unified
shift, depending on which is more convenient for the type in
question.
EqScientificDefined in scientific-0.3.8.0 · Data.Scientific
Scientific numbers can be safely compared for equality. No magnitude 10^e
is calculated so there's no risk of a blowup in space or time when comparing
scientific numbers coming from untrusted sources.
These methods also compute Integer magnitudes (10^e). If these methods
are applied to arguments which have huge exponents this could fill up all
space and crash your program! So don't apply these methods to scientific
numbers coming from untrusted sources.
fromRational will throw an error when the input Rational is a repeating
decimal. Consider using fromRationalRepetend for these rationals which
will detect the repetition and indicate where it starts.
DataScientificDefined in scientific-0.3.8.0 · Data.Scientific
NumScientificDefined in scientific-0.3.8.0 · Data.Scientific
WARNING:+ and - compute the Integer magnitude: 10^e where e is
the difference between the base10Exponents of the arguments. If these
methods are applied to arguments which have huge exponents this could fill up
all space and crash your program! So don't apply these methods to scientific
numbers coming from untrusted sources. The other methods can be used safely.
OrdScientificDefined in scientific-0.3.8.0 · Data.Scientific
Scientific numbers can be safely compared for ordering. No magnitude 10^e
is calculated so there's no risk of a blowup in space or time when comparing
scientific numbers coming from untrusted sources.
ReadScientificDefined in scientific-0.3.8.0 · Data.Scientific
Supports the skipping of parentheses and whitespaces. Example:
> read " ( (( -1.0e+3 ) ))" :: Scientific
-1000.0
(Note: This Read instance makes internal use of
scientificP to parse the floating-point number.)
RealScientificDefined in scientific-0.3.8.0 · Data.Scientific
WARNING:toRational needs to compute the Integer magnitude:
10^e. If applied to a huge exponent this could fill up all space
and crash your program!
Avoid applying toRational (or realToFrac) to scientific numbers
coming from an untrusted source and use toRealFloat instead. The
latter guards against excessive space usage.
WARNING: the methods of the RealFrac instance need to compute the
magnitude 10^e. If applied to a huge exponent this could take a long
time. Even worse, when the destination type is unbounded (i.e. Integer) it
could fill up all space and crash your program!
ShowScientificDefined in scientific-0.3.8.0 · Data.Scientific
See formatScientific if you need more control over the rendering.
Note that in the future I intend to change the type of the base10Exponent
from Int to Integer. To be forward compatible the Binary instance
already encodes the exponent as Integer.
A hash can be safely calculated from a Scientific. No magnitude 10^e is
calculated so there's no risk of a blowup in space or time when hashing
scientific numbers coming from untrusted sources.
Example4 expressions
>>> import Data.Hashable (hash)>>> let x = scientific 1 2>>> let y = scientific 100 0>>> (x == y, hash x == hash y)(True,True)
LiftScientificDefined in scientific-0.3.8.0 · Data.Scientific
Character literals in Haskell are single-quoted: 'Q', 'Я' or 'Ω'.
To represent a single quote itself use '\'', and to represent a backslash
use '\\'. The full grammar can be found in the section 2.6 of the
Haskell 2010 Language Report.
To specify a character by its code point one can use decimal, hexadecimal
or octal notation: '\65', '\x41' and '\o101' are all alternative forms
of 'A'. The largest code point is '\x10ffff'.
There is a special escape syntax for ASCII control characters:
In haskell, complex numbers are represented as a :+ b which can be thought of
as representing a + bi. For a complex number z, abs z is a number with the magnitude of z,
but oriented in the positive real direction, whereas signum z
has the phase of z, but unit magnitude.
Apart from the loss of precision due to IEEE754 floating point numbers,
it holds that z == abs z * signum z.
Note that Complex's instances inherit the deficiencies from the type
parameter's. For example, Complex Float's Ord instance has similar
problems to Float's.
As can be seen in the examples, the Foldable
and Traversable instances traverse the real part first.
A difference list is an abstraction representing a list that
supports \mathcal{O}(1) append and snoc operations, making it
useful for replacing frequent applications of ++ such as logging and pretty
printing (esp. if those uses of ++ are left-nested).
A value of type Dynamic is an object encapsulated together with its type.
A Dynamic may only represent a monomorphic value; an attempt to
create a value of type Dynamic from a polymorphically-typed
expression will result in an ambiguity error (see toDyn).
Showing a value of type Dynamic returns a pretty-printed representation
of the object's type; useful for debugging.
The Either type represents values with two possibilities: a value of
type Either a b is either Left a or Right b.
The Either type is sometimes used to represent a value which is
either correct or an error; by convention, the Left constructor is
used to hold an error value and the Right constructor is used to
hold a correct value (mnemonic: "right" also means "correct").
Examples
The type EitherStringInt is the type of values which can be either
a String or an Int. The Left constructor can be used only on
Strings, and the Right constructor can be used only on Ints:
Example6 expressions
>>> let s = Left "foo" :: Either String Int>>> sLeft "foo">>> let n = Right 3 :: Either String Int>>> nRight 3>>> :type ss :: Either String Int>>> :type nn :: Either String Int
The fmap from our Functor instance will ignore Left values, but
will apply the supplied function to values contained in a Right:
Example4 expressions
>>> let s = Left "foo" :: Either String Int>>> let n = Right 3 :: Either String Int>>> fmap (*2) sLeft "foo">>> fmap (*2) nRight 6
The Monad instance for Either allows us to chain together multiple
actions which may fail, and fail overall if any of the individual
steps failed. First we'll write a function that can either parse an
Int from a Char, or fail.
Example3 expressions
>>> import Data.Char ( digitToInt, isDigit )>>> :{ let parseEither :: Char -> Either String Int parseEither c | isDigit c = Right (digitToInt c) | otherwise = Left "parse error">>> :}
The following should work, since both '1' and '2' can be
parsed as Ints.
Example2 expressions
>>> :{ let parseMultiple :: Either String Int parseMultiple = do x <- parseEither '1' y <- parseEither '2' return (x + y)>>> :}
Example1 expression
>>> parseMultipleRight 3
But the following should fail overall, since the first operation where
we attempt to parse 'm' as an Int will fail:
Example2 expressions
>>> :{ let parseMultiple :: Either String Int parseMultiple = do x <- parseEither 'm' y <- parseEither '2' return (x + y)>>> :}
The Eq class defines equality (==) and inequality (/=).
All the basic datatypes exported by the Prelude are instances of Eq,
and Eq may be derived for any datatype whose constituents are also
instances of Eq.
The Haskell Report defines no laws for Eq. However, instances are
encouraged to follow these properties:
EqOptionsDefined in invariant-0.6.4 · Data.Functor.Invariant.TH
EqInvariantClassDefined in invariant-0.6.4 · Data.Functor.Invariant.TH.Internal
EqStarKindStatusDefined in invariant-0.6.4 · Data.Functor.Invariant.TH.Internal
EqEncodingExceptionDefined in os-string-2.0.7 · System.OsString.Encoding.Internal
EqOsCharDefined in os-string-2.0.7 · System.OsString.Internal.Types
Byte equality of the internal representation.
EqOsStringDefined in os-string-2.0.7 · System.OsString.Internal.Types
Byte equality of the internal representation.
EqPosixCharDefined in os-string-2.0.7 · System.OsString.Internal.Types
EqPosixStringDefined in os-string-2.0.7 · System.OsString.Internal.Types
EqWindowsCharDefined in os-string-2.0.7 · System.OsString.Internal.Types
EqWindowsStringDefined in os-string-2.0.7 · System.OsString.Internal.Types
EqModeDefined in pretty-1.1.3.6 · Text.PrettyPrint.Annotated.HughesPJ
EqStyleDefined in pretty-1.1.3.6 · Text.PrettyPrint.Annotated.HughesPJ
EqTextDetailsDefined in pretty-1.1.3.6 · Text.PrettyPrint.Annotated.HughesPJ
EqPrettyLevelDefined in pretty-1.1.3.6 · Text.PrettyPrint.Annotated.HughesPJClass
EqDocDefined in pretty-1.1.3.6 · Text.PrettyPrint.HughesPJ
EqPrettyLevelDefined in pretty-1.1.3.6 · Text.PrettyPrint.HughesPJClass
EqCardinalityDefined in random-1.2.1.3 · System.Random.GFinite
EqStdGenDefined in random-1.2.1.3 · System.Random.Internal
EqScientificDefined in scientific-0.3.8.0 · Data.Scientific
Scientific numbers can be safely compared for equality. No magnitude 10^e
is calculated so there's no risk of a blowup in space or time when comparing
scientific numbers coming from untrusted sources.
EqTSemDefined in stm-2.5.3.1 · Control.Concurrent.STM.TSem
EqAnnLookupDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqAnnTargetDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqBangDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqBndrVisDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqBodyDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqBytesDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqCallconvDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqClauseDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqConDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqDecDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqDecidedStrictnessDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqDerivClauseDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqDerivStrategyDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqDocLocDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqExpDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqFamilyResultSigDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqFixityDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqFixityDirectionDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqForeignDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqFunDepDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqGuardDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqInfoDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqInjectivityAnnDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqInlineDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqLitDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqLocDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqMatchDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqModNameDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqModuleDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqModuleInfoDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqNameDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqNameFlavourDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqNameSpaceDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqNamespaceSpecifierDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqOccNameDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqOverlapDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqPatDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqPatSynArgsDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqPatSynDirDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqPhasesDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqPkgNameDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqPragmaDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqRangeDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqRoleDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqRuleBndrDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqRuleMatchDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqSafetyDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqSourceStrictnessDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqSourceUnpackednessDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqSpecificityDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqStmtDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqTyLitDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqTySynEqnDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqTypeDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
EqTypeFamilyHeadDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
The type of fixed-point fractional numbers.
The type parameter specifies the number of digits of the fractional part and should be an instance of the HasResolution typeclass.
Lift (Fixeda)Defined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
NFData1FixedDefined in deepseq-1.5.0.0 · Control.DeepSeq
Enum (Fixeda)Defined in base-4.20.2.0 · Data.Fixed
Recall that, for numeric types, succ and pred typically add and subtract
1, respectively. This is not true in the case of Fixed, whose successor
and predecessor functions intuitively return the "next" and "previous" values
in the enumeration. The results of these functions thus depend on the
resolution of the Fixed value. For example, when enumerating values of
resolution 10^-3 of type Milli = Fixed E3,
Example1 expression
>>> succ (0.000 :: Milli)0.001
and likewise
Example1 expression
>>> pred (0.000 :: Milli)-0.001
In other words, succ and pred increment and decrement a fixed-precision
value by the least amount such that the value's resolution is unchanged.
For example, 10^-12 is the smallest (positive) amount that can be added to
a value of type Pico = Fixed E12 without changing its resolution, and so
Example1 expression
>>> succ (0.000000000000 :: Pico)0.000000000001
and similarly
Example1 expression
>>> pred (0.000000000000 :: Pico)-0.000000000001
This is worth bearing in mind when defining Fixed arithmetic sequences. In
particular, you may be forgiven for thinking the sequence
However, this is not true. On the contrary, similarly to the above
implementations of succ and pred, enumFromTo :: Pico -> Pico -> [Pico]
has a "step size" of 10^-12. Hence, the list [1..10] :: [Pico] has
the form
The Foldable class represents data structures that can be reduced to a
summary value one element at a time. Strict left-associative folds are a
good fit for space-efficient reduction, while lazy right-associative folds
are a good fit for corecursive iteration, or for folds that short-circuit
after processing an initial subsequence of the structure's elements.
Instances can be derived automatically by enabling the DeriveFoldable
extension. For example, a derived instance for a binary tree might be:
{-# LANGUAGE DeriveFoldable #-}
data Tree a = Empty
| Leaf a
| Node (Tree a) a (Tree a)
deriving Foldable
A more detailed description can be found in the Overview section of
Data.Foldable#overview.
For the class laws see the Laws section of Data.Foldable#laws.
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.
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.
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:
Example5 expressions
>>> 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"
A left-associative variant of foldMap that is strict in the
accumulator. Use this method for strict reduction when partial
results are merged via (<>).
Examples
Define a Monoid over finite bit strings under xor. Use it to
strictly compute the xor of a list of Int values.
Example11 expressions
>>> :set -XGeneralizedNewtypeDeriving>>> import Data.Bits (Bits, FiniteBits, xor, zeroBits)>>> import Data.Foldable (foldMap')>>> import Numeric (showHex)>>> >>> newtype X a = X a deriving (Eq, Bounded, Enum, Bits, FiniteBits)>>> instance Bits a => Semigroup (X a) where X a <> X b = X (a `xor` b)>>> instance Bits a => Monoid (X a) where mempty = X zeroBits>>> >>> let bits :: [Int]; bits = [0xcafe, 0xfeed, 0xdeaf, 0xbeef, 0x5411]>>> (\ (X a) -> showString "0x" . showHex a $ "") $ foldMap' X bits"0x42"
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,
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):
Example1 expression
>>> take 5 $ foldr (\i acc -> i : fmap (+3) acc) [] (repeat 1)[1,4,7,10,13]
foldr' is a variant of foldr that performs strict reduction from
right to left, i.e. starting with the right-most element. The input
structure must be finite, otherwise foldr' runs out of space
(diverges).
If you want a strict right fold in constant space, you need a structure
that supports faster than O(n) access to the right-most element, such
as Seq from the containers package.
This method does not run in constant space for structures such as lists
that don't support efficient right-to-left iteration and so require
O(n) space to perform right-to-left reduction. Use of this method
with such a structure is a hint that the chosen structure may be a poor
fit for the task at hand. If the order in which the elements are
combined is not important, use foldl' instead.
Left-associative fold of a structure, lazy in the accumulator. This
is rarely what you want, but can work well for structures with efficient
right-to-left sequencing and an operator that is lazy in its left
argument.
In the case of lists, foldl, when applied to a binary operator, a
starting value (typically the left-identity of the operator), and a
list, reduces the list using the binary operator, from left to right:
foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
Note that to produce the outermost application of the operator the
entire input list must be traversed. Like all left-associative folds,
foldl will diverge if given an infinite list.
If you want an efficient strict left-fold, you probably want to use
foldl' instead of foldl. The reason for this is that the latter
does not force the inner results (e.g. z `f` x1 in the above
example) before applying them to the operator (e.g. to (`f` x2)).
This results in a thunk chain O(n) elements long, which then must be
evaluated from the outside-in.
For a general Foldable structure this should be semantically identical
to:
The first example is a strict fold, which in practice is best performed
with foldl'.
Example1 expression
>>> foldl (+) 42 [1,2,3,4]52
Though the result below is lazy, the input is reversed before prepending
it to the initial accumulator, so corecursion begins only after traversing
the entire input string.
Example1 expression
>>> foldl (\acc c -> c : acc) "abcd" "efgh""hgfeabcd"
A left fold of a structure that is infinite on the right cannot
terminate, even when for any finite input the fold just returns the
initial accumulator:
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,
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:
Example1 expression
>>> null []True
Example1 expression
>>> 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).
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.
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:
This function is non-total and will raise a runtime exception if the
structure happens to be empty. A structure that supports random access
and maintains its elements in order should provide a specialised
implementation to return the maximum in faster than linear time.
Examples
Basic usage:
Example1 expression
>>> maximum [1..10]10
Example1 expression
>>> maximum []*** Exception: Prelude.maximum: empty list
Example1 expression
>>> maximum Nothing*** Exception: maximum: empty structure
WARNING: This function is partial for possibly-empty structures like lists.
This function is non-total and will raise a runtime exception if the
structure happens to be empty. A structure that supports random access
and maintains its elements in order should provide a specialised
implementation to return the minimum in faster than linear time.
Examples
Basic usage:
Example1 expression
>>> minimum [1..10]1
Example1 expression
>>> minimum []*** Exception: Prelude.minimum: empty list
A type f is a Functor if it provides a function fmap which, given any types a and b
lets you apply any function from (a -> b) to turn an f a into an f b, preserving the
structure of f. Furthermore f needs to adhere to the following:
Note, that the second law follows from the free theorem of the type fmap and
the first law, so you need only check that the former condition holds.
See these articles by School of Haskell or
David Luposchainsky
for an explanation.
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 Data.Bifunctor instance that allows
both the last and the penultimate parameters to be mapped over.
Examples
Convert from a Maybe Int to a Maybe String
using show:
Example2 expressions
>>> fmap show NothingNothing>>> fmap show (Just 3)Just "3"
Convert from an Either Int Int to an
Either Int String using show:
Example2 expressions
>>> fmap show (Left 17)Left 17>>> fmap show (Right 17)Right "17"
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:
Replace all locations in the input with the same value.
The default definition is fmap . const, but this may be
overridden with a more efficient version.
Examples
Perform a computation with Maybe and replace the result with a
constant value if it is Just:
Example2 expressions
>>> 'a' <$ Just 2Just 'a'>>> 'a' <$ NothingNothing
Right-to-left composition of functors.
The composition of applicative functors is always applicative,
but the composition of monads is not always a monad.
Whereas in Haskell, one can think of a Functor as containing or producing
values, a contravariant functor is a functor that can be thought of as
consuming values.
As an example, consider the type of predicate functions a -> Bool. One
such predicate might be negative x = x < 0, which
classifies integers as to whether they are negative. However, given this
predicate, we can re-use it in other situations, providing we have a way to
map values to integers. For instance, we can use the negative predicate
on a person's bank balance to work out if they are currently overdrawn:
newtype Predicate a = Predicate { getPredicate :: a -> Bool }
instance Contravariant Predicate where
contramap :: (a' -> a) -> (Predicate a -> Predicate a')
contramap f (Predicate p) = Predicate (p . f)
| `- First, map the input...
`----- then apply the predicate.
overdrawn :: Predicate Person
overdrawn = contramap personBankBalance negative
Any instance should be subject to the following laws:
Note, that the second law follows from the free theorem of the type of
contramap and the first law, so you need only check that the former
condition holds.
Replace all locations in the output with the same value.
The default definition is contramap . const, but this may be
overridden with a more efficient version.
Continuing the intuition that Contravariant functors consume input, a Divisible
contravariant functor also has the ability to be composed "beside" another contravariant
functor.
Serializers provide a good example of Divisible contravariant functors. To begin
let's start with the type of serializers for specific types:
newtype Serializer a = Serializer { runSerializer :: a -> ByteString }
This is a contravariant functor:
instance Contravariant Serializer where
contramap f s = Serializer (runSerializer s . f)
That is, given a serializer for a (s :: Serializer a), and a way to turn
bs into as (a mapping f :: b -> a), we have a serializer for b:
contramap f s :: Serializer b.
Divisible gives us a way to combine two serializers that focus on different
parts of a structure. If we postulate the existance of two primitive
serializers - string :: Serializer String and int :: Serializer Int, we
would like to be able to combine these into a serializer for pairs of
Strings and Ints. How can we do this? Simply run both serializers and
combine their output!
data StringAndInt = StringAndInt String Int
stringAndInt :: Serializer StringAndInt
stringAndInt = Serializer $ \(StringAndInt s i) ->
let sBytes = runSerializer string s
iBytes = runSerializer int i
in sBytes <> iBytes
divide is a generalization by also taking a contramap like function to
split any a into a pair. This conveniently allows you to target fields of
a record, for instance, by extracting the values under two fields and
combining them into a tuple.
To complete the example, here is how to write stringAndInt using a
Divisible instance:
instance Divisible Serializer where
conquer = Serializer (const mempty)
divide toBC bSerializer cSerializer = Serializer $ \a ->
case toBC a of
(b, c) ->
let bBytes = runSerializer bSerializer b
cBytes = runSerializer cSerializer c
in bBytes <> cBytes
stringAndInt :: Serializer StringAndInt
stringAndInt =
divide (\(StringAndInt s i) -> (s, i)) string int
Hashable is intended exclusively for use in in-memory data structures.
.
Hashable does not have a fixed standard.
This allows it to improve over time.
.
Because it does not have a fixed standard, different computers or computers on different versions of the code will observe different hash values.
As such, Hashable is not recommended for use other than in-memory datastructures.
Specifically, Hashable is not intended for network use or in applications which persist hashed values.
For stable hashing use named hashes: sha256, crc32, xxhash etc.
If two values are equal according to the == method, then
applying the hashWithSalt method on each of the two values
must produce the same integer result if the same salt is
used in each case.
It is not required that if two values are unequal
according to the == method, then applying the
hashWithSalt method on each of the two values must produce
distinct integer results. However, the programmer should be
aware that producing distinct integer results for unequal
values may improve the performance of hashing-based data
structures.
This method can be used to compute different hash values for
the same input by providing a different salt in each
application of the method. This implies that any instance
that defines hashWithSaltmust make use of the salt in
its implementation.
Like hashWithSalt, but no salt is used. The default
implementation uses hashWithSalt with some default salt.
Instances might want to implement this method to provide a more
efficient implementation than the default implementation.
A hash can be safely calculated from a Scientific. No magnitude 10^e is
calculated so there's no risk of a blowup in space or time when hashing
scientific numbers coming from untrusted sources.
Example4 expressions
>>> import Data.Hashable (hash)>>> let x = scientific 1 2>>> let y = scientific 100 0>>> (x == y, hash x == hash y)(True,True)
HashableTextDefined in hashable-1.4.7.0 · Data.Hashable.Class
HashableTextDefined in hashable-1.4.7.0 · Data.Hashable.Class
HashableDayDefined in time-compat-1.9.8 · Data.Time.Orphans · orphan
HashableMonthDefined in time-compat-1.9.8 · Data.Time.Orphans · orphan
HashableQuarterDefined in time-compat-1.9.8 · Data.Time.Orphans · orphan
A fixed-precision integer type with at least the range [-2^29 .. 2^29-1].
The exact range for a given implementation can be determined by using
minBound and maxBound from the Bounded class.
In Haskell, lists are one of the most important data types as they are
often used analogous to loops in imperative programming languages.
These lists are singly linked, which makes them unsuited for operations
that require \mathcal{O}(1) access. Instead, they are intended to
be traversed.
You can use List a or [a] in type signatures:
length :: [a] -> Int
or
length :: List a -> Int
They are fully equivalent, and List a will be normalised to [a].
Usage
Lists are constructed recursively using the right-associative constructor operator (or cons)
(:) :: a -> [a] -> [a], which prepends an element to a list,
and the empty list [].
Lists can also be constructed using list literals
of the form [x_1, x_2, ..., x_n]
which are syntactic sugar and, unless -XOverloadedLists is enabled,
are translated into uses of (:) and []
String literals, like "I 💜 hs", are translated into
Lists of characters, ['I', ' ', '💜', ' ', 'h', 's'].
Implementation
Internally and in memory, all the above are represented like this,
with arrows being pointers to locations in memory.
╭───┬───┬──╮ ╭───┬───┬──╮ ╭───┬───┬──╮ ╭────╮
│(:)│ │ ─┼──>│(:)│ │ ─┼──>│(:)│ │ ─┼──>│ [] │
╰───┴─┼─┴──╯ ╰───┴─┼─┴──╯ ╰───┴─┼─┴──╯ ╰────╯
v v v
1 2 3
The Semigroup operation for Map is union, which prefers
values from the left operand. If m1 maps a key k to a value
a1, and m2 maps the same key to a different value a2, then
their union m1 <> m2 maps k to a1.
The method names refer to the monoid of lists under concatenation,
but there are many other instances.
Some types can be viewed as a monoid in more than one way,
e.g. both addition and multiplication on numbers.
In such cases we often define newtypes and make those instances
of Monoid, e.g. Data.Semigroup.Sum and Data.Semigroup.Product.
NOTE: Semigroup is a superclass of Monoid since base-4.11.0.0.
NOTE: This method is redundant and has the default
implementation mappend = (<>) since base-4.11.0.0.
Should it be implemented manually, since 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.
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.
Monoidp => Monoid (Par1p)Defined in ghc-internal-9.1003.0 · GHC.Internal.Generics
Semigroupa => Monoid (Maybea)Defined in ghc-internal-9.1003.0 · GHC.Internal.Base
Lift a semigroup into Maybe forming a Monoid according to
http://en.wikipedia.org/wiki/Monoid: "Any semigroup S may be
turned into a monoid simply by adjoining an element e not in S
and defining e*e = e and e*s = s = s*e for all s ∈ S."
Since 4.11.0: constraint on inner a value generalised from
Monoid to Semigroup.
Bitsa => Monoid (Iora)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Bits
Bitsa => Monoid (Xora)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Bits
FiniteBitsa => Monoid (Anda)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Bits
This constraint is arguably too strong. However,
as some types (such as Natural) have undefined complement, this is the
only safe choice.
FiniteBitsa => Monoid (Iffa)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Bits
This constraint is arguably
too strong. However, as some types (such as Natural) have undefined
complement, this is the only safe choice.
The Ord class is used for totally ordered datatypes.
Instances of Ord can be derived for any user-defined datatype whose
constituent types are in Ord. The declared order of the constructors in
the data declaration determines the ordering in derived Ord instances. The
Ordering datatype allows a single comparison to determine the precise
ordering of two objects.
Ord, as defined by the Haskell report, implements a total order and has the
following properties:
Note that (7.) and (8.) do not require min and max to return either of
their arguments. The result is merely required to equal one of the
arguments in terms of (==).
Minimal complete definition: either compare or <=.
Using compare can be more efficient for complex types.
OrdByteArrayDefined in base-4.20.2.0 · Data.Array.Byte
Non-lexicographic ordering. This compares the lengths of
the byte arrays first and uses a lexicographic ordering if
the lengths are equal. Subject to change between major versions.
OrdOptionsDefined in bifunctors-5.6.2 · Data.Bifunctor.TH
OrdByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Internal.Type
OrdByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Lazy.Internal
OrdShortByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Short.Internal
Lexicographic order.
OrdIntSetDefined in containers-0.7 · Data.IntSet.Internal
OrdBigNatDefined in ghc-bignum-1.3 · GHC.Num.BigNat
OrdIntegerDefined in ghc-bignum-1.3 · GHC.Num.Integer
OrdNaturalDefined in ghc-bignum-1.3 · GHC.Num.Natural
OrdExtensionDefined in ghc-boot-th-9.10.3 · GHC.LanguageExtensions.Type
OrdVoidDefined in ghc-internal-9.1003.0 · GHC.Internal.Base
OrdByteOrderDefined in ghc-internal-9.1003.0 · GHC.Internal.ByteOrder
OrdClosureTypeDefined in ghc-internal-9.1003.0 · GHC.Internal.ClosureTypes
OrdBlockReasonDefined in ghc-internal-9.1003.0 · GHC.Internal.Conc.Sync
OrdThreadIdDefined in ghc-internal-9.1003.0 · GHC.Internal.Conc.Sync
OrdThreadStatusDefined in ghc-internal-9.1003.0 · GHC.Internal.Conc.Sync
OrdAllDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Semigroup.Internal
OrdAnyDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Semigroup.Internal
OrdSomeTypeRepDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Typeable.Internal
OrdUniqueDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Unique
OrdVersionDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Version
OrdTimeoutKeyDefined in ghc-internal-9.1003.0 · GHC.Internal.Event.TimeOut
OrdUniqueDefined in ghc-internal-9.1003.0 · GHC.Internal.Event.Unique
OrdErrorCallDefined in ghc-internal-9.1003.0 · GHC.Internal.Exception
OrdArithExceptionDefined in ghc-internal-9.1003.0 · GHC.Internal.Exception.Type
OrdFingerprintDefined in ghc-internal-9.1003.0 · GHC.Internal.Fingerprint.Type
OrdCBoolDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCClockDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCFloatDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCIntDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCIntMaxDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCLLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCPtrdiffDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCSCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCSUSecondsDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCShortDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCSigAtomicDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCSizeDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCTimeDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCUCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCUIntDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCUIntMaxDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCUIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCULLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCULongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCUSecondsDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCUShortDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCWcharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Ptr
OrdWordPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Ptr
OrdAssociativityDefined in ghc-internal-9.1003.0 · GHC.Internal.Generics
IEEE 754 Double-precision type includes not only numbers, but also
positive and negative infinities and a special element called NaN
(which can be quiet or signal).
IEEE 754-2008, section 5.11 requires that if at least one of arguments of
<=, <, >, >= is NaN then the result of the comparison is False,
and instanceOrdDouble complies with this requirement. This violates
the reflexivity: both NaN<=NaN and NaN>=NaN are False.
IEEE 754-2008, section 5.10 defines totalOrder predicate. Unfortunately,
compare on Doubles violates the IEEE standard and does not define a total order.
More specifically, both compareNaNx and comparexNaN always return GT.
Thus, users must be extremely cautious when using instanceOrdDouble.
For instance, one should avoid ordered containers with keys represented by Double,
because data loss and corruption may happen. An IEEE-compliant compare is available
in fp-ieee package as TotallyOrdered newtype.
Moving further, the behaviour of min and max with regards to NaN is
also non-compliant. IEEE 754-2008, section 5.3.1 defines that quiet NaN
should be treated as a missing data by minNum and maxNum functions,
for example, minNum(NaN, 1) = minNum(1, NaN) = 1. Some languages such as Java
deviate from the standard implementing minNum(NaN, 1) = minNum(1, NaN) = NaN.
However, min / max in base are even worse: minNaN 1 is 1, but min 1 NaN
is NaN.
IEEE 754-2008 compliant min / max can be found in ieee754 package under
minNum / maxNum names. Implementations compliant with
minimumNumber / maximumNumber from a newer
IEEE 754-2019,
section 9.6 are available from fp-ieee package.
OrdOptionsDefined in invariant-0.6.4 · Data.Functor.Invariant.TH
OrdInvariantClassDefined in invariant-0.6.4 · Data.Functor.Invariant.TH.Internal
OrdOsCharDefined in os-string-2.0.7 · System.OsString.Internal.Types
Byte ordering of the internal representation.
OrdOsStringDefined in os-string-2.0.7 · System.OsString.Internal.Types
Byte ordering of the internal representation.
OrdPosixCharDefined in os-string-2.0.7 · System.OsString.Internal.Types
OrdPosixStringDefined in os-string-2.0.7 · System.OsString.Internal.Types
OrdWindowsCharDefined in os-string-2.0.7 · System.OsString.Internal.Types
OrdWindowsStringDefined in os-string-2.0.7 · System.OsString.Internal.Types
OrdPrettyLevelDefined in pretty-1.1.3.6 · Text.PrettyPrint.Annotated.HughesPJClass
OrdPrettyLevelDefined in pretty-1.1.3.6 · Text.PrettyPrint.HughesPJClass
OrdCardinalityDefined in random-1.2.1.3 · System.Random.GFinite
OrdScientificDefined in scientific-0.3.8.0 · Data.Scientific
Scientific numbers can be safely compared for ordering. No magnitude 10^e
is calculated so there's no risk of a blowup in space or time when comparing
scientific numbers coming from untrusted sources.
OrdAnnLookupDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdAnnTargetDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdBangDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdBndrVisDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdBodyDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdBytesDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdCallconvDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdClauseDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdConDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdDecDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdDecidedStrictnessDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdDerivClauseDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdDerivStrategyDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdDocLocDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdExpDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdFamilyResultSigDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdFixityDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdFixityDirectionDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdForeignDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdFunDepDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdGuardDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdInfoDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdInjectivityAnnDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdInlineDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdLitDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdLocDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdMatchDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdModNameDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdModuleDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdModuleInfoDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdNameDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdNameFlavourDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdNameSpaceDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdNamespaceSpecifierDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdOccNameDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdOverlapDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdPatDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdPatSynArgsDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdPatSynDirDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdPhasesDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdPkgNameDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdPragmaDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdRangeDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdRoleDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdRuleBndrDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdRuleMatchDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdSafetyDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdSourceStrictnessDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdSourceUnpackednessDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdSpecificityDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdStmtDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdTyLitDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdTySynEqnDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdTypeDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
OrdTypeFamilyHeadDefined in template-haskell-2.22.0.0 · Language.Haskell.TH.Syntax
(Orda, Ordb) => Ord (Eitherab)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Either
(Orda, Ordb) => Ord (a, b)Defined in ghc-prim-0.12.0 · GHC.Classes
(Orde, Orda) => Ord (Validationea)Defined in either-5.0.3 · Data.Either.Validation
(Orde, Orda) => Ord (Validationea)Defined in selective-0.7.0.1 · Control.Selective
(Ordk, Ordv) => Ord (Mapkv)Defined in containers-0.7 · Data.Map.Internal
(Ordk, Ordv) => Ord (HashMapkv)Defined in unordered-containers-0.2.21 · Data.HashMap.Internal
The ordering is total and consistent with the Eq instance. However,
nothing else about the ordering is specified, and it may change from
version to version of either this package or of hashable.
Strictly map the second argument argument
covariantly with a function that is assumed
operationally to be a cast, such as a newtype
constructor.
Note: This operation is explicitly unsafe
since an implementation may choose to use
unsafeCoerce to implement this combinator
and it has no way to validate that your function
meets the requirements.
If you implement this combinator with
unsafeCoerce, then you are taking upon yourself
the obligation that you don't use GADT-like
tricks to distinguish values.
If you import Data.Profunctor.Unsafe you are
taking upon yourself the obligation that you
will only call this with a first argument that is
operationally identity.
The semantics of this function with respect to bottoms
should match the default definition:
(Profuctor.Unsafe.#.) ≡ \_ -> \p -> p `seq` rmapcoerce p
Strictly map the first argument argument
contravariantly with a function that is assumed
operationally to be a cast, such as a newtype
constructor.
Note: This operation is explicitly unsafe
since an implementation may choose to use
unsafeCoerce to implement this combinator
and it has no way to validate that your function
meets the requirements.
If you implement this combinator with
unsafeCoerce, then you are taking upon yourself
the obligation that you don't use GADT-like
tricks to distinguish values.
If you import Data.Profunctor.Unsafe you are
taking upon yourself the obligation that you
will only call this with a second argument that is
operationally identity.
The generalization of Costar of Functor that is strong with respect
to Either.
Note: This is also a notion of strength, except with regards to another monoidal
structure that we can choose to equip Hask with: the cocartesian coproduct.
This represents the right Kan extension of a Profunctorq along a
Profunctorp in a limited version of the 2-category of Profunctors where
the only object is the category Hask, 1-morphisms are profunctors composed
and compose with Profunctor composition, and 2-morphisms are just natural
transformations.
Proxy is a type that holds no data, but has a phantom parameter of
arbitrary type (or even kind). Its use is to provide type information, even
though there is no value available of that type (or it may be too costly to
create one).
Historically, Proxy :: Proxy a is a safer alternative to the
undefined :: a idiom.
Rational numbers, with numerator and denominator of some Integral type.
Note that Ratio's instances inherit the deficiencies from the type
parameter's. For example, Ratio Natural's Num instance has similar
problems to Numeric.Natural.Natural's.
The default definition will raise an exception for a multiplier that is <= 0.
This may be overridden with an implementation that is total. For monoids
it is preferred to use stimesMonoid.
By making this a member of the class, idempotent semigroups
and monoids can upgrade this to execute in \mathcal{O}(1) by
picking stimes = stimesIdempotent or stimes =
stimesIdempotentMonoid respectively.
Concatenation of StrictBuilder is right-biased:
the right builder will be run first. This allows a builder to
run tail-recursively when it was accumulated left-to-right.
Functors representing data structures that can be transformed to
structures of the same shape by performing an Applicative (or,
therefore, Monad) action on each element from left to right.
A more detailed description of what same shape means, the various methods,
how traversals are constructed, and example advanced use-cases can be found
in the Overview section of Data.Traversable#overview.
For the class laws see the Laws section of Data.Traversable#laws.
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.
Example1 expression
>>> traverse Just [1,2,3,4]Just [1,2,3,4]
Example1 expression
>>> 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.
Example1 expression
>>> traverse (const Nothing) [1,2,3,4]Nothing
Example1 expression
>>> traverse (\x -> if odd x then Just x else Nothing) [1,2,3,4]Nothing
Example1 expression
>>> traverse id [Right 1, Right 2, Right 3, Right 4, Left 0]Left 0
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.
Example1 expression
>>> sequenceA [Just 1, Just 2, Just 3]Just [1,2,3]
Example1 expression
>>> 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.
Example1 expression
>>> sequenceA [Just 1, Just 2, Just 3, Nothing]Nothing
Example1 expression
>>> sequenceA [Right 1, Right 2, Right 3, Left 4]Left 4
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 Data.Foldable.mapM_.
Examples
mapM is literally a traverse with a type signature restricted
to Monad. Its implementation may be more efficient due to additional
power of Monad.
Evaluate each monadic action in the structure from left to
right, and collect the results. For a version that ignores the
results see Data.Foldable.sequence_.
Examples
Basic usage:
The first two examples are instances where the input and
and output of sequence are isomorphic.
Example1 expression
>>> sequence $ Right [1,2,3,4][Right 1,Right 2,Right 3,Right 4]
String constants in Haskell are values of type String.
That means if you write a string literal like "hello world",
it will have the type [Char], which is the same as String.
Note: You can ask the compiler to automatically infer different types
with the -XOverloadedStrings language extension, for example
"hello world" :: Text. See IsString for more information.
Because String is just a list of characters, you can use normal list functions
to do basic string manipulation. See Data.List for operations on lists.
Performance considerations
[Char] is a relatively memory-inefficient type.
It is a linked list of boxed word-size characters, internally it looks something like:
╭─────┬───┬──╮ ╭─────┬───┬──╮ ╭─────┬───┬──╮ ╭────╮
│ (:) │ │ ─┼─>│ (:) │ │ ─┼─>│ (:) │ │ ─┼─>│ [] │
╰─────┴─┼─┴──╯ ╰─────┴─┼─┴──╯ ╰─────┴─┼─┴──╯ ╰────╯
v v v
'a' 'b' 'c'
The String "abc" will use 5*3+1 = 16 (in general 5n+1)
words of space in memory.
Furthermore, operations like (++) (string concatenation) are O(n)
(in the left argument).
For historical reasons, the base library uses String in a lot of places
for the conceptual simplicity, but library code dealing with user-data
should use the text
package for Unicode text, or the the
bytestring package
for binary data.
DataTextDefined in text-2.1.3 · Data.Text · orphan
This instance preserves data abstraction at the cost of inefficiency.
We omit reflection services for the sake of data abstraction.
This instance was created by copying the updated behavior of
Data.Set.Set and Data.Map.Data.Map.Map. If you
feel a mistake has been made, please feel free to submit
improvements.
A value of type IO a is a computation which, when performed,
does some I/O before returning a value of type a.
There is really only one way to "perform" an I/O action: bind it to
Main.main in your program. When your program is run, the I/O will
be performed. It isn't possible to perform I/O from an arbitrary
function, unless that function is itself in the IO monad and called
at some point, directly or indirectly, from Main.main.
IO is a monad, so IO actions can be combined using either the do-notation
or the >> and >>= operations from the Monad
class.
The function decodeFloat applied to a real floating-point
number returns the significand expressed as an Integer and an
appropriately scaled exponent (an Int). If decodeFloat x
yields (m,n), then x is equal in value to m*b^^n, where b
is the floating-point radix, and furthermore, either m and n
are both zero or else b^(d-1) <= abs m < b^d, where d is
the value of floatDigits x.
In particular, decodeFloat 0 = (0,0). If the type
contains a negative zero, also decodeFloat (-0.0) = (0,0).
The result ofdecodeFloat xis unspecified if either ofisNaN xorisInfinite xisTrue.
encodeFloat performs the inverse of decodeFloat in the
sense that for finite x with the exception of -0.0,
uncurryencodeFloat (decodeFloat x) = x.
encodeFloat m n is one of the two closest representable
floating-point numbers to m*b^^n (or ±Infinity if overflow
occurs); usually the closer, but if m contains too many bits,
the result may be rounded in the wrong direction.
exponent corresponds to the second component of decodeFloat.
exponent 0 = 0 and for finite nonzero x,
exponent x = snd (decodeFloat x) + floatDigits x.
If x is a finite floating-point number, it is equal in value to
significand x * b ^^ exponent x, where b is the
floating-point radix.
The behaviour is unspecified on infinite or NaN values.
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.
a version of arctangent taking two real floating-point arguments.
For real floating x and y, atan2 y x computes the angle
(from the positive x-axis) of the vector from the origin to the
point (x,y). atan2 y x returns a value in the range [-pi,
pi]. It follows the Common Lisp semantics for the origin when
signed zeroes are supported. atan2 y 1, with y in a type
that is RealFloat, should return the same value as atan y.
A default definition of atan2 is provided, but implementors
can provide a more accurate implementation.
Instances9RealFloat, …
RealFloatCDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
RealFloatCFloatDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
RealFloatDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Float
RealFloatFloatDefined in ghc-internal-9.1003.0 · GHC.Internal.Float
RealFloata => RealFloat (Identitya)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Functor.Identity
Derived instances of Read make the following assumptions, which
derived instances of Text.Show.Show obey:
If the constructor is defined to be an infix operator, then the
derived Read instance will parse only infix applications of
the constructor (not the prefix form).
Associativity is not used to reduce the occurrence of parentheses,
although precedence may be.
If the constructor is defined using record syntax, the derived Read
will parse only the record-syntax form, and furthermore, the fields
must be given in the same order as the original declaration.
The derived Read instance allows arbitrary Haskell whitespace
between tokens of the input string. Extra parentheses are also
allowed.
For example, given the declarations
infixr 5 :^:
data Tree a = Leaf a | Tree a :^: Tree a
the derived instance of Read in Haskell 2010 is equivalent to
instance (Read a) => Read (Tree a) where
readsPrec d r = readParen (d > app_prec)
(\r -> [(Leaf m,t) |
("Leaf",s) <- lex r,
(m,t) <- readsPrec (app_prec+1) s]) r
++ readParen (d > up_prec)
(\r -> [(u:^:v,w) |
(u,s) <- readsPrec (up_prec+1) r,
(":^:",t) <- lex s,
(v,w) <- readsPrec (up_prec+1) t]) r
where app_prec = 10
up_prec = 5
Note that right-associativity of :^: is unused.
The derived instance in GHC is equivalent to
instance (Read a) => Read (Tree a) where
readPrec = parens $ (prec app_prec $ do
Ident "Leaf" <- lexP
m <- step readPrec
return (Leaf m))
+++ (prec up_prec $ do
u <- step readPrec
Symbol ":^:" <- lexP
v <- step readPrec
return (u :^: v))
where app_prec = 10
up_prec = 5
readListPrec = readListPrecDefault
Why do both readsPrec and readPrec exist, and why does GHC opt to
implement readPrec in derived Read instances instead of readsPrec?
The reason is that readsPrec is based on the ReadS type, and although
ReadS is mentioned in the Haskell 2010 Report, it is not a very efficient
parser data structure.
readPrec, on the other hand, is based on a much more efficient ReadPrec
datatype (a.k.a "new-style parsers"), but its definition relies on the use
of the RankNTypes language extension. Therefore, readPrec (and its
cousin, readListPrec) are marked as GHC-only. Nevertheless, it is
recommended to use readPrec instead of readsPrec whenever possible
for the efficiency improvements it brings.
As mentioned above, derived Read instances in GHC will implement
readPrec instead of readsPrec. The default implementations of
readsPrec (and its cousin, readList) will simply use readPrec under
the hood. If you are writing a Read instance by hand, it is recommended
to write it like so:
attempts to parse a value from the front of the string, returning
a list of (parsed value, remaining string) pairs. If there is no
successful parse, the returned list is empty.
Derived instances of Read and Text.Show.Show satisfy the following:
The method readList is provided to allow the programmer to
give a specialised way of parsing lists of values.
For example, this is used by the predefined Read instance of
the Char type, where values of type String are expected to
use double quotes, rather than square brackets.
ReadTextDefined in text-2.1.3 · Data.Text · orphan
ReadTextDefined in text-2.1.3 · Data.Text.Lazy · orphan
ReadFPFormatDefined in text-2.1.3 · Data.Text.Lazy.Builder.RealFloat
ReadDatatypeVariantDefined in th-abstraction-0.7.1.0 · Language.Haskell.TH.Datatype
ReadDayDefined in time-1.12.2 · Data.Time.Format.Parse · orphan
ReadMonthDefined in time-1.12.2 · Data.Time.Calendar.Month
Read as yyyy-mm.
ReadQuarterDefined in time-1.12.2 · Data.Time.Calendar.Quarter
Read as yyyy-Qn.
ReadQuarterOfYearDefined in time-1.12.2 · Data.Time.Calendar.Quarter
ReadDayOfWeekDefined in time-1.12.2 · Data.Time.Calendar.Week
ReadDiffTimeDefined in time-1.12.2 · Data.Time.Clock.Internal.DiffTime
ReadNominalDiffTimeDefined in time-1.12.2 · Data.Time.Clock.Internal.NominalDiffTime
ReadUTCTimeDefined in time-1.12.2 · Data.Time.Format.Parse · orphan
ReadUniversalTimeDefined in time-1.12.2 · Data.Time.Format.Parse · orphan
ReadLocalTimeDefined in time-1.12.2 · Data.Time.Format.Parse · orphan
ReadTimeOfDayDefined in time-1.12.2 · Data.Time.Format.Parse · orphan
ReadTimeZoneDefined in time-1.12.2 · Data.Time.Format.Parse · orphan
This only works for ±HHMM format,
single-letter military time-zones,
and these time-zones: "UTC", "UT", "GMT", "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", "PDT",
per RFC 822 section 5.
ReadZonedTimeDefined in time-1.12.2 · Data.Time.Format.Parse · orphan
This only works for a zonedTimeZone in ±HHMM format,
single-letter military time-zones,
and these time-zones: "UTC", "UT", "GMT", "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", "PDT",
per RFC 822 section 5.
ReadUUIDDefined in uuid-types-1.0.6 · Data.UUID.Types.Internal
ReadUnpackedUUIDDefined in uuid-types-1.0.6 · Data.UUID.Types.Internal
Read ()Defined in ghc-internal-9.1003.0 · GHC.Internal.Read
Reada => Read (Complexa)Defined in base-4.20.2.0 · Data.Complex
Reada => Read (Firsta)Defined in base-4.20.2.0 · Data.Semigroup
Reada => Read (Lasta)Defined in base-4.20.2.0 · Data.Semigroup
Reada => Read (Maxa)Defined in base-4.20.2.0 · Data.Semigroup
Reada => Read (Mina)Defined in base-4.20.2.0 · Data.Semigroup
Reada => Read (Seqa)Defined in containers-0.7 · Data.Sequence.Internal
Reada => Read (ViewLa)Defined in containers-0.7 · Data.Sequence.Internal
Reada => Read (ViewRa)Defined in containers-0.7 · Data.Sequence.Internal
Reada => Read (Treea)Defined in containers-0.7 · Data.Tree
Reada => Read (DNonEmptya)Defined in dlist-1.0 · Data.DList.DNonEmpty.Internal
Reada => Read (DLista)Defined in dlist-1.0 · Data.DList.Internal
Reada => Read (NonEmptya)Defined in ghc-internal-9.1003.0 · GHC.Internal.Read
Reada => Read (Anda)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Bits
Reada => Read (Iffa)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Bits
Reada => Read (Iora)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Bits
Reada => Read (Xora)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Bits
Reada => Read (Identitya)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Functor.Identity
This instance would be equivalent to the derived instances of the
Identity newtype if the runIdentity field were removed
Reada => Read (Firsta)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Monoid
Reada => Read (Lasta)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Monoid
Reada => Read (Downa)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Ord
This instance would be equivalent to the derived instances of the
Down newtype if the getDown field were removed
Reada => Read (Duala)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Semigroup.Internal
Reada => Read (Producta)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Semigroup.Internal
Reada => Read (Suma)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Semigroup.Internal
Reada => Read (ZipLista)Defined in ghc-internal-9.1003.0 · GHC.Internal.Functor.ZipList
Reada => Read (Maybea)Defined in ghc-internal-9.1003.0 · GHC.Internal.Read
Reada => Read (Arraya)Defined in primitive-0.9.1.0 · Data.Primitive.Array
Reada => Read (SmallArraya)Defined in primitive-0.9.1.0 · Data.Primitive.SmallArray
Reada => Read (Vectora)Defined in vector-0.13.2.0 · Data.Vector
Reada => Read (Vectora)Defined in vector-0.13.2.0 · Data.Vector.Strict
Reada => Read (a)Defined in ghc-internal-9.1003.0 · GHC.Internal.Read
Reada => Read [a]Defined in ghc-internal-9.1003.0 · GHC.Internal.Read
Reade => Read (IntMape)Defined in containers-0.7 · Data.IntMap.Internal
A simple day and time aggregate, where the day is of the specified parameter,
and the time is a TimeOfDay.
Conversion of this (as local civil time) to UTC depends on the time zone.
Conversion of this (as local mean time) to UT1 depends on the longitude.
EqUUIDDefined in uuid-types-1.0.6 · Data.UUID.Types.Internal
DataUUIDDefined in uuid-types-1.0.6 · Data.UUID.Types.Internal
OrdUUIDDefined in uuid-types-1.0.6 · Data.UUID.Types.Internal
ReadUUIDDefined in uuid-types-1.0.6 · Data.UUID.Types.Internal
ShowUUIDDefined in uuid-types-1.0.6 · Data.UUID.Types.Internal
Pretty prints a UUID (without quotation marks). See also toString.
Example1 expression
>>> show nil"00000000-0000-0000-0000-000000000000"
StorableUUIDDefined in uuid-types-1.0.6 · Data.UUID.Types.Internal
This Storable instance uses the memory layout as described in RFC 4122, but in contrast to the Binary instance, the fields are stored in host byte order.
NFDataUUIDDefined in uuid-types-1.0.6 · Data.UUID.Types.Internal
RandomUUIDDefined in uuid-types-1.0.6 · Data.UUID.Types.Internal
This Random instance produces insecure version 4 UUIDs as
specified in RFC 4122.
UniformUUIDDefined in uuid-types-1.0.6 · Data.UUID.Types.Internal
BinaryUUIDDefined in uuid-types-1.0.6 · Data.UUID.Types.Internal
This Binary instance is compatible with RFC 4122, storing the fields in network order as 16 bytes.
HashableUUIDDefined in uuid-types-1.0.6 · Data.UUID.Types.Internal
LiftUUIDDefined in uuid-types-1.0.6 · Data.UUID.Types.Internal
The member functions of this class facilitate writing values of
primitive types to raw memory (which may have been allocated with the
above mentioned routines) and reading values from blocks of raw
memory. The class, furthermore, includes support for computing the
storage requirements and alignment restrictions of storable types.
Memory addresses are represented as values of type Ptr a, for some
a which is an instance of class Storable. The type argument to
Ptr helps provide some valuable type safety in FFI code (you can't
mix pointers of different types without an explicit cast), while
helping the Haskell type system figure out which marshalling method is
needed for a given pointer.
All marshalling between Haskell and a foreign language ultimately
boils down to translating Haskell data structures into the binary
representation of a corresponding data structure of the foreign
language and vice versa. To code this marshalling in Haskell, it is
necessary to manipulate primitive data types stored in unstructured
memory blocks. The class Storable facilitates this manipulation on
all types for which it is instantiated, which are the standard basic
types of Haskell, the fixed size Int types (Int8, Int16,
Int32, Int64), the fixed size Word types (Word8, Word16,
Word32, Word64), StablePtr, all types from Foreign.C.Types,
as well as Ptr.
Computes the alignment constraint of the argument. An
alignment constraint x is fulfilled by any address divisible
by x. The alignment must be a power of two if this instance
is to be used with alloca or allocaArray. The value of
the argument is not used.
Read a value from a memory area regarded as an array
of values of the same kind. The first argument specifies
the start address of the array and the second the index into
the array (the first element of the array has index
0). The following equality holds,
Note that the peek and poke functions might require properly
aligned addresses to function correctly. This is architecture
dependent; thus, portable code should ensure that when peeking or
poking values of some type a, the alignment
constraint for a, as given by the function
alignment is fulfilled.
Write the given value to the given memory location. Alignment
restrictions might apply; see peek.
Instances92Storable, …
StorableEventDefined in ghc-internal-9.1003.0 · GHC.Internal.Event.EPoll
StorableEventDefined in ghc-internal-9.1003.0 · GHC.Internal.Event.Poll
StorablePollFdDefined in ghc-internal-9.1003.0 · GHC.Internal.Event.Poll
StorableFingerprintDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
StorableCBoolDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCClockDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCFloatDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCIntDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCIntMaxDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCLLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCPtrdiffDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCSCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCSUSecondsDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCShortDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCSigAtomicDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCSizeDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCTimeDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCUCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCUIntDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCUIntMaxDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCUIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCULLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCULongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCUSecondsDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCUShortDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableCWcharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
StorableIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Ptr
StorableWordPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Ptr
StorableFLockDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Handle.Lock.LinuxOFD
StorableInt16Defined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
StorableInt32Defined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
StorableInt64Defined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
StorableInt8Defined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
StorableIoSubSystemDefined in ghc-internal-9.1003.0 · GHC.Internal.RTS.Flags
StorableCBlkCntDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCBlkSizeDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCCcDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCClockIdDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCDevDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCFsBlkCntDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCFsFilCntDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCGidDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCIdDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCInoDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCKeyDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCModeDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCNfdsDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCNlinkDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCOffDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCPidDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCRLimDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCSocklenDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCSpeedDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCSsizeDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCTcflagDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCTimerDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableCUidDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableFdDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
StorableWord16Defined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
StorableWord32Defined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
StorableWord64Defined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
StorableWord8Defined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
StorableBoolDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
StorableCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
StorableDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
StorableFloatDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
StorableIntDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
StorableWordDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
StorableCTimespecDefined in time-1.12.2 · Data.Time.Clock.Internal.CTimespec
StorableCTimevalDefined in time-1.12.2 · Data.Time.Clock.Internal.CTimeval
StorableUUIDDefined in uuid-types-1.0.6 · Data.UUID.Types.Internal
This Storable instance uses the memory layout as described in RFC 4122, but in contrast to the Binary instance, the fields are stored in host byte order.
Storable ()Defined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
Storable (ConstPtra)Defined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
Storable (FunPtra)Defined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
Storable (Ptra)Defined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
Storable (StablePtra)Defined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
A Version represents the version of a software entity.
An instance of Eq is provided, which implements exact equality
modulo reordering of the tags in the versionTags field.
An instance of Ord is also provided, which gives lexicographic
ordering on the versionBranch fields (i.e. 2.1 > 2.0, 1.2.3 > 1.2.2,
etc.). This is expected to be sufficient for many uses, but note that
you may need to use a more specific ordering for your versioning
scheme. For example, some versioning schemes may include pre-releases
which have tags "pre1", "pre2", and so on, and these would need to
be taken into account when determining ordering. In some cases, date
ordering may be more appropriate, so the application would have to
look for date tags in the versionTags field and compare those.
The bottom line is, don't always assume that compare and other Ord
operations are the right thing for every Version.
Similarly, concrete representations of versions may differ. One
possible concrete representation is provided (see showVersion and
parseVersion), but depending on the application a different concrete
representation may be more appropriate.
The numeric branch for this version. This reflects the
fact that most software versions are tree-structured; there
is a main trunk which is tagged with versions at various
points (1,2,3...), and the first branch off the trunk after
version 3 is 3.1, the second branch off the trunk after
version 3 is 3.2, and so on. The tree can be branched
arbitrarily, just by adding more digits.
We represent the branch as a list of Int, so
version 3.2.1 becomes [3,2,1]. Lexicographic ordering
(i.e. the default instance of Ord for [Int]) gives
the natural ordering of branches.
A version can be tagged with an arbitrary list of strings.
The interpretation of the list of tags is entirely dependent
on the entity that this version applies to.
Instances12IsList, Eq, Data, Ord, Read, Show, …
IsListVersionDefined in ghc-internal-9.1003.0 · GHC.Internal.IsList
EqVersionDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Version
DataVersionDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Data
OrdVersionDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Version
ReadVersionDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Version
ShowVersionDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Version
GenericVersionDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Version
NFDataVersionDefined in deepseq-1.5.0.0 · Control.DeepSeq
BinaryVersionDefined in binary-0.8.9.3 · Data.Binary.Class
HashableVersionDefined in hashable-1.4.7.0 · Data.Hashable.Class
The type ForeignPtr represents references to objects that are
maintained in a foreign language, i.e., that are not part of the
data structures usually managed by the Haskell storage manager.
The essential difference between ForeignPtrs and vanilla memory
references of type Ptr a is that the former may be associated
with finalizers. A finalizer is a routine that is invoked when
the Haskell storage manager detects that - within the Haskell heap
and stack - there are no more references left that are pointing to
the ForeignPtr. Typically, the finalizer will, then, invoke
routines in the foreign language that free the resources bound by
the foreign object.
The ForeignPtr is parameterised in the same way as Ptr. The
type argument of ForeignPtr should normally be an instance of
class Storable.
A value of type Ptr a represents a pointer to an object, or an
array of objects, which may be marshalled to or from Haskell values
of type a.
The type a will often be an instance of class
Storable which provides the marshalling operations.
However this is not essential, and you can provide your own operations
to access the pointer. For example you might write small foreign
functions to get or set the fields of a C struct.
A stable pointer is a reference to a Haskell expression that is
guaranteed not to be affected by garbage collection, i.e., it will neither be
deallocated nor will the value of the stable pointer itself change during
garbage collection (ordinary references may be relocated during garbage
collection). Consequently, stable pointers can be passed to foreign code,
which can treat it as an opaque reference to a Haskell value.
The StablePtr 0 is reserved for representing NULL in foreign code.
A value of type StablePtr a is a stable pointer to a Haskell
expression of type a.
Class Enum defines operations on sequentially ordered types.
The enumFrom... methods are used in Haskell's translation of
arithmetic sequences.
Instances of Enum may be derived for any enumeration type (types
whose constructors have no fields). The nullary constructors are
assumed to be numbered left-to-right by fromEnum from 0 through n-1.
See Chapter 10 of the Haskell Report for more details.
For any type that is an instance of class Bounded as well as Enum,
the following should hold:
fromEnum and toEnum should give a runtime error if the
result value is not representable in the result type.
For example, toEnum 7 :: Bool is an error.
enumFrom x = enumFromTo x maxBound
enumFromThen x y = enumFromThenTo x y bound
where
bound | fromEnum y >= fromEnum x = maxBound
| otherwise = minBound
Used in Haskell's translation of [n,n'..]
with [n,n'..] = enumFromThen n n', a possible implementation being
enumFromThen n n' = n : n' : worker (f x) (f x n'),
worker s v = v : worker s (s v), x = fromEnum n' - fromEnum n and
f n y
| n > 0 = f (n - 1) (succ y)
| n < 0 = f (n + 1) (pred y)
| otherwise = y
Used in Haskell's translation of [n,n'..m] with
[n,n'..m] = enumFromThenTo n n' m, a possible implementation
being enumFromThenTo n n' m = worker (f x) (c x) n m,
x = fromEnum n' - fromEnum n, c x = bool (>=) ((x 0)
f n y
| n > 0 = f (n - 1) (succ y)
| n < 0 = f (n + 1) (pred y)
| otherwise = y
and
worker s c v m
| c v m = v : worker s c (s v) m
| otherwise = []
EnumFPFormatDefined in text-2.1.3 · Data.Text.Lazy.Builder.RealFloat
EnumDayDefined in time-1.12.2 · Data.Time.Calendar.Days
EnumMonthDefined in time-1.12.2 · Data.Time.Calendar.Month
EnumQuarterDefined in time-1.12.2 · Data.Time.Calendar.Quarter
EnumQuarterOfYearDefined in time-1.12.2 · Data.Time.Calendar.Quarter
maps Q1..Q4 to 1..4
EnumDayOfWeekDefined in time-1.12.2 · Data.Time.Calendar.Week
"Circular", so for example [Tuesday ..] gives an endless sequence.
Also: fromEnum gives [1 .. 7] for [Monday .. Sunday], and toEnum performs mod 7 to give a cycle of days.
EnumDiffTimeDefined in time-1.12.2 · Data.Time.Clock.Internal.DiffTime
EnumNominalDiffTimeDefined in time-1.12.2 · Data.Time.Clock.Internal.NominalDiffTime
Enum ()Defined in ghc-internal-9.1003.0 · GHC.Internal.Enum
Enuma => Enum (Firsta)Defined in base-4.20.2.0 · Data.Semigroup
Enuma => Enum (Lasta)Defined in base-4.20.2.0 · Data.Semigroup
Enuma => Enum (Maxa)Defined in base-4.20.2.0 · Data.Semigroup
Enuma => Enum (Mina)Defined in base-4.20.2.0 · Data.Semigroup
Enum (Fixeda)Defined in base-4.20.2.0 · Data.Fixed
Recall that, for numeric types, succ and pred typically add and subtract
1, respectively. This is not true in the case of Fixed, whose successor
and predecessor functions intuitively return the "next" and "previous" values
in the enumeration. The results of these functions thus depend on the
resolution of the Fixed value. For example, when enumerating values of
resolution 10^-3 of type Milli = Fixed E3,
Example1 expression
>>> succ (0.000 :: Milli)0.001
and likewise
Example1 expression
>>> pred (0.000 :: Milli)-0.001
In other words, succ and pred increment and decrement a fixed-precision
value by the least amount such that the value's resolution is unchanged.
For example, 10^-12 is the smallest (positive) amount that can be added to
a value of type Pico = Fixed E12 without changing its resolution, and so
Example1 expression
>>> succ (0.000000000000 :: Pico)0.000000000001
and similarly
Example1 expression
>>> pred (0.000000000000 :: Pico)-0.000000000001
This is worth bearing in mind when defining Fixed arithmetic sequences. In
particular, you may be forgiven for thinking the sequence
However, this is not true. On the contrary, similarly to the above
implementations of succ and pred, enumFromTo :: Pico -> Pico -> [Pico]
has a "step size" of 10^-12. Hence, the list [1..10] :: [Pico] has
the form
DataFloatDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Data
NumFloatDefined in ghc-internal-9.1003.0 · GHC.Internal.Float · orphan
This instance implements IEEE 754 standard with all its usual pitfalls
about NaN, infinities and negative zero.
Neither addition nor multiplication are associative or distributive:
Haskell defines operations to read and write characters from and to files,
represented by values of type Handle. Each value of this type is a
handle: a record used by the Haskell run-time system to manage I/O
with file system objects. A handle has at least the following properties:
whether it manages input or output or both;
whether it is open, closed or semi-closed;
whether the object is seekable;
whether buffering is disabled, or enabled on a line or block basis;
a buffer (whose length may be zero).
Most handles will also have a current I/O position indicating where the next
input or output operation will occur. A handle is readable if it
manages only input or both input and output; likewise, it is writable if
it manages only output or both input and output. A handle is open when
first allocated.
Once it is closed it can no longer be used for either input or output,
though an implementation cannot re-use its storage while references
remain to it. Handles are in the Show and Eq classes. The string
produced by showing a handle is system dependent; it should include
enough information to identify the handle for debugging. A handle is
equal according to == only to itself; no attempt
is made to compare the internal state of different handles for equality.
Instances2Eq, Show
EqHandleDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Handle.Types
ShowHandleDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Handle.Types
Note that it isn't customarily expected that a type instance of both Num
and Ord implement an ordered ring. Indeed, in base only Integer and
Rational do.
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.
Instances91Num, …
NumIntegerDefined in ghc-internal-9.1003.0 · GHC.Internal.Num
NumNaturalDefined in ghc-internal-9.1003.0 · GHC.Internal.Num
Note that Natural's Num instance isn't a ring: no element but 0 has an
additive inverse. It is a semiring though.
NumEventTypeDefined in ghc-internal-9.1003.0 · GHC.Internal.Event.EPoll
NumEventDefined in ghc-internal-9.1003.0 · GHC.Internal.Event.Poll
NumUniqueDefined in ghc-internal-9.1003.0 · GHC.Internal.Event.Unique
NumCBoolDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCClockDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCFloatDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCIntDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCIntMaxDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCLLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCPtrdiffDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCSCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCSUSecondsDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCShortDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCSigAtomicDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCSizeDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCTimeDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCUCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCUIntDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCUIntMaxDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCUIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCULLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCULongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCUSecondsDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCUShortDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumCWcharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
NumIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Ptr
NumWordPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Ptr
NumInt16Defined in ghc-internal-9.1003.0 · GHC.Internal.Int
NumInt32Defined in ghc-internal-9.1003.0 · GHC.Internal.Int
NumInt64Defined in ghc-internal-9.1003.0 · GHC.Internal.Int
NumInt8Defined in ghc-internal-9.1003.0 · GHC.Internal.Int
NumCBlkCntDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCBlkSizeDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCCcDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCClockIdDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCDevDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCFsBlkCntDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCFsFilCntDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCGidDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCIdDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCInoDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCKeyDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCModeDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCNfdsDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCNlinkDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCOffDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCPidDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCRLimDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCSocklenDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCSpeedDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCSsizeDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCTcflagDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumCUidDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumFdDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
NumWord16Defined in ghc-internal-9.1003.0 · GHC.Internal.Word
NumWord32Defined in ghc-internal-9.1003.0 · GHC.Internal.Word
NumWord64Defined in ghc-internal-9.1003.0 · GHC.Internal.Word
NumWord8Defined in ghc-internal-9.1003.0 · GHC.Internal.Word
NumDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Float · orphan
This instance implements IEEE 754 standard with all its usual pitfalls
about NaN, infinities and negative zero.
Neither addition nor multiplication are associative or distributive:
NumFloatDefined in ghc-internal-9.1003.0 · GHC.Internal.Float · orphan
This instance implements IEEE 754 standard with all its usual pitfalls
about NaN, infinities and negative zero.
Neither addition nor multiplication are associative or distributive:
NumIntDefined in ghc-internal-9.1003.0 · GHC.Internal.Num
NumWordDefined in ghc-internal-9.1003.0 · GHC.Internal.Num
NumCardinalityDefined in random-1.2.1.3 · System.Random.GFinite
NumScientificDefined in scientific-0.3.8.0 · Data.Scientific
WARNING:+ and - compute the Integer magnitude: 10^e where e is
the difference between the base10Exponents of the arguments. If these
methods are applied to arguments which have huge exponents this could fill up
all space and crash your program! So don't apply these methods to scientific
numbers coming from untrusted sources. The other methods can be used safely.
(Applicativef, Numa) => Num (Apfa)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Monoid
Note that even if the underlying Num and Applicative instances are
lawful, for most Applicatives, this instance will not be lawful. If you use
this instance with the list Applicative, the following customary laws will
not hold:
Commutativity:
Example2 expressions
>>> Ap [10,20] + Ap [1,2]Ap {getAp = [11,12,21,22]}>>> Ap [1,2] + Ap [10,20]Ap {getAp = [11,21,12,22]}
Additive inverse:
Example2 expressions
>>> Ap [] + negate (Ap [])Ap {getAp = []}>>> fromInteger 0 :: Ap [] IntAp {getAp = [0]}
Distributivity:
Example2 expressions
>>> Ap [1,2] * (3 + 4)Ap {getAp = [7,14]}>>> (Ap [1,2] * 3) + (Ap [1,2] * 4)Ap {getAp = [7,11,10,14]}
Num (f (ga)) => Num (Composefga)Defined in base-4.20.2.0 · Data.Functor.Compose
The law does not hold for Float, Double, CFloat,
CDouble, etc., because these types contain non-finite values,
which cannot be roundtripped through Rational.
RealScientificDefined in scientific-0.3.8.0 · Data.Scientific
WARNING:toRational needs to compute the Integer magnitude:
10^e. If applied to a huge exponent this could fill up all space
and crash your program!
Avoid applying toRational (or realToFrac) to scientific numbers
coming from an untrusted source and use toRealFloat instead. The
latter guards against excessive space usage.
Derived instances of Show have the following properties, which
are compatible with derived instances of Text.Read.Read:
The result of show is a syntactically correct Haskell
expression containing only constants, given the fixity
declarations in force at the point where the type is declared.
It contains only the constructor names defined in the data type,
parentheses, and spaces. When labelled constructor fields are
used, braces, commas, field names, and equal signs are also used.
If the constructor is defined to be an infix operator, then
showsPrec will produce infix applications of the constructor.
the representation will be enclosed in parentheses if the
precedence of the top-level constructor in x is less than d
(associativity is ignored). Thus, if d is 0 then the result
is never surrounded in parentheses; if d is 11 it is always
surrounded in parentheses, unless it is an atomic expression.
If the constructor is defined using record syntax, then show
will produce the record-syntax form, with the fields given in the
same order as the original declaration.
For example, given the declarations
infixr 5 :^:
data Tree a = Leaf a | Tree a :^: Tree a
instance (Show a) => Show (Tree a) where
showsPrec d (Leaf m) = showParen (d > app_prec) $
showString "Leaf " . showsPrec (app_prec+1) m
where app_prec = 10
showsPrec d (u :^: v) = showParen (d > up_prec) $
showsPrec (up_prec+1) u .
showString " :^: " .
showsPrec (up_prec+1) v
where up_prec = 5
Note that right-associativity of :^: is ignored. For example,
show (Leaf 1 :^: Leaf 2 :^: Leaf 3) produces the string
"Leaf 1 :^: (Leaf 2 :^: Leaf 3)".
The method showList is provided to allow the programmer to
give a specialised way of showing lists of values.
For example, this is used by the predefined Show instance of
the Char type, where values of type String should be shown
in double quotes, rather than between square brackets.
Instances480Show, …
ShowByteArrayDefined in base-4.20.2.0 · Data.Array.Byte
ShowTimeoutDefined in base-4.20.2.0 · System.Timeout
ShowOptionsDefined in bifunctors-5.6.2 · Data.Bifunctor.TH
ShowBuilderDefined in bytestring-0.12.2.0 · Data.ByteString.Builder · orphan
ShowFormatModeDefined in bytestring-0.12.2.0 · Data.ByteString.Builder.RealFloat
ShowFloatingDecimalDefined in bytestring-0.12.2.0 · Data.ByteString.Builder.RealFloat.D2S
ShowFloatingDecimalDefined in bytestring-0.12.2.0 · Data.ByteString.Builder.RealFloat.F2S
ShowByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Internal.Type
An abstract name for an object, that supports equality and hashing.
Stable names have the following property:
If sn1 :: StableName and sn2 :: StableName and sn1 == sn2
then sn1 and sn2 were created by calls to makeStableName on
the same object.
The reverse is not necessarily true: if two stable names are not
equal, then the objects they name may still be equal. Note in particular
that makeStableName may return a different StableName after an
object is evaluated.
Stable Names are similar to Stable Pointers (Foreign.StablePtr),
but differ in the following ways:
There is no freeStableName operation, unlike Foreign.StablePtrs.
Stable names are reclaimed by the runtime system when they are no
longer needed.
There is no deRefStableName operation. You can't get back from
a stable name to the original Haskell object. The reason for
this is that the existence of a stable name for an object does not
guarantee the existence of the object itself; it can still be garbage
collected.
Fork a thread and call the supplied function when the thread is about
to terminate, with an exception or a returned value. The function is
called with asynchronous exceptions masked.
Block the current thread until data is available to read on the
given file descriptor (GHC only).
This will throw an IOError if the file descriptor was closed
while this thread was blocked. To safely close a file descriptor
that has been used with threadWaitRead, use
closeFdWith.
Returns an STM action that can be used to wait for data
to read from a file descriptor. The second returned value
is an IO action that can be used to deregister interest
in the file descriptor.
Block the current thread until data can be written to the
given file descriptor (GHC only).
This will throw an IOError if the file descriptor was closed
while this thread was blocked. To safely close a file descriptor
that has been used with threadWaitWrite, use
closeFdWith.
Returns an STM action that can be used to wait until data
can be written to a file descriptor. The second returned value
is an IO action that can be used to deregister interest
in the file descriptor.
Duplicate a Chan: the duplicate channel begins empty, but data written to
either channel from then on will be available from both. Hence this creates
a kind of broadcast channel, where data written by anyone is seen by
everyone else.
(Note that a duplicated channel is not equal to its original.
So: fmap (c /=) $ dupChan c returns True for all c.)
Read the next value from the Chan. Blocks when the channel is empty. Since
the read end of a channel is an MVar, this operation inherits fairness
guarantees of MVars (e.g. threads blocked in this operation are woken up in
FIFO order).
Throws BlockedIndefinitelyOnMVar when the channel is
empty and no other thread holds a reference to the channel.
Convert a single digit Char to the corresponding Int. This
function fails unless its argument satisfies isHexDigit, but
recognises both upper- and lower-case hexadecimal digits (that
is, '0'..'9', 'a'..'f', 'A'..'F').
Examples
Characters '0' through '9' are converted properly to
0..9:
Selects alphabetic Unicode characters (lower-case, upper-case and
title-case letters, plus letters of caseless scripts and
modifiers letters). This function is equivalent to
isAlpha.
This function returns True if its argument has one of the
following GeneralCategorys, or False otherwise:
The function polar takes a complex number and
returns a (magnitude, phase) pair in canonical form:
the magnitude is non-negative, and the phase in the range (-pi, pi];
if the magnitude is zero, then so is the phase.
readData p is a parser for datatypes where each alternative
begins with a data constructor. It parses the constructor and
passes it to p. Parsers for various constructors can be constructed
with readUnaryWith and readBinaryWith, and combined with
(<|>) from the Alternative class.
readsData p d is a parser for datatypes where each alternative
begins with a data constructor. It parses the constructor and
passes it to p. Parsers for various constructors can be constructed
with readsUnary, readsUnary1 and readsBinary1, and combined with
mappend from the Monoid class.
showsBinaryWith sp1 sp2 n d x y produces the string
representation of a binary data constructor with name n and arguments
x and y, in precedence context d.
If f is both Functor and Contravariant then by the time you factor
in the laws of each of those classes, it can't actually use its argument in
any meaningful capacity.
This method is surprisingly useful. Where both instances exist and are
lawful we have the following laws:
approxRational, applied to two real fractional numbers x and epsilon,
returns the simplest rational number within epsilon of x.
A rational number y is said to be simpler than another y' if
mtimesDefault n a = a <> a <> ... <> a -- using <> (n-1) times
In many cases, stimes 0 a for a Monoid will produce mempty.
However, there are situations when it cannot do so. In particular,
the following situation is fairly common:
data T a = ...
class Constraint1 a
class Constraint1 a => Constraint2 a
instance Constraint1 a => Semigroup (T a)
instance Constraint2 a => Monoid (T a)
Since Constraint1 is insufficient to implement mempty,
stimes for T a cannot do so.
When working with such a type, or when working polymorphically with
Semigroup instances, mtimesDefault should be used when the
multiplier might be zero. It is implemented using stimes when
the multiplier is nonzero and mempty when it is zero.
Wrap an IO computation to time out and return Nothing in case no result
is available within n microseconds (1/10^6 seconds). In case a result
is available before the timeout expires, Just a is returned. A negative
timeout interval means "wait indefinitely". When specifying long timeouts,
be careful not to exceed maxBound :: Int, which on 32-bit machines is only
2147483647 μs, less than 36 minutes.
Consider using Control.Concurrent.Timeout.timeout from unbounded-delays package.
Example1 expression
>>> timeout 1000000 (threadDelay 1000 *> pure "finished on time")Just "finished on time"
Example1 expression
>>> timeout 10000 (threadDelay 100000 *> pure "finished on time")Nothing
The design of this combinator was guided by the objective that timeout n f
should behave exactly the same as f as long as f doesn't time out. This
means that f has the same myThreadId it would have without the timeout
wrapper. Any exceptions f might throw cancel the timeout and propagate
further up. It also possible for f to receive exceptions thrown to it by
another thread.
A tricky implementation detail is the question of how to abort an IO
computation. This combinator relies on asynchronous exceptions internally
(namely throwing the computation the Timeout exception). The technique
works very well for computations executing inside of the Haskell runtime
system, but it doesn't work at all for non-Haskell code. Foreign function
calls, for example, cannot be timed out with this combinator simply because
an arbitrary C function cannot receive asynchronous exceptions. When
timeout is used to wrap an FFI call that blocks, no timeout event can be
delivered until the FFI call returns, which pretty much negates the purpose
of the combinator. In practice, however, this limitation is less severe than
it may sound. Standard I/O functions like GHC.Internal.System.IO.hGetBuf,
GHC.Internal.System.IO.hPutBuf, Network.Socket.accept, or GHC.Internal.System.IO.hWaitForInput
appear to be blocking, but they really don't because the runtime system uses
scheduling mechanisms like select(2) to perform asynchronous I/O, so it
is possible to interrupt standard socket I/O or file I/O using this
combinator.
The return value is either String or (IO a) (which
should be (IO ()), but Haskell's type system
makes this hard).
The format string consists of ordinary characters and
conversion specifications, which specify how to format
one of the arguments to printf in the output string. A
format specification is introduced by the % character;
this character can be self-escaped into the format string
using %%. A format specification ends with a
format character that provides the primary information about
how to format the value. The rest of the conversion
specification is optional. In order, one may have flag
characters, a width specifier, a precision specifier, and
type-specific modifier characters.
Unlike C printf(3), the formatting of this printf
is driven by the argument type; formatting is type specific. The
types formatted by printf "out of the box" are:
printf is also extensible to support other types: see below.
A conversion specification begins with the
character %, followed by zero or more of the following flags:
- left adjust (default is right adjust)
+ always use a sign (+ or -) for signed conversions
space leading space for positive numbers in signed conversions
0 pad with zeros rather than spaces
# use an \"alternate form\": see below
When both flags are given, - overrides 0 and + overrides space.
A negative width specifier in a * conversion is treated as
positive but implies the left adjust flag.
The "alternate form" for unsigned radix conversions is
as in C printf(3):
%o prefix with a leading 0 if needed
%x prefix with a leading 0x if nonzero
%X prefix with a leading 0X if nonzero
%b prefix with a leading 0b if nonzero
%[eEfFgG] ensure that the number contains a decimal point
Any flags are followed optionally by a field width:
num field width
* as num, but taken from argument list
The field width is a minimum, not a maximum: it will be
expanded as needed to avoid mutilating a value.
Any field width is followed optionally by a precision:
.num precision
. same as .0
.* as num, but taken from argument list
Negative precision is taken as 0. The meaning of the
precision depends on the conversion type.
Integral minimum number of digits to show
RealFloat number of digits after the decimal point
String maximum number of characters
The precision for Integral types is accomplished by zero-padding.
If both precision and zero-pad are given for an Integral field,
the zero-pad is ignored.
Any precision is followed optionally for Integral types
by a width modifier; the only use of this modifier being
to set the implicit size of the operand for conversion of
a negative operand to unsigned:
hh Int8
h Int16
l Int32
ll Int64
L Int64
The specification ends with a format character:
c character Integral
d decimal Integral
o octal Integral
x hexadecimal Integral
X hexadecimal Integral
b binary Integral
u unsigned decimal Integral
f floating point RealFloat
F floating point RealFloat
g general format float RealFloat
G general format float RealFloat
e exponent format float RealFloat
E exponent format float RealFloat
s string String
v default format any type
The "%v" specifier is provided for all built-in types,
and should be provided for user-defined type formatters
as well. It picks a "best" representation for the given
type. For the built-in types the "%v" specifier is
converted as follows:
c Char
u other unsigned Integral
d other signed Integral
g RealFloat
s String
Mismatch between the argument types and the format
string, as well as any other syntactic or semantic errors
in the format string, will cause an exception to be
thrown at runtime.
Note that the formatting for RealFloat types is
currently a bit different from that of C printf(3),
conforming instead to showEFloat,
showFFloat and showGFloat (and their
alternate versions showFFloatAlt and
showGFloatAlt). This is hard to fix: the fixed
versions would format in a backward-incompatible way.
In any case the Haskell behavior is generally more
sensible than the C behavior. A brief summary of some
key differences:
Haskell printf never uses the default "6-digit" precision
used by C printf.
Haskell printf treats the "precision" specifier as
indicating the number of digits after the decimal point.
Haskell printf prints the exponent of e-format
numbers without a gratuitous plus sign, and with the
minimum possible number of digits.
Haskell printf will place a zero after a decimal point when
possible.
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:
The mapBoth function takes two functions and applies the first if iff the value
takes the form Left _ and the second if the value takes the form Right _.
The whenLeft function takes an Either value and a function which returns a monad.
The monad is only executed when the given argument takes the form Left _, otherwise
it does nothing.
The whenRight function takes an Either value and a function which returns a monad.
The monad is only executed when the given argument takes the form Right _, otherwise
it does nothing.
Strict (call-by-value) application operator. It takes a function and an
argument, evaluates the argument to weak head normal form (WHNF), then calls
the function with that value.
A variant of <*> with the types of the arguments reversed. It differs from
flip(<*>) in that the effects are resolved in the order the arguments are
presented.
asTypeOf is a type-restricted version of const. It is usually
used as an infix operator, and its typing forces its first argument
(which is usually overloaded) to have the same type as the second.
Attempt to convert an Integral type a to an Integral type b using
the size of the types as measured by Bits methods.
A simpler version of this function is:
toIntegral :: (Integral a, Integral b) => a -> Maybe b
toIntegral x
| toInteger x == toInteger y = Just y
| otherwise = Nothing
where
y = fromIntegral x
This version requires going through Integer, which can be inefficient.
However, toIntegralSized is optimized to allow GHC to statically determine
the relative type sizes (as measured by bitSizeMaybe and isSigned) and
avoid going through Integer for many types. (The implementation uses
fromIntegral, which is itself optimized with rules for base types but may
go through Integer for some type pairs.)
Like forkIO, this sparks off a new thread to run the IO
computation passed as the first argument, and returns the ThreadId
of the newly created thread.
However, forkOS creates a bound thread, which is necessary if you
need to call foreign (non-Haskell) libraries that make use of
thread-local state, such as OpenGL (see Control.Concurrent#boundthreads).
Using forkOS instead of forkIO makes no difference at all to the
scheduling behaviour of the Haskell runtime system. It is a common
misconception that you need to use forkOS instead of forkIO to
avoid blocking all the Haskell threads when making a foreign call;
this isn't the case. To allow foreign calls to be made without
blocking all the Haskell threads (with GHC), it is only necessary to
use the -threaded option when linking your program, and to make sure
the foreign import is not marked unsafe.
Run the IO computation passed as the first argument. If the calling thread
is not bound, a bound thread is created temporarily. runInBoundThread
doesn't finish until the IO computation finishes.
You can wrap a series of foreign function calls that rely on thread-local state
with runInBoundThread so that you can use them without knowing whether the
current thread is bound.
Run the IO computation passed as the first argument. If the calling thread
is bound, an unbound thread is created temporarily using forkIO.
runInBoundThread doesn't finish until the IO computation finishes.
Use this function only in the rare case that you have actually observed a
performance loss due to the use of bound threads. A program that
doesn't need its main thread to be bound and makes heavy use of concurrency
(e.g. a web server), might want to wrap its main action in
runInUnboundThread.
Note that exceptions which are thrown to the current thread are thrown in turn
to the thread that is executing the given computation. This ensures there's
always a way of killing the forked thread.
Close a file descriptor in a concurrency-safe way (GHC only). If
you are using threadWaitRead or threadWaitWrite to perform
blocking I/O, you must use this function to close file
descriptors, or blocked threads may not be woken.
Any threads that are blocked on the file descriptor via
threadWaitRead or threadWaitWrite will be unblocked by having
IO exceptions thrown.
Switch the value of returned TVar from initial value False to True
after a given number of microseconds. The caveats associated with
threadDelay also apply.
Be careful not to exceed maxBound :: Int, which on 32-bit machines is only
2147483647 μs, less than 36 minutes.
Suspends the current thread for a given number of microseconds
(GHC only).
There is no guarantee that the thread will be rescheduled promptly
when the delay has expired, but the thread will never continue to
run earlier than specified.
Be careful not to exceed maxBound :: Int, which on 32-bit machines is only
2147483647 μs, less than 36 minutes.
Consider using Control.Concurrent.Thread.Delay.delay from unbounded-delays package.
Using atomically inside an unsafePerformIO or unsafeInterleaveIO
subverts some of guarantees that STM provides. It makes it possible to
run a transaction inside of another transaction, depending on when the
thunk is evaluated. If a nested transaction is attempted, an exception
is thrown by the runtime. It is possible to safely use atomically inside
unsafePerformIO or unsafeInterleaveIO, but the typechecker does not
rule out programs that may attempt nested transactions, meaning that
the programmer must take special care to prevent these.
catchSTM m f catches any exception thrown by m using throwSTM,
using the function f to handle the exception. If an exception is
thrown, any changes made by m are rolled back, but changes prior to
m persist.
Enables the allocation counter to be treated as a limit for the
current thread. When the allocation limit is enabled, if the
allocation counter counts down below zero, the thread will be sent
the AllocationLimitExceeded asynchronous exception. When this
happens, the counter is reinitialised (by default
to 100K, but tunable with the +RTS -xq option) so that it can handle
the exception and perform any necessary clean up. If it exhausts
this additional allowance, another AllocationLimitExceeded exception
is sent, and so forth. Like other asynchronous exceptions, the
AllocationLimitExceeded exception is deferred while the thread is inside
mask or an exception handler in catch.
Note that memory allocation is unrelated to live memory, also
known as heap residency. A thread can allocate a large amount of
memory and retain anything between none and all of it. It is
better to think of the allocation limit as a limit on
CPU time, rather than a limit on memory.
Compared to using timeouts, allocation limits don't count time
spent blocked or in foreign calls.
Creates a new thread to run the IO computation passed as the
first argument, and returns the ThreadId of the newly created
thread.
The new thread will be a lightweight, unbound thread. Foreign calls
made by this thread are not guaranteed to be made by any particular OS
thread; if you need foreign calls to be made by a particular OS
thread, then use forkOS instead.
The new thread inherits the masked state of the parent (see
GHC.Control.Exception.mask).
WARNING: Exceptions in the new thread will not be rethrown in the thread that
created it. This means that you might be completely unaware of the problem
if/when this happens. You may want to use the
async library instead.
Like forkIO, but the child thread is passed a function that can
be used to unmask asynchronous exceptions. This function is
typically used in the following way
so that the exception handler in the child thread is established
with asynchronous exceptions masked, meanwhile the main body of
the child thread is executed in the unmasked state.
Note that the unmask function passed to the child thread should
only be used in that thread; the behaviour is undefined if it is
invoked in a different thread.
Like forkIO, but lets you specify on which capability the thread
should run. Unlike a forkIO thread, a thread created by forkOn
will stay on the same capability for its entire lifetime (forkIO
threads can migrate between capabilities according to the scheduling
policy). forkOn is useful for overriding the scheduling policy when
you know in advance how best to distribute the threads.
The Int argument specifies a capability number (see
getNumCapabilities). Typically capabilities correspond to physical
processors, but the exact behaviour is implementation-dependent. The
value passed to forkOn is interpreted modulo the total number of
capabilities as returned by getNumCapabilities.
GHC note: the number of capabilities is specified by the +RTS -N
option when the program is started. Capabilities can be fixed to
actual processor cores with +RTS -qa if the underlying operating
system supports that, although in practice this is usually unnecessary
(and may actually degrade performance in some cases - experimentation
is recommended).
Returns the number of Haskell threads that can run truly
simultaneously (on separate physical processors) at any given time. To change
this value, use setNumCapabilities.
labelThread stores a string as identifier for this thread. This
identifier will be used in the debugging output to make distinction of
different threads easier (otherwise you only have the thread state object's
address in the heap). It also emits an event to the RTS eventlog.
Make a weak pointer to a ThreadId. It can be important to do
this if you want to hold a reference to a ThreadId while still
allowing the thread to receive the BlockedIndefinitely family of
exceptions (e.g. BlockedIndefinitelyOnMVar). Holding a normal
ThreadId reference will prevent the delivery of
BlockedIndefinitely exceptions because the reference could be
used as the target of throwTo at any time, which would unblock
the thread.
Holding a Weak ThreadId, on the other hand, will not prevent the
thread from receiving BlockedIndefinitely exceptions. It is
still possible to throw an exception to a Weak ThreadId, but the
caller must use deRefWeak first to determine whether the thread
still exists.
the value passed to the +RTS -N flag. This is the number of
Haskell threads that can run truly simultaneously at any given
time, and is typically set to the number of physical processor cores on
the machine.
Strictly speaking it is better to use getNumCapabilities, because
the number of capabilities might vary at runtime.
Retry execution of the current memory transaction because it has seen
values in TVars which mean that it should not continue (e.g. the TVars
represent a shared buffer that is now empty). The implementation may
block the thread until one of the TVars that it has read from has been
updated. (GHC only)
Every thread has an allocation counter that tracks how much
memory has been allocated by the thread. The counter is
initialized to zero, and setAllocationCounter sets the current
value. The allocation counter counts *down*, so in the absence of
a call to setAllocationCounter its value is the negation of the
number of bytes of memory allocated by the thread.
There are two things that you can do with this counter:
Set the number of Haskell threads that can run truly simultaneously
(on separate physical processors) at any given time. The number
passed to forkOn is interpreted modulo this value. The initial
value is given by the +RTS -N runtime flag.
This is also the number of threads that will participate in parallel
garbage collection. It is strongly recommended that the number of
capabilities is not set larger than the number of physical processor
cores, and it may often be beneficial to leave one or more cores free
to avoid contention with other processes in the machine.
Returns the number of the capability on which the thread is currently
running, and a boolean indicating whether the thread is locked to
that capability or not. A thread is locked to a capability if it
was created with forkOn.
A variant of throw that can only be used within the STM monad.
Throwing an exception in STM aborts the transaction and propagates the
exception. If the exception is caught via catchSTM, only the changes
enclosed by the catch are rolled back; changes made outside of catchSTM
persist.
If the exception is not caught inside of the STM, it is re-thrown by
atomically, and the entire STM is rolled back.
Although throwSTM has a type that is an instance of the type of throw, the
two functions are subtly different:
throw e `seq` x ===> throw e
throwSTM e `seq` x ===> x
The first example will cause the exception e to be raised,
whereas the second one won't. In fact, throwSTM will only cause
an exception to be raised when it is used within the STM monad.
The throwSTM variant should be used in preference to throw to
raise an exception within the STM monad because it guarantees
ordering with respect to other STM operations, whereas throw
does not.
throwTo raises an arbitrary exception in the target thread (GHC only).
Exception delivery synchronizes between the source and target thread:
throwTo does not return until the exception has been raised in the
target thread. The calling thread can thus be certain that the target
thread has received the exception. Exception delivery is also atomic
with respect to other exceptions. Atomicity is a useful property to have
when dealing with race conditions: e.g. if there are two threads that
can kill each other, it is guaranteed that only one of the threads
will get to kill the other.
Whatever work the target thread was doing when the exception was
raised is not lost: the computation is suspended until required by
another thread.
If the target thread is currently making a foreign call, then the
exception will not be raised (and hence throwTo will not return)
until the call has completed. This is the case regardless of whether
the call is inside a mask or not. However, in GHC a foreign call
can be annotated as interruptible, in which case a throwTo will
cause the RTS to attempt to cause the call to return; see the GHC
documentation for more details.
Important note: the behaviour of throwTo differs from that described in
the paper "Asynchronous exceptions in Haskell"
(http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm).
In the paper, throwTo is non-blocking; but the library implementation adopts
a more synchronous design in which throwTo does not return until the exception
is received by the target thread. The trade-off is discussed in Section 9 of the paper.
Like any blocking operation, throwTo is therefore interruptible (see Section 5.3 of
the paper). Unlike other interruptible operations, however, throwTo
is always interruptible, even if it does not actually block.
There is no guarantee that the exception will be delivered promptly,
although the runtime will endeavour to ensure that arbitrary
delays don't occur. In GHC, an exception can only be raised when a
thread reaches a safe point, where a safe point is where memory
allocation occurs. Some loops do not perform any memory allocation
inside the loop and therefore cannot be interrupted by a throwTo.
If the target of throwTo is the calling thread, then the behaviour
is the same as throwIO, except that the exception
is thrown as an asynchronous exception. This means that if there is
an enclosing pure computation, which would be the case if the current
IO operation is inside unsafePerformIO or unsafeInterleaveIO, that
computation is not permanently replaced by the exception, but is
suspended as if it had received an asynchronous exception.
Note that if throwTo is called with the current thread as the
target, the exception will be thrown even if the thread is currently
inside mask or uninterruptibleMask.
Unsafely performs IO in the STM monad. Beware: this is a highly
dangerous thing to do.
The STM implementation will often run transactions multiple
times, so you need to be prepared for this if your IO has any
side effects.
The STM implementation will abort transactions that are known to
be invalid and need to be restarted. This may happen in the middle
of unsafeIOToSTM, so make sure you don't acquire any resources
that need releasing (exception handlers are ignored when aborting
the transaction). That includes doing any IO using Handles, for
example. Getting this wrong will probably lead to random deadlocks.
The transaction may have seen an inconsistent view of memory when
the IO runs. Invariants that you expect to be true throughout
your program may not be true inside a transaction, due to the
way transactions are implemented. Normally this wouldn't be visible
to the programmer, but using unsafeIOToSTM can expose it.
The yield action allows (forces, in a co-operative multitasking
implementation) a context-switch to any other currently runnable
threads (if any), and is occasionally useful when implementing
concurrency abstractions.
An exception-safe wrapper for modifying the contents of an MVar.
Like withMVar, modifyMVar will replace the original contents of
the MVar if an exception is raised during the operation. This
function is only atomic if there are no other producers for this
MVar. In other words, it cannot guarantee that, by the time
modifyMVar_ gets the chance to write to the MVar, the value
of the MVar has not been altered by a write operation from another thread.
Take a value from an MVar, put a new value into the MVar and
return the value taken. This function is atomic only if there are
no other producers for this MVar. In other words, it cannot guarantee
that, by the time swapMVar gets the chance to write to the MVar,
the value of the MVar has not been altered
by a write operation from another thread.
withMVar is an exception-safe wrapper for operating on the contents
of an MVar. This operation is exception-safe: it will replace the
original contents of the MVar if an exception is raised (see
Control.Exception). However, it is only atomic if there are no
other producers for this MVar. In other words, it cannot guarantee
that, by the time withMVar gets the chance to write to the MVar,
the value of the MVar has not been altered
by a write operation from another thread.
When invoked inside mask, this function allows a masked
asynchronous exception to be raised, if one exists. It is
equivalent to performing an interruptible operation (see
#interruptible), but does not involve any actual blocking.
Sometimes you want to catch two different sorts of exception. You could
do something like
f = expr `catch` \ (ex :: ArithException) -> handleArith ex
`catch` \ (ex :: IOException) -> handleIO ex
However, there are a couple of problems with this approach. The first is
that having two exception handlers is inefficient. However, the more
serious issue is that the second exception handler will catch exceptions
in the first, e.g. in the example above, if handleArith throws an
IOException then the second exception handler will catch it.
Instead, we provide a function catches, which would be used thus:
f = expr `catches` [Handler (\ (ex :: ArithException) -> handleArith ex),
Handler (\ (ex :: IOException) -> handleIO ex)]
When you want to acquire a resource, do some work with it, and
then release the resource, it is a good idea to use bracket,
because bracket will install the necessary exception handler to
release the resource in the event that an exception is raised
during the computation. If an exception is raised, then bracket will
re-raise the exception (after performing the release).
The arguments to bracket are in this order so that we can partially apply
it, e.g.:
withFile name mode = bracket (openFile name mode) hClose
Bracket wraps the release action with mask, which is sufficient to ensure
that the release action executes to completion when it does not invoke any
interruptible actions, even in the presence of asynchronous exceptions. For
example, hClose is uninterruptible when it is not racing other uses of the
handle. Similarly, closing a socket (from "network" package) is also
uninterruptible under similar conditions. An example of an interruptible
action is killThread. Completion of interruptible release actions can be
ensured by wrapping them in uninterruptibleMask_, but this risks making
the program non-responsive to Control-C, or timeouts. Another option is to
run the release action asynchronously in its own thread:
void $ uninterruptibleMask_ $ forkIO $ do { ... }
The resource will be released as soon as possible, but the thread that invoked
bracket will not block in an uninterruptible state.
The function catchJust is like catch, but it takes an extra
argument which is an exception predicate, a function which
selects which type of exceptions we're interested in.
catchJust (\e -> if isDoesNotExistErrorType (ioeGetErrorType e) then Just () else Nothing)
(readFile f)
(\_ -> do hPutStrLn stderr ("No such file: " ++ show f)
return "")
Any other exceptions which are not matched by the predicate
are re-raised, and may be caught by an enclosing
catch, catchJust, etc.
Similar to catch, but returns an Either result which is
(Right a) if no exception of type e was raised, or (Left ex)
if an exception of type e was raised and its value is ex.
If any other type of exception is raised then it will be propagated
up to the next enclosing exception handler.
A variant of try that takes an exception predicate to select
which exceptions are caught (c.f. catchJust). If the exception
does not match the predicate, it is re-thrown.
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.
A common use of forever is to process input from network sockets,
System.IO.Handles, and channels
(e.g. Control.Concurrent.MVar.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:
Note that "forever" isn't necessarily non-terminating.
If the action is in a MonadPlus and short-circuits after some number of iterations.
then forever actually returns mzero, effectively short-circuiting its caller.
The mapAndUnzipM function maps its first argument over a list, returning
the result as a pair of lists. This function is mainly used with complicated
data structures or a state monad.
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:
Example4 expressions
>>> import Control.Monad ( when )>>> let report e = when (isLeft e) $ putStrLn "ERROR">>> report (Right 1)>>> report (Left "parse error")ERROR
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:
Example4 expressions
>>> import Control.Monad ( when )>>> let report e = when (isRight e) $ putStrLn "SUCCESS">>> report (Left "parse error")>>> report (Right 1)SUCCESS
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:
Example2 expressions
>>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]>>> partitionEithers list(["foo","bar","baz"],[3,7])
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:
Example1 expression
>>> and []True
Example1 expression
>>> and [True]True
Example1 expression
>>> and [False]False
Example1 expression
>>> and [True, True, False]False
Example1 expression
>>> and (False : repeat True) -- Infinite list [False,True,True,True,...False
The find function takes a predicate and a structure and returns
the leftmost element of the structure matching the predicate, or
Nothing if there is no such element.
Left-to-right monadic fold over the elements of a structure.
Given a structure t with elements (a, b, ..., w, x, y), the result of
a fold with an operator function f is equivalent to:
foldlM f z t = do
aa <- f z a
bb <- f aa b
...
xx <- f ww x
yy <- f xx y
return yy -- Just @return z@ when the structure is empty
For a Monad m, given two functions f1 :: a -> m b and f2 :: b -> m c,
their Kleisli composition (f1 >=> f2) :: a -> m c is defined by:
(f1 >=> f2) a = f1 a >>= f2
Another way of thinking about foldlM is that it amounts to an application
to z of a Kleisli composition:
foldlM f z t =
flip f a >=> flip f b >=> ... >=> flip f x >=> flip f y $ z
The monadic effects of foldlM are sequenced from left to right.
If at some step the bind operator (>>=) short-circuits (as with, e.g.,
mzero in a MonadPlus), the evaluated effects will be from an initial
segment of the element sequence. If you want to evaluate the monadic
effects in right-to-left order, or perhaps be able to short-circuit after
processing a tail of the sequence of elements, you'll need to use foldrM
instead.
If the monadic effects don't short-circuit, the outermost application of
f is to the rightmost element y, so that, ignoring effects, the result
looks like a left fold:
((((z `f` a) `f` b) ... `f` w) `f` x) `f` y
Examples
Basic usage:
Example2 expressions
>>> let f a e = do { print e ; return $ e : a }>>> foldlM f [] [0..3]0123[3,2,1,0]
Right-to-left monadic fold over the elements of a structure.
Given a structure t with elements (a, b, c, ..., x, y), the result of
a fold with an operator function f is equivalent to:
foldrM f z t = do
yy <- f y z
xx <- f x yy
...
bb <- f b cc
aa <- f a bb
return aa -- Just @return z@ when the structure is empty
For a Monad m, given two functions f1 :: a -> m b and f2 :: b -> m c,
their Kleisli composition (f1 >=> f2) :: a -> m c is defined by:
(f1 >=> f2) a = f1 a >>= f2
Another way of thinking about foldrM is that it amounts to an application
to z of a Kleisli composition:
foldrM f z t = f y >=> f x >=> ... >=> f b >=> f a $ z
The monadic effects of foldrM are sequenced from right to left, and e.g.
folds of infinite lists will diverge.
If at some step the bind operator (>>=) short-circuits (as with, e.g.,
mzero in a MonadPlus), the evaluated effects will be from a tail of the
element sequence. If you want to evaluate the monadic effects in
left-to-right order, or perhaps be able to short-circuit after an initial
sequence of elements, you'll need to use foldlM instead.
If the monadic effects don't short-circuit, the outermost application of
f is to the leftmost element a, so that, ignoring effects, the result
looks like a right fold:
a `f` (b `f` (c `f` (... (x `f` (y `f` z))))).
Examples
Basic usage:
Example2 expressions
>>> let f i acc = do { print i ; return $ i : acc }>>> foldrM f [] [0..3]3210[0,1,2,3]
Map each element of a structure to a monadic action, evaluate
these actions from left to right, and ignore the results. For a
version that doesn't ignore the results see
Data.Traversable.mapM.
mapM_ is just like traverse_, but specialised to monadic actions.
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:
Example1 expression
>>> or []False
Example1 expression
>>> or [True]True
Example1 expression
>>> or [False]False
Example1 expression
>>> or [True, True, False]True
Example1 expression
>>> or (True : repeat False) -- Infinite list [True,False,False,False,...True
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 Data.Traversable.sequence.
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.
& 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 flipid, where id 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
Example1 expression
>>> 5 & (+1) & show"6"
Example1 expression
>>> sqrt $ [1 / n^2 | n <- [1..1000]] & sum & (*6)3.1406380562059946
fix f is the least fixed point of the function f,
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
Example1 expression
>>> 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.
Example1 expression
>>> fix (\rec n -> if n <= 1 then 1 else n * rec (n-1)) 5120
on b u x y runs the binary function bon 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.
This function is useful for using IORef in a safe way in a multithreaded
program. If you only have one IORef, then using atomicModifyIORef to
access and modify it will prevent race conditions.
Extending the atomicity to multiple IORefs is problematic, so it
is recommended that if you need to do anything more complicated
then using Control.Concurrent.MVar.MVar instead is a good idea.
Conceptually,
atomicModifyIORef ref f = do
-- Begin atomic block
old <- readIORef ref
let r = f old
new = fst r
writeIORef ref new
-- End atomic block
case r of
(_new, res) -> pure res
The actions in the section labeled "atomic block" are not subject to
interference from other threads. In particular, it is impossible for the
value in the IORef to change between the readIORef and writeIORef
invocations.
The user-supplied function is applied to the value stored in the IORef,
yielding a new value to store in the IORef and a value to return. After
the new value is (lazily) stored in the IORef, atomicModifyIORef forces
the result pair, but does not force either component of the result. To force
both components, use atomicModifyIORef'.
Note that
atomicModifyIORef ref (_ -> undefined)
will raise an exception in the calling thread, but will also
install the bottoming value in the IORef, where it may be read by
other threads.
This function imposes a memory barrier, preventing reordering around the
"atomic block"; see Data.IORef#memmodel for details.
Variant of writeIORef. The prefix "atomic" relates to a fact that
it imposes a reordering barrier, similar to atomicModifyIORef.
Such a write will not be reordered with other reads
or writes even on CPUs with weak memory model.
Mutate the contents of an IORef, combining readIORef and writeIORef.
This is not an atomic update, consider using atomicModifyIORef when
operating in a multithreaded environment.
Be warned that modifyIORef does not apply the function strictly. This
means if the program calls modifyIORef many times, but seldom uses the
value, thunks will pile up in memory resulting in a space leak. This is a
common mistake made when using an IORef as a counter. For example, the
following will likely produce a stack overflow:
The isSubsequenceOf function takes two lists and returns True if all
the elements of the first list occur, in order, in the second. The
elements do not have to occur consecutively.
The catMaybes function takes a list of Maybes and returns
a list of all the Just values.
Examples
Basic usage:
Example1 expression
>>> 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):
Example3 expressions
>>> 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]
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.
The mapMaybe function is a version of map which can throw
out elements. In particular, the functional argument returns
something of type Maybe b. If this is Nothing, no element
is added on to the result list. If it is Just b, then b is
included in the result list.
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:
Example1 expression
>>> maybe False odd (Just 3)True
Example1 expression
>>> 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:
Apply show to a Maybe Int. If we have Just n, we want to show
the underlying Intn. But if we have Nothing, we return the
empty string instead of (for example) "Nothing":
Example2 expressions
>>> maybe "" show (Just 5)"5">>> maybe "" show Nothing""
The \\ function is list difference (non-associative).
In the result of xs\\ys, the first occurrence of each element of
ys in turn (if any) has been removed from xs. Thus
(xs ++ ys) \\ xs == ys.
It is a special case of deleteFirstsBy, which allows the programmer
to supply their own equality test.
Examples
Example1 expression
>>> "Hello World!" \\ "ell W""Hoorld!"
The second list must be finite, but the first may be infinite.
The deleteFirstsBy function takes a predicate and two lists and
returns the first list with the first occurrence of each element of
the second list removed. This is the non-overloaded version of (\\).
(\\) == deleteFirstsBy (==)
The second list must be finite, but the first may be infinite.
The dropWhileEnd function drops the largest suffix of a list
in which the given predicate holds for all elements.
Laziness
This function is lazy in spine, but strict in elements,
which makes it different from reverse.dropWhilep.reverse,
which is strict in spine, but lazy in elements. For instance:
Example1 expression
>>> take 1 (dropWhileEnd (< 0) (1 : undefined))[1]
The elemIndex function returns the index of the first element
in the given list which is equal (by ==) to the query element,
or Nothing if there is no such element.
For the result to be Nothing, the list must be finite.
The findIndex function takes a predicate and a list and returns
the index of the first element in the list satisfying the predicate,
or Nothing if there is no such element.
For the result to be Nothing, the list must be finite.
\mathcal{O}(n). The genericLength function is an overloaded version
of length. In particular, instead of returning an Int, it returns any
type which is an instance of Num. It is, however, less efficient than
length.
Users should take care to pick a return type that is wide enough to contain
the full length of the list. If the width is insufficient, the overflow
behaviour will depend on the (+) implementation in the selected Num
instance. The following example overflows because the actual list length
of 200 lies outside of the Int8 range of -128..127.
The groupBy function is the non-overloaded version of group.
When a supplied relation is not transitive, it is important
to remember that equality is checked against the first element in the group,
not against the nearest neighbour:
Example1 expression
>>> groupBy (\a b -> b - a < 5) [0..19][[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14],[15,16,17,18,19]]
It's often preferable to use Data.List.NonEmpty.groupBy,
which provides type-level guarantees of non-emptiness of inner lists.
\mathcal{O}(n). The insert function takes an element and a list and
inserts the element into the list at the first position where it is less than
or equal to the next element. In particular, if the list is sorted before the
call, the result will also be sorted. It is a special case of insertBy,
which allows the programmer to supply their own comparison function.
The intersect function takes the list intersection of two lists.
It is a special case of intersectBy, which allows the programmer to
supply their own equality test.
Examples
Example1 expression
>>> [1,2,3,4] `intersect` [2,4,6,8][2,4]
If equal elements are present in both lists, an element from the first list
will be used, and all duplicates from the second list quashed:
If the second list is infinite, intersect either hangs
or returns its first argument in full. Otherwise if the first list
is infinite, intersect might be productive:
The intersectBy function is the non-overloaded version of intersect.
It is productive for infinite arguments only if the first one
is a subset of the second.
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 . linesidempotent:
\mathcal{O}(n^2). The nub function removes duplicate elements from a
list. In particular, it keeps only the first occurrence of each element. (The
name nub means `essence'.) It is a special case of nubBy, which allows
the programmer to supply their own equality test.
If there exists instance Ord a, it's faster to use nubOrd from the containers package
(link to the latest online documentation),
which takes only \mathcal{O}(n \log d) time where d is the number of
distinct elements in the list.
Another approach to speed up nub is to use
mapData.List.NonEmpty.head . Data.List.NonEmpty.group . sort,
which takes \mathcal{O}(n \log n) time, requires instance Ord a and doesn't
preserve the order.
The partition function takes a predicate and a list, and returns
the pair of lists of elements which do and do not satisfy the
predicate, respectively; i.e.,
partition p xs == (filter p xs, filter (not . p) xs)
The permutations function is maximally lazy:
for each n, the value of permutations xs starts with those permutations
that permute take n xs and keep drop n xs.
The sort function implements a stable sorting algorithm.
It is a special case of sortBy, which allows the programmer to supply
their own comparison function.
Elements are arranged from lowest to highest, keeping duplicates in
the order they appeared in the input.
The sortBy function is the non-overloaded version of sort.
The argument must be finite.
The supplied comparison relation is supposed to be reflexive and antisymmetric,
otherwise, e. g., for _ _ -> GT, the ordered list simply does not exist.
The relation is also expected to be transitive: if it is not then sortBy
might fail to find an ordered permutation, even if it exists.
Examples
Example1 expression
>>> sortBy (\(a,_) (b,_) -> compare a b) [(2, "world"), (4, "!"), (1, "Hello")][(1,"Hello"),(2,"world"),(4,"!")]
Sort a list by comparing the results of a key function applied to each
element. sortOn f is equivalent to sortBy (comparing f), but has the
performance advantage of only evaluating f once for each element in the
input list. This is called the decorate-sort-undecorate paradigm, or
Schwartzian transform.
Elements are arranged from lowest to highest, keeping duplicates in
the order they appeared in the input.
\mathcal{O}(\min(m,n)). The stripPrefix function drops the given
prefix from a list. It returns Nothing if the list did not start with the
prefix given, or Just the list after the prefix, if it does.
The unfoldr function is a `dual' to foldr: while foldr
reduces a list to a summary value, unfoldr builds a list from
a seed value. The function takes the element and returns Nothing
if it is done producing the list or returns Just(a,b), in which
case, a is a prepended to the list and b is used as the next
element in a recursive call. For example,
iterate f == unfoldr (\x -> Just (x, f x))
In some cases, unfoldr can undo a foldr operation:
unfoldr f' (foldr f z xs) == xs
if the following holds:
f' (f x y) = Just (x,y)
f' z = Nothing
Laziness
Example1 expression
>>> take 1 (unfoldr (\x -> Just (x, undefined)) 'a')"a"
Examples
Example1 expression
>>> unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10[10,9,8,7,6,5,4,3,2,1]
Example1 expression
>>> take 10 $ unfoldr (\(x, y) -> Just (x, (y, x + y))) (0, 1)[0,1,1,2,3,5,8,13,21,54]
The union function returns the list union of the two lists.
It is a special case of unionBy, which allows the programmer to supply
their own equality test.
Examples
Example1 expression
>>> "dog" `union` "cow""dogcw"
If equal elements are present in both lists, an element from the first list
will be used. If the second list contains equal elements, only the first one
will be retained:
words breaks a string up into a list of words, which were delimited
by white space (as defined by isSpace). This function trims any white spaces
at the beginning and at the end.
Examples
Example1 expression
>>> words "Lorem ipsum\ndolor"["Lorem","ipsum","dolor"]
The zip4 function takes four lists and returns a list of
quadruples, analogous to zip.
It is capable of list fusion, but it is restricted to its
first list argument and its resulting list.
The zip5 function takes five lists and returns a list of
five-tuples, analogous to zip.
It is capable of list fusion, but it is restricted to its
first list argument and its resulting list.
The zip6 function takes six lists and returns a list of six-tuples,
analogous to zip.
It is capable of list fusion, but it is restricted to its
first list argument and its resulting list.
The zip7 function takes seven lists and returns a list of
seven-tuples, analogous to zip.
It is capable of list fusion, but it is restricted to its
first list argument and its resulting list.
vvaluezipWith4 :: (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e]
The zipWith4 function takes a function which combines four
elements, as well as four lists and returns a list of their point-wise
combination, analogous to zipWith.
It is capable of list fusion, but it is restricted to its
first list argument and its resulting list.
The zipWith5 function takes a function which combines five
elements, as well as five lists and returns a list of their point-wise
combination, analogous to zipWith.
It is capable of list fusion, but it is restricted to its
first list argument and its resulting list.
The zipWith6 function takes a function which combines six
elements, as well as six lists and returns a list of their point-wise
combination, analogous to zipWith.
It is capable of list fusion, but it is restricted to its
first list argument and its resulting list.
The zipWith7 function takes a function which combines seven
elements, as well as seven lists and returns a list of their point-wise
combination, analogous to zipWith.
It is capable of list fusion, but it is restricted to its
first list argument and its resulting list.
Function for ensuring the value a is within the inclusive bounds given by
low and high. If it is, a is returned unchanged. The result
is otherwise low if a <= low, or high if high <= a.
When clamp is used at Double and Float, it has NaN propagating semantics in
its second argument. That is, clamp (l,h) NaN = NaN, but clamp (NaN, NaN)
x = x.
asProxyTypeOf is a type-restricted version of const.
It is usually used as an infix operator, and its typing forces its first
argument (which is usually overloaded) to have the same type as the tag
of the second.
Note the lower-case proxy in the definition. This allows any type
constructor with just one argument to be passed to the function, for example
we could also write
Be warned that modifySTRef does not apply the function strictly. This
means if the program calls modifySTRef many times, but seldom uses the
value, thunks will pile up in memory resulting in a space leak. This is a
common mistake made when using an STRef as a counter. For example, the
following will leak memory and may produce a stack overflow:
This function may be used as a value for fmap in a Functor
instance, provided that traverse is defined. (Using
fmapDefault with a Traversable instance defined only by
sequenceA will result in infinite recursion.)
The mapAccumL function behaves like a combination of fmap
and foldl; it applies a function to each element of a structure,
passing an accumulating parameter from left to right, and returning
a final value of this accumulator together with the new structure.
Examples
Basic usage:
Example1 expression
>>> mapAccumL (\a b -> (a + b, a)) 0 [1..10](55,[0,1,3,6,10,15,21,28,36,45])
Example1 expression
>>> mapAccumL (\a b -> (a <> show b, a)) "0" [1..5]("012345",["0","01","012","0123","01234"])
The mapAccumM function behaves like a combination of mapM and
mapAccumL that traverses the structure while evaluating the actions
and passing an accumulating parameter from left to right.
It returns a final value of this accumulator together with the new structure.
The accumulator is often used for caching the intermediate results of a computation.
Examples
Basic usage:
Example2 expressions
>>> let expensiveDouble a = putStrLn ("Doubling " <> show a) >> pure (2 * a)>>> :{mapAccumM (\cache a -> case lookup a cache of Nothing -> expensiveDouble a >>= \double -> pure ((a, double):cache, double) Just double -> pure (cache, double) ) [] [1, 2, 3, 1, 2, 3]:}Doubling 1Doubling 2Doubling 3([(3,6),(2,4),(1,2)],[2,4,6,2,4,6])
The mapAccumR function behaves like a combination of fmap
and foldr; it applies a function to each element of a structure,
passing an accumulating parameter from right to left, and returning
a final value of this accumulator together with the new structure.
Examples
Basic usage:
Example1 expression
>>> mapAccumR (\a b -> (a + b, a)) 0 [1..10](55,[54,52,49,45,40,34,27,19,10,0])
Example1 expression
>>> mapAccumR (\a b -> (a <> show b, a)) "0" [1..5]("054321",["05432","0543","054","05","0"])
Applies a type to a function type. Returns: Just u if the first argument
represents a function of type t -> u and the second argument represents a
function of type t. Otherwise, returns Nothing.
Creates a new object of type Unique. The value returned will
not compare equal to any other value of type Unique returned by
previous calls to newUnique. There is no limit on the number of
times newUnique may be called.
Provides one possible concrete representation for Version. For
a version with versionBranch= [1,2,3] and versionTags= ["tag1","tag2"], the output will be 1.2.3-tag1-tag2.
The traceEvent function behaves like trace with the difference that
the message is emitted to the eventlog, if eventlog profiling is available
and enabled at runtime.
It is suitable for use in pure code. In an IO context use traceEventIO
instead.
Note that when using GHC's SMP runtime, it is possible (but rare) to get
duplicate events emitted if two CPUs simultaneously evaluate the same thunk
that uses traceEvent.
Like trace but returning unit in an arbitrary Applicative context. Allows
for convenient use in do-notation.
Note that the application of traceM is not an action in the Applicative
context, as traceIO is in the IO type. While the fresh bindings in the
following example will force the traceM expressions to be reduced every time
the do-block is executed, traceM "not crashed" would only be reduced once,
and the message would only be printed once. If your monad is in
MonadIO, liftIO . traceIO
may be a better option.
Example1 expression
>>> :{do x <- Just 3 traceM ("x: " ++ show x) y <- pure 12 traceM ("y: " ++ show y) pure (x*2 + y):}x: 3y: 12Just 18
The traceMarker function emits a marker to the eventlog, if eventlog
profiling is available and enabled at runtime. The String is the name of
the marker. The name is just used in the profiling tools to help you keep
clear which marker is which.
This function is suitable for use in pure code. In an IO context use
traceMarkerIO instead.
Note that when using GHC's SMP runtime, it is possible (but rare) to get
duplicate events emitted if two CPUs simultaneously evaluate the same thunk
that uses traceMarker.
Like trace, but uses show on the argument to convert it to a String.
This makes it convenient for printing the values of interesting variables or
expressions inside a function. For example, here we print the values of the
variables x and y:
Example1 expression
>>> let f x y = traceShow ("x", x, "y", y) (x + y) in f (1+2) 5("x",3,"y",5)8
Note in this example we also create simple labels just by including some strings.
like trace, but additionally prints a call stack if one is
available.
In the current GHC implementation, the call stack is only
available if the program was compiled with -prof; otherwise
traceStack behaves exactly like trace. Entries in the call
stack correspond to SCC annotations, so it is a good idea to use
-fprof-auto or -fprof-auto-calls to add SCC annotations automatically.
A special case of error.
It is expected that compilers will recognize this and insert error
messages which are more appropriate to the context in which undefined
appears.
The groupWith function uses the user supplied function which
projects an element out of every list element in order to first sort the
input list and then to form groups by equality on these projected elements
The sortWith function sorts a list of elements using the
user supplied function to project something out of each element
In general if the user supplied function is expensive to compute then
you should probably be using sortOn, as it only needs
to compute it once for each element. sortWith, on the other hand
must compute the mapping function for every comparison that it performs.
Show a signed RealFloat value to full precision
using standard decimal notation for arguments whose absolute value lies
between 0.1 and 9,999,999, and scientific notation otherwise.
This function is similar to mallocArray,
but yields a memory area that has a finalizer attached that releases
the memory area. As with mallocForeignPtr, it is not guaranteed that
the block of memory was allocated by malloc.
This function is similar to mallocArray0,
but yields a memory area that has a finalizer attached that releases
the memory area. As with mallocForeignPtr, it is not guaranteed that
the block of memory was allocated by malloc.
Turns a plain memory reference into a foreign pointer, and
associates a finalizer with the reference. The finalizer will be
executed after the last reference to the foreign object is dropped.
There is no guarantee of promptness, however the finalizer will be
executed before the program exits.
This variant of newForeignPtr adds a finalizer that expects an
environment in addition to the finalized pointer. The environment
that will be passed to the finalizer is fixed by the second argument to
newForeignPtrEnv.
Release the storage associated with the given FunPtr, which
must have been obtained from a wrapper stub. This should be called
whenever the return value from a foreign import wrapper function is
no longer required; otherwise, the storage it uses will leak.
This function adds a finalizer to the given foreign object. The
finalizer will run before all other finalizers for the same
object which have already been registered.
Causes the finalizers associated with a foreign pointer to be run
immediately. The foreign pointer must not be used again after this
function is called. If the foreign pointer does not support finalizers,
this is a no-op.
although it may be implemented differently internally: you may not
assume that the memory returned by mallocForeignPtr has been
allocated with malloc.
GHC notes: mallocForeignPtr has a heavily optimised
implementation in GHC. It uses pinned memory in the garbage
collected heap, so the ForeignPtr does not require a finalizer to
free the memory. Use of mallocForeignPtr and associated
functions is strongly recommended in preference to
newForeignPtr with a finalizer.
Advances the given address by the given offset in bytes.
The new ForeignPtr shares the finalizer of the original,
equivalent from a finalization standpoint to just creating another
reference to the original. That is, the finalizer will not be
called before the new ForeignPtr is unreachable, nor will it be
called an additional time due to this call, and the finalizer will
be called with the same address that it would have had this call
not happened, *not* the new address.
This function ensures that the foreign object in
question is alive at the given place in the sequence of IO
actions. However, this comes with a significant caveat: the contract above
does not hold if GHC can demonstrate that the code preceding
touchForeignPtr diverges (e.g. by looping infinitely or throwing an
exception). For this reason, you are strongly advised to use instead
withForeignPtr where possible.
Also, note that this function should not be used to express dependencies
between finalizers on ForeignPtrs. For example, if the finalizer for a
ForeignPtrF1 calls touchForeignPtr on a second ForeignPtrF2,
then the only guarantee is that the finalizer for F2 is never started
before the finalizer for F1. They might be started together if for
example both F1 and F2 are otherwise unreachable, and in that case the
scheduler might end up running the finalizer for F2 first.
In general, it is not recommended to use finalizers on separate
objects with ordering constraints between them. To express the
ordering robustly requires explicit synchronisation using MVars
between the finalizers, but even then the runtime sometimes runs
multiple finalizers sequentially in a single thread (for
performance reasons), so synchronisation between finalizers could
result in artificial deadlock. Another alternative is to use
explicit reference counting.
This is a way to look at the pointer living inside a
foreign object. This function takes a function which is
applied to that pointer. The resulting IO action is then
executed. The foreign object is kept alive at least during
the whole action, even if it is not used directly
inside. Note that it is not safe to return the pointer from
the action and use it after the action completes. All uses
of the pointer should be inside the
withForeignPtr bracket. The reason for
this unsafeness is the same as for
unsafeForeignPtrToPtr below: the finalizer
may run earlier than expected, because the compiler can only
track usage of the ForeignPtr object, not
a Ptr object made from it.
This function is normally used for marshalling data to
or from the object pointed to by the
ForeignPtr, using the operations from the
Storable class.
This is the simplest of the exception-catching functions. It
takes a single argument, runs it, and if an exception is raised
the "handler" is executed, with the value of the exception passed as an
argument. Otherwise, the result is returned as normal. For example:
catch (readFile f)
(\e -> do let err = show (e :: IOException)
hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err)
return "")
Note that we have to give a type signature to e, or the program
will not typecheck as the type is ambiguous. While it is possible
to catch exceptions of any type, see the section "Catching all
exceptions" (in Control.Exception) for an explanation of the problems with doing so.
For catching exceptions in pure (non-IO) expressions, see the
function evaluate.
Note that due to Haskell's unspecified evaluation order, an
expression may throw one of several possible exceptions: consider
the expression (error "urk") + (1 `div` 0). Does
the expression throw
ErrorCall "urk", or DivideByZero?
The answer is "it might throw either"; the choice is
non-deterministic. If you are catching any type of exception then you
might catch either. If you are calling catch with type
IO Int -> (ArithException -> IO Int) -> IO Int then the handler may
get run with DivideByZero as an argument, or an ErrorCall "urk"
exception may be propagated further up. If you call it again, you
might get the opposite behaviour. This is ok, because catch is an
IO computation.
evaluate is typically used to uncover any exceptions that a lazy value
may contain, and possibly handle them.
evaluate only evaluates to weak head normal form. If deeper
evaluation is needed, the force function from Control.DeepSeq
may be handy:
evaluate $ force x
There is a subtle difference between evaluate x and return$! x,
analogous to the difference between throwIO and throw. If the lazy
value x throws an exception, return$! x will fail to return an
IO action and will throw an exception instead. evaluate x, on the
other hand, always produces an IO action; that action will throw an
exception upon execution iff x throws an exception upon evaluation.
The practical implication of this difference is that due to the
imprecise exceptions semantics,
(return $! error "foo") >> error "bar"
may throw either "foo" or "bar", depending on the optimizations
performed by the compiler. On the other hand,
evaluate (error "foo") >> error "bar"
is guaranteed to throw "foo".
The rule of thumb is to use evaluate to force or handle exceptions in
lazy values. If, on the other hand, you are forcing a lazy value for
efficiency reasons only and do not care about exceptions, you may
use return$! x.
Executes an IO computation with asynchronous
exceptions masked. That is, any thread which attempts to raise
an exception in the current thread with throwTo
will be blocked until asynchronous exceptions are unmasked again.
The argument passed to mask is a function that takes as its
argument another function, which can be used to restore the
prevailing masking state within the context of the masked
computation. For example, a common way to use mask is to protect
the acquisition of a resource:
mask $ \restore -> do
x <- acquire
restore (do_something_with x) `onException` release
release
This code guarantees that acquire is paired with release, by masking
asynchronous exceptions for the critical parts. (Rather than write
this code yourself, it would be better to use
bracket which abstracts the general pattern).
Note that the restore action passed to the argument to mask
does not necessarily unmask asynchronous exceptions, it just
restores the masking state to that of the enclosing context. Thus
if asynchronous exceptions are already masked, mask cannot be used
to unmask exceptions again. This is so that if you call a library function
with exceptions masked, you can be sure that the library call will not be
able to unmask exceptions again. If you are writing library code and need
to use asynchronous exceptions, the only way is to create a new thread;
see forkIOWithUnmask.
Asynchronous exceptions may still be received while in the masked
state if the masked thread blocks in certain ways; see
Control.Exception#interruptible.
Threads created by forkIO inherit the
MaskingState from the parent; that is, to start a thread in the
MaskedInterruptible state,
use mask_ $ forkIO .... This is particularly useful if you need
to establish an exception handler in the forked thread before any
asynchronous exceptions are received. To create a new thread in
an unmasked state use forkIOWithUnmask.
Embed a strict state thread in an IO
action. The RealWorld parameter indicates that the internal state
used by the ST computation is a special one supplied by the IO
monad, and thus distinct from those used by invocations of runST.
A variant of throw that can only be used within the IO monad.
Although throwIO has a type that is an instance of the type of throw, the
two functions are subtly different:
throw e `seq` () ===> throw e
throwIO e `seq` () ===> ()
The first example will cause the exception e to be raised,
whereas the second one won't. In fact, throwIO will only cause
an exception to be raised when it is used within the IO monad.
The throwIO variant should be used in preference to throw to
raise an exception within the IO monad because it guarantees
ordering with respect to other operations, whereas throw
does not. We say that throwIO throws *precise* exceptions and
throw, error, etc. all throw *imprecise* exceptions.
For example
throw e + error "boom" ===> error "boom"
throw e + error "boom" ===> throw e
are both valid reductions and the compiler may pick any (loop, even), whereas
throwIO e >> error "boom" ===> throwIO e
will always throw e when executed.
See also the
GHC wiki page on precise exceptions
for a more technical introduction to how GHC optimises around precise vs.
imprecise exceptions.
Like mask, but the masked computation is not interruptible (see
Control.Exception#interruptible). THIS SHOULD BE USED WITH
GREAT CARE, because if a thread executing in uninterruptibleMask
blocks for any reason, then the thread (and possibly the program,
if this is the main thread) will be unresponsive and unkillable.
This function should only be necessary if you need to mask
exceptions around an interruptible operation, and you can guarantee
that the interruptible operation will only block for a short period
of time.
Computation hClosehdl makes handle hdl closed. Before the
computation finishes, if hdl is writable its buffer is flushed as
for hFlush.
Performing hClose on a handle that has already been closed has no effect;
doing so is not an error. All other operations on a closed handle will fail.
If hClose fails for any reason, any further operations (apart from
hClose) on the handle will still fail as if hdl had been successfully
closed.
hClose is an interruptible operation in the sense described in
Control.Exception. If hClose is interrupted by an asynchronous
exception in the process of flushing its buffers, then the I/O device
(e.g., file) will be closed anyway.
This version of unsafePerformIO is more efficient
because it omits the check that the IO is only being performed by a
single thread. Hence, when you use unsafeDupablePerformIO,
there is a possibility that the IO action may be performed multiple
times (on a multiprocessor), and you should therefore ensure that
it gives the same results each time. It may even happen that one
of the duplicated IO actions is only run partially, and then interrupted
in the middle without an exception being raised. Therefore, functions
like bracket cannot be used safely within
unsafeDupablePerformIO.
unsafeInterleaveIO allows an IO computation to be deferred lazily.
When passed a value of type IO a, the IO will only be performed
when the value of the a is demanded. This is used to implement lazy
file reading, see GHC.Internal.System.IO.hGetContents.
This is the "back door" into the IO monad, allowing
IO computation to be performed at any time. For
this to be safe, the IO computation should be
free of side effects and independent of its environment.
If the I/O computation wrapped in unsafePerformIO performs side
effects, then the relative order in which those side effects take
place (relative to the main I/O trunk, or other calls to
unsafePerformIO) is indeterminate. Furthermore, when using
unsafePerformIO to cause side-effects, you should take the following
precautions to ensure the side effects are performed as many times as
you expect them to be. Note that these precautions are necessary for
GHC, but may not be sufficient, and other compilers may require
different precautions:
Use {-# NOINLINE foo #-} as a pragma on any function foo
that calls unsafePerformIO. If the call is inlined,
the I/O may be performed more than once.
Use the compiler flag -fno-cse to prevent common sub-expression
elimination being performed on the module, which might combine
two side effects that were meant to be separate. A good example
is using multiple global variables (like test in the example below).
Make sure that the either you switch off let-floating (-fno-full-laziness), or that the
call to unsafePerformIO cannot float outside a lambda. For example,
if you say:
f x = unsafePerformIO (newIORef [])
you may get only one reference cell shared between all calls to f.
Better would be
f x = unsafePerformIO (newIORef [x])
because now it can't float outside the lambda.
It is less well known that
unsafePerformIO is not type safe. For example:
test :: IORef [a]
test = unsafePerformIO $ newIORef []
main = do
writeIORef test [42]
bang <- readIORef test
print (bang :: [Char])
This program will core dump. This problem with polymorphic references
is well known in the ML community, and does not arise with normal
monadic use of references. There is no easy way to make it impossible
once you use unsafePerformIO. Indeed, it is
possible to write coerce :: a -> b with the
help of unsafePerformIO. So be careful!
WARNING: If you're looking for "a way to get a String from an 'IO String'",
then unsafePerformIO is not the way to go. Learn about do-notation and the
<- syntax element before you proceed.
A strict version of atomicModifyIORef. This forces both the
value stored in the IORef and the value returned.
Conceptually,
atomicModifyIORef' ref f = do
-- Begin atomic block
old <- readIORef ref
let r = f old
new = fst r
writeIORef ref new
-- End atomic block
case r of
(!_new, !res) -> pure res
The actions in the "atomic block" are not subject to interference
by other threads. In particular, the value in the IORef cannot
change between the readIORef and writeIORef invocations.
The new value is installed in the IORef before either value is forced.
So
atomicModifyIORef' ref (x -> (x+1, undefined))
will increment the IORef and then throw an exception in the calling
thread.
atomicModifyIORef' ref (x -> (undefined, x))
and
atomicModifyIORef' ref (_ -> undefined)
will each raise an exception in the calling thread, but will also
install the bottoming value in the IORef, where it may be read by
other threads.
This function imposes a memory barrier, preventing reordering around
the "atomic block"; see Data.IORef#memmodel for details.
This function does not create a memory barrier and can be reordered
with other independent reads and writes within a thread, which may cause issues
for multithreaded execution. In these cases, consider using atomicWriteIORef
instead. See Data.IORef#memmodel for more details.
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 satisfyp and second element is the remainder of the list:
This is a partial function, it throws an error on empty lists. Use pattern matching, uncons or listToMaybe instead. Consider refactoring to use Data.List.NonEmpty.
\mathcal{O}(1). Extract the first element of a list, which must be non-empty.
To disable the warning about partiality put {-# OPTIONS_GHC -Wno-x-partial -Wno-unrecognised-warning-flags #-}
at the top of the file. To disable it throughout a package put the same
options into ghc-options section of Cabal file. To disable it in GHCi
put :set -Wno-x-partial -Wno-unrecognised-warning-flags into ~/.ghci config file.
See also the migration guide.
Examples
Example1 expression
>>> head [1, 2, 3]1
Example1 expression
>>> head [1..]1
Example1 expression
>>> head []*** Exception: Prelude.head: empty list
iteratef x returns an infinite list of repeated applications
of f to x:
iterate f x == [x, f x, f (f x), ...]
Laziness
Note that iterate is lazy, potentially leading to thunk build-up if
the consumer doesn't force each iterate. See iterate' for a strict
variant of this function.
Example1 expression
>>> take 1 $ iterate undefined 42[42]
Examples
Example1 expression
>>> take 10 $ iterate not True[True,False,True,False,True,False,True,False,True,False]
Example1 expression
>>> take 10 $ iterate (+3) 42[42,45,48,51,54,57,60,63,66,69]
replicaten 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.
\mathcal{O}(n). scanr is the right-to-left dual of scanl. Note that the order of parameters on the accumulating function are reversed compared to scanl.
Also note that
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:
This is a partial function, it throws an error on empty lists. Replace it with drop 1, or use pattern matching or uncons instead. Consider refactoring to use Data.List.NonEmpty.
\mathcal{O}(1). Extract the elements after the head of a list, which
must be non-empty.
To disable the warning about partiality put {-# OPTIONS_GHC -Wno-x-partial -Wno-unrecognised-warning-flags #-}
at the top of the file. To disable it throughout a package put the same
options into ghc-options section of Cabal file. To disable it in GHCi
put :set -Wno-x-partial -Wno-unrecognised-warning-flags into ~/.ghci config file.
See also the migration guide.
Examples
Example1 expression
>>> tail [1, 2, 3][2,3]
Example1 expression
>>> tail [1][]
Example1 expression
>>> tail []*** Exception: Prelude.tail: empty list
zip3 takes three lists and returns a list of triples, analogous to
zip.
It is capable of list fusion, but it is restricted to its
first list argument and its resulting list.
vvaluezipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
\mathcal{O}(\min(l,m,n)). The zipWith3 function takes a function which combines three
elements, as well as three lists and returns a list of the function applied
to corresponding elements, analogous to zipWith.
It is capable of list fusion, but it is restricted to its
first list argument and its resulting list.
zipWith3 (,,) xs ys zs == zip3 xs ys zs
zipWith3 f [x1,x2,x3..] [y1,y2,y3..] [z1,z2,z3..] == [f x1 y1 z1, f x2 y2 z2, f x3 y3 z3..]
Examples
Example1 expression
>>> zipWith3 (\x y z -> [x, y, z]) "123" "abc" "xyz"["1ax","2by","3cz"]
Example1 expression
>>> zipWith3 (\x y z -> (x * y) + z) [1, 2, 3] [4, 5, 6] [7, 8, 9][11,18,27]
Notice that the boolean value returned is just a snapshot of
the state of the MVar. By the time you get to react on its result,
the MVar may have been filled (or emptied) - so be extremely
careful when using this operation. Use tryTakeMVar instead if possible.
Make a StablePtr that can be passed to the C function
hs_try_putmvar(). The RTS wants a StablePtr to the
underlying MVar#, but a StablePtr# can only refer to
lifted types, so we have to cheat by coercing.
Put a value into an MVar. If the MVar is currently full,
putMVar will wait until it becomes empty.
There are two further important properties of putMVar:
putMVar is single-wakeup. That is, if there are multiple
threads blocked in putMVar, and the MVar becomes empty,
only one thread will be woken up. The runtime guarantees that
the woken thread completes its putMVar operation.
When multiple threads are blocked on an MVar, they are
woken up in FIFO order. This is useful for providing
fairness properties of abstractions built using MVars.
Atomically read the contents of an MVar. If the MVar is
currently empty, readMVar will wait until it is full.
readMVar is guaranteed to receive the next putMVar.
readMVar is multiple-wakeup, so when multiple readers are
blocked on an MVar, all of them are woken up at the same time.
The runtime guarantees that all woken threads complete their readMVar operation.
Compatibility note: Prior to base 4.7, readMVar was a combination
of takeMVar and putMVar. This mean that in the presence of
other threads attempting to putMVar, readMVar could block.
Furthermore, readMVar would not receive the next putMVar if there
was already a pending thread blocked on takeMVar. The old behavior
can be recovered by implementing 'readMVar as follows:
readMVar :: MVar a -> IO a
readMVar m =
mask_ $ do
a <- takeMVar m
putMVar m a
return a
Return the contents of the MVar. If the MVar is currently
empty, takeMVar will wait until it is full. After a takeMVar,
the MVar is left empty.
There are two further important properties of takeMVar:
takeMVar is single-wakeup. That is, if there are multiple
threads blocked in takeMVar, and the MVar becomes full,
only one thread will be woken up. The runtime guarantees that
the woken thread completes its takeMVar operation.
When multiple threads are blocked on an MVar, they are
woken up in FIFO order. This is useful for providing
fairness properties of abstractions built using MVars.
A non-blocking version of putMVar. The tryPutMVar function
attempts to put the value a into the MVar, returning True if
it was successful, or False otherwise.
A non-blocking version of readMVar. The tryReadMVar function
returns immediately, with Nothing if the MVar was empty, or
Just a if the MVar was full with contents a.
Because - is treated specially in the Haskell grammar,
(-e) is not a section, but an application of prefix negation.
However, (subtractexp) is equivalent to the disallowed section.
Reads an unsignedRealFrac value,
expressed in decimal scientific notation.
Note that this function takes time linear in the magnitude of its input
which can scale exponentially with input size (e.g. "1e100000000" is a
very large number while having a very small textual form).
For this reason, users should take care to avoid using this function on
untrusted input. Users needing to parse floating point values
(e.g. Float) are encouraged to instead use read, which does
not suffer from this issue.
Show a signed RealFloat value
using scientific (exponential) notation (e.g. 2.45e2, 1.5e-3).
In the call showEFloat digs val, if digs is Nothing,
the value is shown to full precision; if digs is Just d,
then at most d digits after the decimal point are shown.
Show a signed RealFloat value
using standard decimal notation (e.g. 245000, 0.0015).
In the call showFFloat digs val, if digs is Nothing,
the value is shown to full precision; if digs is Just d,
then at most d digits after the decimal point are shown.
Show a signed RealFloat value
using standard decimal notation for arguments whose absolute value lies
between 0.1 and 9,999,999, and scientific notation otherwise.
In the call showGFloat digs val, if digs is Nothing,
the value is shown to full precision; if digs is Just d,
then at most d digits after the decimal point are shown.
Show a signed RealFloat value
using standard decimal notation for arguments whose absolute value lies
between 0.1 and 9,999,999, and scientific notation otherwise.
This behaves as showFFloat, except that a decimal point
is always guaranteed, even if not needed.
Given an arbitrary address and an alignment constraint,
alignPtr yields the next higher address that fulfills the
alignment constraint. An alignment constraint x is fulfilled by
any address divisible by x. This operation is idempotent.
Note: this is valid only on architectures where data and function
pointers range over the same set of addresses, and should only be used
for bindings to external libraries whose interface already relies on
this assumption.
Note: this is valid only on architectures where data and function
pointers range over the same set of addresses, and should only be used
for bindings to external libraries whose interface already relies on
this assumption.
The lex function reads a single lexeme from the input, discarding
initial white space, and returning the characters that constitute the
lexeme. If the input string contains only white space, lex returns a
single successful `lexeme' consisting of the empty string. (Thus
lex "" = [("","")].) If there is no legal lexeme at the
beginning of the input string, lex fails (i.e. returns []).
This lexer is not completely faithful to the Haskell lexical syntax
in the following respects:
Qualified names are not handled properly
Octal and hexadecimal numerics are not recognized as a single token
Read a string representation of a character, using Haskell
source-language escape conventions, and convert it to the character
that it encodes. For example:
gcd x y is the non-negative factor of both x and y of which
every common factor of x and y is also a factor; for example
gcd 4 2 = 2, gcd (-4) 6 = 2, gcd 0 4 = 4. gcd 0 0 = 0.
(That is, the common divisor that is "greatest" in the divisibility
preordering.)
Note: Since for signed fixed-width integer types, absminBound < 0,
the result may be negative if one of the arguments is minBound (and
necessarily is if the other is 0 or minBound) for such types.
Return the value computed by a state thread.
The forall ensures that the internal state used by the ST
computation is inaccessible to the rest of the program.
Convert an Int in the range 0..15 to the corresponding single
digit Char. This function fails on other inputs, and generates
lower-case hexadecimal digits.
Coerce a stable pointer to an address. No guarantees are made about
the resulting value, except that the original stable pointer can be
recovered by castPtrToStablePtr. In particular, the address might not
refer to an accessible memory location and any attempt to pass it to
the member functions of the class Storable leads to
undefined behaviour.
Obtain the Haskell value referenced by a stable pointer, i.e., the
same value that was passed to the corresponding call to
newStablePtr. If the argument to deRefStablePtr has
already been freed using freeStablePtr, the behaviour of
deRefStablePtr is undefined.
Dissolve the association between the stable pointer and the Haskell
value. Afterwards, if the stable pointer is passed to
deRefStablePtr or freeStablePtr, the behaviour is
undefined. However, the stable pointer may still be passed to
castStablePtrToPtr, but the Ptr () value returned
by castStablePtrToPtr, in this case, is undefined (in particular,
it may be nullPtr). Nevertheless, the call
to castStablePtrToPtr is guaranteed not to diverge.
Convert a StableName to an Int. The Int returned is not
necessarily unique; several StableNames may map to the same Int
(in practice however, the chances of this are small, so the result
of hashStableName makes a good hash key).
Computation getProgName returns the name of the program as it was
invoked.
However, this is hard-to-impossible to implement on some non-Unix
OSes, so instead, for maximum portability, we just return the leafname
of the program as invoked. Even then there are some differences
between platforms: on Windows, for example, a program invoked as foo
is probably really FOO.EXE, and that is what getProgName will return.
setEnv name value sets the specified environment variable to value.
Early versions of this function operated under the mistaken belief that
setting an environment variable to the empty string on Windows removes
that environment variable from the environment. For the sake of
compatibility, it adopted that behavior on POSIX. In particular
If you'd like to be able to set environment variables to blank strings,
use setEnv.
Throws IOException if name is the empty string or
contains an equals sign.
Beware that this function must not be executed concurrently
with getEnv, lookupEnv, getEnvironment and such. One thread
reading environment variables at the same time with another one modifying them
can result in a segfault, see
Setenv is not Thread Safe
for discussion.
unsetEnv name removes the specified environment variable from the
environment of the current process.
Throws IOException if name is the empty string or
contains an equals sign.
Beware that this function must not be executed concurrently
with getEnv, lookupEnv, getEnvironment and such. One thread
reading environment variables at the same time with another one modifying them
can result in a segfault, see
Setenv is not Thread Safe
for discussion.
Get an action to query the absolute pathname of the current executable.
If the operating system provides a reliable way to determine the current
executable, return the query action, otherwise return Nothing. The action
is defined on FreeBSD, Linux, MacOS, NetBSD, Solaris, and Windows.
Even where the query action is defined, there may be situations where no
result is available, e.g. if the executable file was deleted while the
program is running. Therefore the result of the query action is a Maybe
FilePath.
Note that for scripts and interactive sessions, the result is the path to
the interpreter (e.g. ghci.)
Note also that while most operating systems return Nothing if the
executable file was deleted/unlinked, some (including NetBSD) return the
original path.
Returns the absolute pathname of the current executable,
or argv[0] if the operating system does not provide a reliable
way query the current executable.
Note that for scripts and interactive sessions, this is the path to
the interpreter (e.g. ghci.)
Since base 4.11.0.0, getExecutablePath resolves symlinks on Windows.
If an executable is launched through a symlink, getExecutablePath
returns the absolute path of the original executable.
If the executable has been deleted, behaviour is ill-defined and
varies by operating system. See executablePath for a more
reliable way to query the current executable.
Computation exitWithcode throws ExitCodecode.
Normally this terminates the program, returning code to the
program's caller.
On program termination, the standard Handles stdout and
stderr are flushed automatically; any other buffered Handles
need to be flushed manually, otherwise the buffered data will be
discarded.
A program that fails in any other way is treated as if it had
called exitFailure.
A program that terminates successfully without calling exitWith
explicitly is treated as if it had called exitWithExitSuccess.
Note: in GHC, exitWith should be called from the main program
thread in order to exit the process. When called from another
thread, exitWith will throw an ExitCode as normal, but the
exception will not cause the process itself to exit.
The computation appendFilefile str function appends the string str,
to the file file.
Note that writeFile and appendFile write a literal string
to a file. To write a value of any printable type, as with print,
use the show function to convert the value to a string first.
main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
The interact function takes a function of type String->String
as its argument. The entire input from the standard input device is
passed to this function as its argument, and the resulting string is
output on the standard output device.
Adds a location description and maybe a file path and file handle
to an IOError. If any of the file handle or file path is not given
the corresponding value in the IOError remains unaltered.
The catchIOError function establishes a handler that receives any
IOError raised in the action protected by catchIOError.
An IOError is caught by
the most recent handler established by one of the exception handling
functions. These handlers are
not selective: all IOErrors are caught. Exception propagation
must be explicitly provided in a handler by re-raising any unwanted
exceptions. For example, in
f = catchIOError g (\e -> if IO.isEOFError e then return [] else ioError e)
the function f returns [] when an end-of-file exception
(cf. isEOFError) occurs in g; otherwise, the
exception is propagated to the next outer handler.
When an exception propagates outside the main program, the Haskell
system prints the associated IOError value and exits the program.
Non-I/O exceptions are not caught by this variant; to catch all
exceptions, use catch from Control.Exception.
An error indicating that an IO operation failed because
one of its arguments is a single-use resource, which is already
being used (for example, opening the same file twice for writing
might give this error).
An error indicating that an IO operation failed because
the operation was not possible.
Any computation which returns an IO result may fail with
isIllegalOperation. In some cases, an implementation will not be
able to distinguish between the possible error causes. In this case
it should fail with isIllegalOperation.
Construct an IOError of the given type where the second argument
describes the error location and the third and fourth argument
contain the file handle and file path of the file involved in the
error if applicable.
I/O error where the operation failed because the resource vanished.
This happens when, for example, attempting to write to a closed
socket or attempting to write to a named pipe that was deleted.
The read function reads input from a string, which must be
completely consumed by the input process. read fails with an error if the
parse is unsuccessful, and it is therefore discouraged from being used in
real applications. Use readMaybe or readEither for safe alternatives.
Example1 expression
>>> read "123" :: Int123
Example1 expression
>>> read "hello" :: Int*** Exception: Prelude.read: no parse
The Unicode general category of the character. This relies on the
Enum instance of GeneralCategory, which must remain in the
same order as the categories are presented in the Unicode
standard.
Selects alphabetic Unicode characters (lower-case, upper-case and
title-case letters, plus letters of caseless scripts and modifiers letters).
This function is equivalent to isLetter.
This function returns True if its argument has one of the
following GeneralCategorys, or False otherwise:
Note that numeric digits outside the ASCII range, as well as numeric
characters which aren't digits, are selected by this function but not by
isDigit. Such characters may be part of identifiers but are not used by
the printer and reader to represent numbers, e.g., Roman numerals like V,
full-width digits like '1' (aka '65297').
This function returns True if its argument has one of the
following GeneralCategorys, or False otherwise:
Note: this predicate does not work for letter-like characters such as:
'ⓐ' (U+24D0 circled Latin small letter a) and
'ⅳ' (U+2173 small Roman numeral four). This is due to selecting only
characters with the GeneralCategoryLowercaseLetter.
Note: this predicate selects characters with the Unicode property
Lowercase, which includes letter-like characters such as:
'ⓐ' (U+24D0 circled Latin small letter a) and
'ⅳ' (U+2173 small Roman numeral four).
These classes are defined in the
Unicode Character Database,
part of the Unicode standard. The same document defines what is
and is not a "Punctuation".
Selects upper-case or title-case alphabetic Unicode characters (letters).
Title case is used by a small number of letter ligatures like the
single-character form of Lj.
Note: this predicate does not work for letter-like characters such as:
'Ⓐ' (U+24B6 circled Latin capital letter A) and
'Ⅳ' (U+2163 Roman numeral four). This is due to selecting only
characters with the GeneralCategoryUppercaseLetter or TitlecaseLetter.
See isUpperCase for a more intuitive predicate. Note that
unlike isUpperCase, isUpper does select title-case characters such as
'Dž' (U+01C5 Latin capital letter d with small letter z with caron) or
'ᾯ' (U+1FAF Greek capital letter omega with dasia and perispomeni and
prosgegrammeni).
Note: this predicate selects characters with the Unicode property
Uppercase, which include letter-like characters such as:
'Ⓐ' (U+24B6 circled Latin capital letter A) and
'Ⅳ' (U+2163 Roman numeral four).
See isUpper for the legacy predicate. Note that
unlike isUpperCase, isUpper does select title-case characters such as
'Dž' (U+01C5 Latin capital letter d with small letter z with caron) or
'ᾯ' (U+1FAF Greek capital letter omega with dasia and perispomeni and
prosgegrammeni).
Convert a letter to the corresponding title-case or upper-case
letter, if any. (Title case differs from upper case only for a small
number of ligature letters.)
Any other character is returned unchanged.
unsafeCoerce coerces a value from one type to another, bypassing the type-checker.
There are several legitimate ways to use unsafeCoerce:
To coerce a lifted type such as Int to Any, put it in a list of Any,
and then later coerce it back to Int before using it.
To produce e.g. (a+b) :~: (b+a) from unsafeCoerce Refl.
Here the two sides really are the same type -- so nothing unsafe is happening
-- but GHC is not clever enough to see it.
In Data.Typeable we have
eqTypeRep :: forall k1 k2 (a :: k1) (b :: k2).
TypeRep a -> TypeRep b -> Maybe (a :~~: b)
eqTypeRep a b
| sameTypeRep a b = Just (unsafeCoerce HRefl)
| otherwise = Nothing
Here again, the unsafeCoerce HRefl is safe, because the two types really
are the same -- but the proof of that relies on the complex, trusted
implementation of Typeable.
(superseded) The "reflection trick", which takes advantage of the fact that in
class C a where { op :: ty }, we can safely coerce between C a and ty
(which have different kinds!) because it's really just a newtype.
Note: there is no guarantee, at all that this behavior will be supported
into perpetuity.
It is now preferred to use withDict in GHC.Magic.Dict, which
is type-safe. See Note [withDict] in GHC.Tc.Instance.Class for details.
(superseded) Casting between two types which have exactly the same structure:
between a newtype of T and T, or between types which differ only
in "phantom" type parameters.
It is now preferred to use coerce from Data.Coerce, which
is type-safe.
Other uses of unsafeCoerce are undefined. In particular, you should not use
unsafeCoerce to cast a T to an algebraic data type D, unless T is also
an algebraic data type. For example, do not cast Int->Int to Bool, even if
you later cast that Bool back to Int->Int before applying it. The reasons
have to do with GHC's internal representation details (for the cognoscenti, data values
can be entered but function closures cannot). If you want a safe type to cast things
to, use Any, which is not an algebraic data type.
Extract the value from a Solo. Very often, values should be extracted
directly using pattern matching, to control just what gets evaluated when.
getSolo is for convenience in situations where that is not the case:
When the result is passed to a strict function, it makes no difference
whether the pattern matching is done on the "outside" or on the
"inside":
Data.Set.insert (getSolo sol) set === case sol of Solo v -> Data.Set.insert v set
A traversal may be performed in Solo in order to control evaluation
internally, while using getSolo to extract the final result. A strict
mapping function, for example, could be defined
map' :: Traversable t => (a -> b) -> t a -> t b
map' f = getSolo . traverse ((Solo $!) . f)
Since we support a generic implementation of hashWithSalt we
cannot also provide a default implementation for that method for
the non-generic instance use case. Instead we provide
defaultHashWith.
Compute a hash value for the content of this ByteArray#, using
an initial salt.
This function can for example be used to hash non-contiguous
segments of memory as if they were one contiguous segment, by using
the output of one hash as the salt for the next.
Compute a hash value for the content of this pointer, using an
initial salt.
This function can for example be used to hash non-contiguous
segments of memory as if they were one contiguous segment, by using
the output of one hash as the salt for the next.
MonadError analogue of the mapExceptT function. The
computation is unwrapped, a function is applied to the Either, and
the result is lifted into the second MonadError instance.
A different MonadError analogue to the withExceptT function.
Modify the value (and possibly the type) of an error in an ExceptT-transformed
monad, while stripping the ExceptT layer.
This is useful for adapting the MonadError constraint of a computation.
For example:
data DatabaseError = ...
performDatabaseQuery :: (MonadError DatabaseError m, ...) => m PersistedValue
data AppError
= MkDatabaseError DatabaseError
| ...
app :: (MonadError AppError m, ...) => m ()
Given these types, performDatabaseQuery cannot be used directly inside
app, because the error types don't match. Using modifyError, an equivalent
function with a different error type can be constructed:
performDatabaseQuery' :: (MonadError AppError m, ...) => m PersistedValue
performDatabaseQuery' = modifyError MkDatabaseError performDatabaseQuery
Since the error types do match, performDatabaseQuery' _can_ be used in app,
assuming all other constraints carry over.
This works by instantiating the m in the type of performDatabaseQuery to
ExceptT DatabaseError m', which satisfies the MonadError DatabaseError
constraint. Immediately, the ExceptT DatabaseError layer is unwrapped,
producing Either a DatabaseError or a PersistedValue. If it's the former,
the error is wrapped in MkDatabaseError and re-thrown in the inner monad,
otherwise the result value is returned.
MonadError analogue to the withExceptT function.
Modify the value (but not the type) of an error. The type is
fixed because of the functional dependency m -> e. If you need
to change the type of e use mapError or modifyError.
An operator alias for select, which is sometimes convenient. It tries to
follow the notational convention for Applicative operators. The angle
bracket pointing to the left means we always use the corresponding value.
The value on the right, however, may be skipped, hence the question mark.
Recover the application operator <*> from select. Rigid selective
functors satisfy the law <*>=apS and furthermore, the resulting
applicative functor satisfies all laws of Applicative:
The branch function is a natural generalisation of select: instead of
skipping an unnecessary effect, it chooses which of the two given effectful
functions to apply to a given argument; the other effect is unnecessary. It
is possible to implement branch in terms of select, which is a good
puzzle (give it a try!).
We can write a function with the type signature of select using the
Applicative type class, but it will always execute the effects associated
with the second argument, hence being potentially less efficient.
For traversable functors, we can implement select in another interesting
way: the effects associated with the second argument can be skipped as long
as the first argument contains only Right values.
Duplicate a TChan: the duplicate channel begins empty, but data written to
either channel from then on will be available from both. Hence this creates
a kind of broadcast channel, where data written by anyone is seen by
everyone else.
Create a write-only TChan. More precisely, readTChan will retry
even after items have been written to the channel. The only way to read
a broadcast channel is to duplicate it with dupTChan.
Consider a server that broadcasts messages to clients:
The problem with using newTChan to create the broadcast channel is that if
it is only written to and never read, items will pile up in memory. By
using newBroadcastTChan to create the broadcast channel, items can be
garbage collected after clients have seen them.
A version of putTMVar that does not retry. The tryPutTMVar
function attempts to put the value a into the TMVar, returning
True if it was successful, or False otherwise.
week of year for Week Date format, 0-padded to two chars,
01
-
53
%U
week of year where weeks start on Sunday (as
sundayStartWeek
), 0-padded to two chars,
00
-
53
%W
week of year where weeks start on Monday (as
mondayStartWeek
), 0-padded to two chars,
00
-
53
Duration types
The specifiers for DiffTime, NominalDiffTime, CalendarDiffDays, and CalendarDiffTime are semantically
separate from the other types.
Specifiers on negative time differences will generally be negative (think rem rather than mod).
NominalDiffTime and DiffTime
Note that a "minute" of DiffTime is simply 60 SI seconds, rather than a minute of civil time.
Use NominalDiffTime to work with civil time, ignoring any leap seconds.
For NominalDiffTime and DiffTime:
%w
total whole weeks
%d
total whole days
%D
whole days of week
%h
total whole hours
%H
whole hours of day
%m
total whole minutes
%M
whole minutes of hour
%s
total whole seconds
%Es
total seconds, with decimal point and up to <width> (default 12) decimal places, without trailing zeros.
For a whole number of seconds,
%Es
omits the decimal point unless padding is specified.
%0Es
total seconds, with decimal point and <width> (default 12) decimal places.
%S
whole seconds of minute
%ES
seconds of minute, with decimal point and up to <width> (default 12) decimal places, without trailing zeros.
For a whole number of seconds,
%ES
omits the decimal point unless padding is specified.
%0ES
seconds of minute as two digits, with decimal point and <width> (default 12) decimal places.
CalendarDiffDays
For CalendarDiffDays (and CalendarDiffTime):
%y
total years
%b
total months
%B
months of year
%w
total weeks, not including months
%d
total days, not including months
%D
days of week
CalendarDiffTime
For CalendarDiffTime:
%h
total hours, not including months
%H
hours of day
%m
total minutes, not including months
%M
minutes of hour
%s
total whole seconds, not including months
%Es
total seconds, not including months, with decimal point and up to <width> (default 12) decimal places, without trailing zeros.
For a whole number of seconds,
%Es
omits the decimal point unless padding is specified.
%0Es
total seconds, not including months, with decimal point and <width> (default 12) decimal places.
%S
whole seconds of minute
%ES
seconds of minute, with decimal point and up to <width> (default 12) decimal places, without trailing zeros.
For a whole number of seconds,
%ES
omits the decimal point unless padding is specified.
%0ES
seconds of minute as two digits, with decimal point and <width> (default 12) decimal places.
knownTimeZones contains only the ten time-zones mentioned in RFC 822 sec. 5:
"UT", "GMT", "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", "PDT".
Note that the parsing functions will regardless parse "UTC", single-letter military time-zones, and +HHMM format.
Parses a time value given a format string.
Missing information will be derived from 1970-01-01 00:00 UTC (which was a Thursday).
Supports the same %-codes as formatTime, including %-, %_ and %0 modifiers, however padding widths are not supported.
Case is not significant in the input string.
Some variations in the input are accepted:
%z%Ez
accepts any of
±HHMM
or
±HH:MM
.
%Z%EZ
accepts any string of letters, or any of the formats accepted by
%z
.
%0Y
accepts exactly four digits.
%0G
accepts exactly four digits.
%0C
accepts exactly two digits.
%0f
accepts exactly two digits.
For example, to parse a date in YYYY-MM-DD format, while allowing the month
and date to have optional leading zeros (notice the - modifier used for %m
and %d):
Prelude Data.Time> parseTimeM True defaultTimeLocale "%Y-%-m-%-d" "2010-3-04" :: Maybe Day
Just 2010-03-04
Apply a function to transform the result of a continuation-passing
computation. This has a more restricted type than the map operations
for other monad transformers, because ContT does not define a functor
in the category of monads.
Monads in which IO computations may be embedded.
Any monad built by applying a sequence of monad transformers to the
IO monad will be an instance of this class.
Instances should satisfy the following laws, which state that liftIO
is a transformer of monads:
Lift a computation from the IO monad.
This allows us to run IO computations in any monadic stack, so long as it supports these kinds of operations
(i.e. IO is the base monad for the stack).
Example
import Control.Monad.Trans.State -- from the "transformers" library
printState :: Show s => StateT s IO ()
printState = do
state <- get
liftIO $ print state
Had we omitted liftIO, we would have ended up with this error:
• Couldn't match type ‘IO’ with ‘StateT s IO’
Expected type: StateT s IO ()
Actual type: IO ()
The important part here is the mismatch between StateT s IO () and IO ().
Luckily, we know of a function that takes an IO a and returns an (m a): liftIO,
enabling us to run the program and see the expected results:
Given a structure with elements whose type is a Semigroup, combine
them via the semigroup's (<>) operator. This fold is
right-associative and lazy in the accumulator. When you need a strict
left-associative fold, use foldMap1' instead, with id as the map.
Map each element of the structure to a semigroup, and combine the
results with (<>). This fold is right-associative and lazy in the
accumulator. For strict left-associative folds consider foldMap1'
instead.
Lifting of the Eq class to unary type constructors.
Any instance should be subject to the following law that canonicity
is preserved:
liftEq (==) = (==)
This class therefore represents the generalization of Eq by
decomposing its main method into a canonical lifting on a canonical
inner method, so that the lifting can be reused for other arguments
than the canonical one.
Lift an equality test through the type constructor.
The function will usually be applied to an equality function,
but the more general type ensures that the implementation uses
it to compare elements of the first container with elements of
the second.
Instances83Eq1, …
Eq1ComplexDefined in base-4.20.2.0 · Data.Functor.Classes
The function will usually be applied to equality functions,
but the more general type ensures that the implementation uses
them to compare elements of the first container with elements of
the second.
Instances21Eq2, …
Eq2MapDefined in containers-0.7 · Data.Map.Internal
Eq2EitherDefined in base-4.20.2.0 · Data.Functor.Classes
Eq2Tuple2Defined in base-4.20.2.0 · Data.Functor.Classes
Eq2HashMapDefined in unordered-containers-0.2.21 · Data.HashMap.Internal
Eq1f => Eq2 (CofreeFf)Defined in free-5.2 · Control.Comonad.Trans.Cofree
Eq1f => Eq2 (FreeFf)Defined in free-5.2 · Control.Monad.Trans.Free
Eq1f => Eq2 (FreeFf)Defined in free-5.2 · Control.Monad.Trans.Free.Ap
Eq2ConstDefined in base-4.20.2.0 · Data.Functor.Classes
This class therefore represents the generalization of Ord by
decomposing its main method into a canonical lifting on a canonical
inner method, so that the lifting can be reused for other arguments
than the canonical one.
Lift a compare function through the type constructor.
The function will usually be applied to a comparison function,
but the more general type ensures that the implementation uses
it to compare elements of the first container with elements of
the second.
Instances81Ord1, …
Ord1IntMapDefined in containers-0.7 · Data.IntMap.Internal
Ord1SeqDefined in containers-0.7 · Data.Sequence.Internal
Ord1SetDefined in containers-0.7 · Data.Set.Internal
Lift compare functions through the type constructor.
The function will usually be applied to comparison functions,
but the more general type ensures that the implementation uses
them to compare elements of the first container with elements of
the second.
Instances21Ord2, …
Ord2MapDefined in containers-0.7 · Data.Map.Internal
Ord2EitherDefined in base-4.20.2.0 · Data.Functor.Classes
Ord2Tuple2Defined in base-4.20.2.0 · Data.Functor.Classes
Ord2HashMapDefined in unordered-containers-0.2.21 · Data.HashMap.Internal
Ord1f => Ord2 (CofreeFf)Defined in free-5.2 · Control.Comonad.Trans.Cofree
Ord1f => Ord2 (FreeFf)Defined in free-5.2 · Control.Monad.Trans.Free
Ord1f => Ord2 (FreeFf)Defined in free-5.2 · Control.Monad.Trans.Free.Ap
Ord2ConstDefined in base-4.20.2.0 · Data.Functor.Classes
This class therefore represents the generalization of Read by
decomposing it's methods into a canonical lifting on a canonical
inner method, so that the lifting can be reused for other arguments
than the canonical one.
Both liftReadsPrec and liftReadPrec exist to match the interface
provided in the Read type class, but it is recommended to implement
Read1 instances using liftReadPrec as opposed to liftReadsPrec, since
the former is more efficient than the latter. For example:
readList function for an application of the type constructor
based on readsPrec and readList functions for the argument type.
The default implementation using standard list syntax is correct
for most types.
Lifting of the Read class to binary type constructors.
Both liftReadsPrec2 and liftReadPrec2 exist to match the interface
provided in the Read type class, but it is recommended to implement
Read2 instances using liftReadPrec2 as opposed to liftReadsPrec2,
since the former is more efficient than the latter. For example:
readList function for an application of the type constructor
based on readsPrec and readList functions for the argument types.
The default implementation using standard list syntax is correct
for most types.
This class therefore represents the generalization of Show by
decomposing it's methods into a canonical lifting on a canonical
inner method, so that the lifting can be reused for other arguments
than the canonical one.
showList function for an application of the type constructor
based on showsPrec and showList functions for the argument type.
The default implementation using standard list syntax is correct
for most types.
Instances78Show1, …
Show1ComplexDefined in base-4.20.2.0 · Data.Functor.Classes
showList function for an application of the type constructor
based on showsPrec and showList functions for the argument types.
The default implementation using standard list syntax is correct
for most types.
Instances20Show2, …
Show2MapDefined in containers-0.7 · Data.Map.Internal
Show2EitherDefined in base-4.20.2.0 · Data.Functor.Classes
Show2Tuple2Defined in base-4.20.2.0 · Data.Functor.Classes
Show2HashMapDefined in unordered-containers-0.2.21 · Data.HashMap.Internal
Show1f => Show2 (CofreeFf)Defined in free-5.2 · Control.Comonad.Trans.Cofree
Show1f => Show2 (FreeFf)Defined in free-5.2 · Control.Monad.Trans.Free
Show1f => Show2 (FreeFf)Defined in free-5.2 · Control.Monad.Trans.Free.Ap
Show2ConstDefined in base-4.20.2.0 · Data.Functor.Classes
Beware that Data.Semigroup.First is different from
Data.Monoid.First. The former simply returns the first value,
so Data.Semigroup.First Nothing <> x = Data.Semigroup.First Nothing.
The latter returns the first non-Nothing,
thus Data.Monoid.First Nothing <> x = x.
Examples
Example1 expression
>>> First 0 <> First 10First 0
Example1 expression
>>> sconcat $ First 1 :| [ First n | n <- [2 ..] ]First 1
Beware that Data.Semigroup.Last is different from
Data.Monoid.Last. The former simply returns the last value,
so x <> Data.Semigroup.Last Nothing = Data.Semigroup.Last Nothing.
The latter returns the last non-Nothing,
thus x <> Data.Monoid.Last Nothing = x.
Examples
Example1 expression
>>> Last 0 <> Last 10Last {getLast = 10}
Example1 expression
>>> sconcat $ Last 1 :| [ Last n | n <- [2..]]Last {getLast = * hangs forever *
NOTE: This is not needed anymore since Semigroup became a superclass of
Monoid in base-4.11 and this newtype be deprecated at some point in the future.
It has a lower memory overhead than a ByteString and does not
contribute to heap fragmentation. It can be converted to or from a
ByteString (at the cost of copying the string data). It supports very few
other operations.
Instances16IsList, Eq, Data, Ord, Read, Show, …
IsListShortByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Short.Internal
EqShortByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Short.Internal
DataShortByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Short.Internal
OrdShortByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Short.Internal
Lexicographic order.
ReadShortByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Short.Internal
ShowShortByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Short.Internal
ComonadApply is to Comonad like Applicative is to Monad.
Mathematically, it is a strong lax symmetric semi-monoidal comonad on the
category Hask of Haskell types. That it to say that w is a strong lax
symmetric semi-monoidal functor on Hask, where both extract and duplicate are
symmetric monoidal natural transformations.
Noting the superclass constraint that f must also be Divisible, a Decidable
functor has the ability to "fan out" input, under the intuition that contravariant
functors consume input.
In the discussion for Divisible, an example was demonstrated with Serializers,
that turn as into ByteStrings. Divisible allowed us to serialize the product
of multiple values by concatenation. By making our Serializer also Decidable-
we now have the ability to serialize the sum of multiple values - for example
different constructors in an ADT.
Consider serializing arbitrary identifiers that can be either Strings or Ints:
data Identifier = StringId String | IntId Int
We know we have serializers for Strings and Ints, but how do we combine them
into a Serializer for Identifier? Essentially, our Serializer needs to
scrutinise the incoming value and choose how to serialize it:
identifier :: Serializer Identifier
identifier = Serializer $ \identifier ->
case identifier of
StringId s -> runSerializer string s
IntId i -> runSerializer int i
It is exactly this notion of choice that Decidable encodes. Hence if we add
an instance of Decidable for Serializer...
instance Decidable Serializer where
lose f = Serializer $ \a -> absurd (f a)
choose split l r = Serializer $ \a ->
either (runSerializer l) (runSerializer r) (split a)
Then our identifierSerializer is
identifier :: Serializer Identifier
identifier = choose toEither string int where
toEither (StringId s) = Left s
toEither (IntId i) = Right i
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
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 !_ = ()
liftRnf should reduce its argument to normal form (that is, fully
evaluate all sub-components), given an argument to reduce a arguments,
and then return ().
liftRnf2 should reduce its argument to normal form (that
is, fully evaluate all sub-components), given functions to
reduce a and b arguments respectively, and then return ().
Note: Unlike for the unary liftRnf, there is currently no
support for generically deriving liftRnf2.
Instances17NFData2, …
NFData2ArgDefined in deepseq-1.5.0.0 · Control.DeepSeq
NFData2ArrayDefined in deepseq-1.5.0.0 · Control.DeepSeq
NFData2EitherDefined in deepseq-1.5.0.0 · Control.DeepSeq
NFData2STRefDefined in deepseq-1.5.0.0 · Control.DeepSeq
NFData2Tuple2Defined in deepseq-1.5.0.0 · Control.DeepSeq
NFData2HashMapDefined in unordered-containers-0.2.21 · Data.HashMap.Internal
NFData2LeafDefined in unordered-containers-0.2.21 · Data.HashMap.Internal
>>> some (putStr "la")lalalalalalalalala... * goes on forever *
Example1 expression
>>> some Nothingnothing
Example1 expression
>>> 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 (putStr "la")lalalalalalalalala... * goes on forever *
Example1 expression
>>> many NothingJust []
Example1 expression
>>> 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.
Instances70Alternative, …
AlternativeGetDefined in binary-0.8.9.3 · Data.Binary.Get.Internal
AlternativeSeqDefined in containers-0.7 · Data.Sequence.Internal
Return the number of bits in the type of the argument.
The actual value of the argument is ignored. Moreover, finiteBitSize
is total, in contrast to the deprecated bitSize function it replaces.
Note: The default implementation for this method is intentionally
naive. However, the instances provided for the primitive
integral types are implemented using CPU specific machine
instructions.
Note: The default implementation for this method is intentionally
naive. However, the instances provided for the primitive
integral types are implemented using CPU specific machine
instructions.
Instances64FiniteBits, …
FiniteBitsEventTypeDefined in ghc-internal-9.1003.0 · GHC.Internal.Event.EPoll
FiniteBitsEventDefined in ghc-internal-9.1003.0 · GHC.Internal.Event.Poll
FiniteBitsCBoolDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsCCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsCIntDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsCIntMaxDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsCIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsCLLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsCLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsCPtrdiffDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsCSCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsCShortDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsCSigAtomicDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsCSizeDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsCUCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsCUIntDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsCUIntMaxDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsCUIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsCULLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsCULongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsCUShortDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsCWcharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
FiniteBitsIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Ptr
FiniteBitsWordPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Ptr
FiniteBitsInt16Defined in ghc-internal-9.1003.0 · GHC.Internal.Int
FiniteBitsInt32Defined in ghc-internal-9.1003.0 · GHC.Internal.Int
FiniteBitsInt64Defined in ghc-internal-9.1003.0 · GHC.Internal.Int
FiniteBitsInt8Defined in ghc-internal-9.1003.0 · GHC.Internal.Int
FiniteBitsCBlkCntDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsCBlkSizeDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsCClockIdDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsCDevDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsCFsBlkCntDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsCFsFilCntDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsCGidDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsCIdDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsCInoDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsCKeyDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsCModeDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsCNfdsDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsCNlinkDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsCOffDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsCPidDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsCRLimDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsCSocklenDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsCSsizeDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsCTcflagDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsCUidDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsFdDefined in ghc-internal-9.1003.0 · GHC.Internal.System.Posix.Types
FiniteBitsWord16Defined in ghc-internal-9.1003.0 · GHC.Internal.Word
FiniteBitsWord32Defined in ghc-internal-9.1003.0 · GHC.Internal.Word
FiniteBitsWord64Defined in ghc-internal-9.1003.0 · GHC.Internal.Word
FiniteBitsWord8Defined in ghc-internal-9.1003.0 · GHC.Internal.Word
FiniteBitsBoolDefined in ghc-internal-9.1003.0 · GHC.Internal.Bits
FiniteBitsIntDefined in ghc-internal-9.1003.0 · GHC.Internal.Bits
FiniteBitsWordDefined in ghc-internal-9.1003.0 · GHC.Internal.Bits
A ThreadId is an abstract type representing a handle to a thread.
ThreadId is an instance of Eq, Ord and Show, where
the Ord instance implements an arbitrary total ordering over
ThreadIds. The Show instance lets you convert an arbitrary-valued
ThreadId to string form; showing a ThreadId value is occasionally
useful when debugging or diagnosing the behaviour of a concurrent
program.
Note: in GHC, if you have a ThreadId, you essentially have
a pointer to the thread itself. This means the thread itself can't be
garbage collected until you drop the ThreadId. This misfeature would
be difficult to correct while continuing to support threadStatus.
The loop operator expresses computations in which an output value
is fed back as input, although the computation occurs only once.
It underlies the rec value recursion construct in arrow notation.
loop should satisfy the following laws:
Beware that for many monads (those for which the >>= operation
is strict) this instance will not satisfy the right-tightening law
required by the ArrowLoop class.
Beware that for many monads (those for which the >>= operation
is strict) this instance will not satisfy the right-tightening law
required by the ArrowLoop class.
A class method without a definition (neither a default definition,
nor a definition in the appropriate instance) was called. The
String gives information about which method it was.
Thrown when the runtime system detects that the computation is
guaranteed not to terminate. Note that there is no guarantee that
the runtime system will notice whether any given computation is
guaranteed to terminate or not.
A record selector was applied to a constructor without the
appropriate field. This can only happen with a datatype with
multiple constructors, where some fields are in one constructor
but not another. The String gives information about the source
location of the record selector.
A record update was performed on a constructor without the
appropriate field. This can only happen with a datatype with
multiple constructors, where some fields are in one constructor
but not another. The String gives information about the source
location of the record update.
An expression that didn't typecheck during compile time was called.
This is only possible with -fdefer-type-errors. The String gives
details about the failed type check.
Representation of constructors. Note that equality on constructors
with different types may not work -- i.e. the constructors for False and
Nothing may compare equal.
Instances2Eq, Show
EqConstrDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Data
Equality of constructors
ShowConstrDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Data
Because we ignore the second type parameter to Const,
the Applicative instance, which has
(<*>) :: Monoid m => Const m (a -> b) -> Const m a -> Const m b
essentially turns into Monoid m => m -> m -> m, which is (<>)
Enum (fa) => Enum (Apfa)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Monoid
Eq (fa) => Eq (Apfa)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Monoid
(Data (fa), Dataa, Typeablef) => Data (Apfa)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Data
(Applicativef, Numa) => Num (Apfa)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Monoid
Note that even if the underlying Num and Applicative instances are
lawful, for most Applicatives, this instance will not be lawful. If you use
this instance with the list Applicative, the following customary laws will
not hold:
Commutativity:
Example2 expressions
>>> Ap [10,20] + Ap [1,2]Ap {getAp = [11,12,21,22]}>>> Ap [1,2] + Ap [10,20]Ap {getAp = [11,21,12,22]}
Additive inverse:
Example2 expressions
>>> Ap [] + negate (Ap [])Ap {getAp = []}>>> fromInteger 0 :: Ap [] IntAp {getAp = [0]}
Distributivity:
Example2 expressions
>>> Ap [1,2] * (3 + 4)Ap {getAp = [7,14]}>>> (Ap [1,2] * 3) + (Ap [1,2] * 4)Ap {getAp = [7,11,10,14]}
Ord (fa) => Ord (Apfa)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Monoid
Read (fa) => Read (Apfa)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Monoid
Show (fa) => Show (Apfa)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Monoid
Generic (Apfa)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Monoid
The Down type allows you to reverse sort order conveniently. A value of type
Down a contains a value of type a (represented as Down a).
If a has an Ord instance associated with it then comparing two
values thus wrapped will give you the opposite of their normal sort order.
This is particularly useful when sorting in generalised list comprehensions,
as in: then sortWith by Down x.
Example1 expression
>>> compare True FalseGT
Example1 expression
>>> compare (Down True) (Down False)LT
If a has a Bounded instance then the wrapped instance also respects
the reversed ordering by exchanging the values of minBound and
maxBound.
Example1 expression
>>> minBound :: Int-9223372036854775808
Example1 expression
>>> minBound :: Down IntDown 9223372036854775807
All other instances of Down a behave as they do for a.
Propositional equality. If a :~: b is inhabited by some terminating
value, then the type a is the same as the type b. To use this equality
in practice, pattern-match on the a :~: b to get out the Refl constructor;
in the body of the pattern-match, the compiler knows that a ~ b.
The Bounded class is used to name the upper and lower limits of a
type. Ord is not a superclass of Bounded since types that are not
totally ordered may also have upper and lower bounds.
The Bounded class may be derived for any enumeration type;
minBound is the first constructor listed in the data declaration
and maxBound is the last.
Bounded may also be derived for single-constructor datatypes whose
constituent types are in Bounded.
Wraps a particular exception exposing its ExceptionContext. Intended to
be used when catching exceptions in cases where access to the context is
desired.
The SomeException type is the root of the exception type hierarchy.
When an exception of type e is thrown, behind the scenes it is
encapsulated in a SomeException.
Trigonometric and hyperbolic functions and related functions.
The Haskell Report defines no laws for Floating. However, (+), (*)
and exp are customarily expected to define an exponential field and have
the following properties:
A signed integral type that can be losslessly converted to and from
Ptr. This type is also compatible with the C99 type intptr_t, and
can be marshalled to and from that type safely.
An unsigned integral type that can be losslessly converted to and from
Ptr. This type is also compatible with the C99 type uintptr_t, and
can be marshalled to and from that type safely.
A finalizer is represented as a pointer to a foreign function that, at
finalisation time, gets as an argument a plain pointer variant of the
foreign pointer that the finalizer is associated with.
Note that the foreign function must either use the ccall or the capi calling convention.
File and directory names are values of type String, whose precise
meaning is operating system dependent. Files can be opened, yielding a
handle which can then be used to operate on the contents of that file.
The current thread's stack exceeded its limit.
Since an exception has been raised, the thread's stack
will certainly be below its limit again, but the
programmer should take remedial action
immediately.
The program's heap is reaching its limit, and
the program should take action to reduce the amount of
live data it has. Notes:
It is undefined which thread receives this exception.
GHC currently throws this to the same thread that
receives UserInterrupt, but this may change in the
future.
The GHC RTS currently can only recover from heap overflow
if it detects that an explicit memory limit (set via RTS flags).
has been exceeded. Currently, failure to allocate memory from
the operating system results in immediate termination of the
program.
This exception is raised by default in the main thread of
the program when the user requests to terminate the program
via the usual mechanism(s) (e.g. Control-C in the console).
Instances4Eq, Ord, Show, Exception
EqAsyncExceptionDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Exception
OrdAsyncExceptionDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Exception
ShowAsyncExceptionDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Exception
indicates program failure with an exit code.
The exact interpretation of the code is
operating-system dependent. In particular, some values
may be prohibited (e.g. 0 on a POSIX-compliant system).
The Haskell 2010 type for exceptions in the IO monad.
Any I/O operation may raise an IOError instead of returning a result.
For a more general type of exception, including also those that arise
in pure code, see Exception.
Exceptions that occur in the IO monad.
An IOException records a more specific error type, a descriptive
string and maybe the handle that was used when the error was
flagged.
The fromListN function takes the input list's length and potentially
uses it to construct the structure l more efficiently compared to
fromList. If the given number does not equal to the input list's length
the behaviour of fromListN is not specified.
The Haskell Report defines no laws for Fractional. However, (+) and
(*) are customarily expected to define a division ring and have the
following properties:
These methods also compute Integer magnitudes (10^e). If these methods
are applied to arguments which have huge exponents this could fill up all
space and crash your program! So don't apply these methods to scientific
numbers coming from untrusted sources.
fromRational will throw an error when the input Rational is a repeating
decimal. Consider using fromRationalRepetend for these rationals which
will detect the repetition and indicate where it starts.
FractionalDiffTimeDefined in time-1.12.2 · Data.Time.Clock.Internal.DiffTime
The Haskell Report defines no laws for Integral. However, Integral
instances are customarily expected to define a Euclidean domain and have the
following properties for the div/mod and quot/rem pairs, given
suitable Euclidean functions f and g:
x = y * quot x y + rem x y with rem x y = fromInteger 0 or
g (rem x y) < g y
x = y * div x y + mod x y with mod x y = fromInteger 0 or
f (mod x y) < f y
An example of a suitable Euclidean function, for Integer's instance, is
abs.
In addition, toInteger should be total, and fromInteger should be a left
inverse for it, i.e. fromInteger (toInteger i) = i.
WARNING: the methods of the RealFrac instance need to compute the
magnitude 10^e. If applied to a huge exponent this could take a long
time. Even worse, when the destination type is unbounded (i.e. Integer) it
could fill up all space and crash your program!
RealFracDiffTimeDefined in time-1.12.2 · Data.Time.Clock.Internal.DiffTime
The shows functions return a function that prepends the
output String to an existing String. This allows constant-time
concatenation of results using function composition.
callCC (call-with-current-continuation)
calls a function with the current continuation as its argument.
Provides an escape continuation mechanism for use with Continuation monads.
Escape continuations allow to abort the current computation and return
a value immediately.
They achieve a similar effect to throwError
and catchError
within an Except monad.
Advantage of this function over calling return is that it makes
the continuation explicit,
allowing more flexibility and better control
(see examples in Control.Monad.Cont).
The standard idiom used with callCC is to provide a lambda-expression
to name the continuation. Then calling the named continuation anywhere
within its scope will escape from the computation,
even if it is many layers deep within nested computations.
The strategy of combining computations that can throw exceptions
by bypassing bound functions
from the point an exception is thrown to the point that it is handled.
Is parameterized over the type of error information and
the monad type constructor.
It is common to use Either String as the monad type constructor
for an error monad in which error descriptions take the form of strings.
In that case and many other common cases the resulting monad is already defined
as an instance of the MonadError class.
You can also define your own error type and/or use a monad type constructor
other than EitherString or EitherIOError.
In these cases you will have to explicitly define instances of the MonadError
class.
(If you are using the deprecated Control.Monad.Error or
Control.Monad.Trans.Error, you may also have to define an Error instance.)
This represents the right Kan lift of a Profunctorq along a
Profunctorp in a limited version of the 2-category of Profunctors where
the only object is the category Hask, 1-morphisms are profunctors composed
and compose with Profunctor composition, and 2-morphisms are just natural
transformations.
Any applicative functor can be given a Selective instance by defining
select=selectA. This data type captures this pattern, so you can use
it in combination with the DerivingVia extension as follows:
newtype Over m a = Over m
deriving (Functor, Applicative, Selective) via SelectA (Const m)
Any monad can be given a Selective instance by defining
select=selectM. This data type captures this pattern, so you can use
it in combination with the DerivingVia extension as follows:
newtype V1 a = V1 a
deriving (Functor, Applicative, Selective, Monad) via SelectM Identity
EnumDayOfWeekDefined in time-1.12.2 · Data.Time.Calendar.Week
"Circular", so for example [Tuesday ..] gives an endless sequence.
Also: fromEnum gives [1 .. 7] for [Monday .. Sunday], and toEnum performs mod 7 to give a cycle of days.
EqDayOfWeekDefined in time-1.12.2 · Data.Time.Calendar.Week
DataDayOfWeekDefined in time-1.12.2 · Data.Time.Calendar.Week
OrdDayOfWeekDefined in time-1.12.2 · Data.Time.Calendar.Week
ReadDayOfWeekDefined in time-1.12.2 · Data.Time.Calendar.Week
ShowDayOfWeekDefined in time-1.12.2 · Data.Time.Calendar.Week
IxDayOfWeekDefined in time-1.12.2 · Data.Time.Calendar.Week
NFDataDayOfWeekDefined in time-1.12.2 · Data.Time.Calendar.Week
HashableDayOfWeekDefined in time-compat-1.9.8 · Data.Time.Orphans · orphan
FormatTimeDayOfWeekDefined in time-1.12.2 · Data.Time.Format.Format.Instances · orphan
LiftDayOfWeekDefined in time-compat-1.9.8 · Data.Time.Orphans · orphan
This is a length of time, as measured by a clock.
Conversion functions such as fromInteger and realToFrac will treat it as seconds.
For example, (0.010 :: DiffTime) corresponds to 10 milliseconds.
It has a precision of one picosecond (= 10^-12 s). Enumeration functions will treat it as picoseconds.
This is a length of time, as measured by UTC.
It has a precision of 10^-12 s.
Conversion functions such as fromInteger and realToFrac will treat it as seconds.
For example, (0.010 :: NominalDiffTime) corresponds to 10 milliseconds.
It has a precision of one picosecond (= 10^-12 s). Enumeration functions will treat it as picoseconds.
It ignores leap-seconds, so it's not necessarily a fixed amount of clock time.
For instance, 23:00 UTC + 2 hours of NominalDiffTime = 01:00 UTC (+ 1 day),
regardless of whether a leap-second intervened.
SystemTime is time returned by system clock functions.
Its semantics depends on the clock function, but the epoch is typically the beginning of 1970.
Note that systemNanoseconds of 1E9 to 2E9-1 can be used to represent leap seconds.
This is the simplest representation of UTC.
It consists of the day number, and a time offset from midnight.
Note that if a day has a leap second added to it, it will have 86401 seconds.
The Modified Julian Date is the day with the fraction of the day, measured from UT midnight.
It's used to represent UT1, which is time as measured by the earth's rotation, adjusted for various wobbles.
Time of day as represented in hour, minute and second (with picoseconds), typically used to express local time of day.
TimeOfDay 24 0 0 is considered invalid for the purposes of makeTimeOfDayValid, as well as reading and parsing,
but valid for ISO 8601 parsing in Data.Time.Format.ISO8601.
The name of the zone, typically a three- or four-letter acronym.
Instances12Eq, Data, Ord, Read, Show, Generic, …
EqTimeZoneDefined in time-1.12.2 · Data.Time.LocalTime.Internal.TimeZone
DataTimeZoneDefined in time-1.12.2 · Data.Time.LocalTime.Internal.TimeZone
OrdTimeZoneDefined in time-1.12.2 · Data.Time.LocalTime.Internal.TimeZone
ReadTimeZoneDefined in time-1.12.2 · Data.Time.Format.Parse · orphan
This only works for ±HHMM format,
single-letter military time-zones,
and these time-zones: "UTC", "UT", "GMT", "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", "PDT",
per RFC 822 section 5.
ShowTimeZoneDefined in time-1.12.2 · Data.Time.LocalTime.Internal.TimeZone
This only shows the time zone name, or offset if the name is empty.
GenericTimeZoneDefined in time-compat-1.9.8 · Data.Time.Orphans · orphan
NFDataTimeZoneDefined in time-1.12.2 · Data.Time.LocalTime.Internal.TimeZone
HashableTimeZoneDefined in time-compat-1.9.8 · Data.Time.Orphans · orphan
FormatTimeTimeZoneDefined in time-1.12.2 · Data.Time.Format.Format.Instances · orphan
ParseTimeTimeZoneDefined in time-1.12.2 · Data.Time.Format.Parse.Instances · orphan
ISO8601TimeZoneDefined in time-1.12.2 · Data.Time.Format.ISO8601
±hh:mm (ISO 8601:2004(E) sec. 4.2.5.1 extended format)
There is no Eq instance for ZonedTime.
If you want to compare local times, use zonedTimeToLocalTime.
If you want to compare absolute times, use zonedTimeToUTC.
DataZonedTimeDefined in time-1.12.2 · Data.Time.LocalTime.Internal.ZonedTime
ReadZonedTimeDefined in time-1.12.2 · Data.Time.Format.Parse · orphan
This only works for a zonedTimeZone in ±HHMM format,
single-letter military time-zones,
and these time-zones: "UTC", "UT", "GMT", "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", "PDT",
per RFC 822 section 5.
ShowZonedTimeDefined in time-1.12.2 · Data.Time.LocalTime.Internal.ZonedTime
For the time zone, this only shows the name, or offset if the name is empty.
GenericZonedTimeDefined in time-compat-1.9.8 · Data.Time.Orphans · orphan
NFDataZonedTimeDefined in time-1.12.2 · Data.Time.LocalTime.Internal.ZonedTime
FormatTimeZonedTimeDefined in time-1.12.2 · Data.Time.Format.Format.Instances · orphan
ParseTimeZonedTimeDefined in time-1.12.2 · Data.Time.Format.Parse.Instances · orphan
ISO8601ZonedTimeDefined in time-1.12.2 · Data.Time.Format.ISO8601
yyyy-mm-ddThh:mm:ss[.sss]±hh:mm (ISO 8601:2004(E) sec. 4.3.2 extended format)
The class of monad transformers.
For any monad m, the result t m should also be a monad,
and lift should be a monad transformation from m to t m,
i.e. it should satisfy the following laws:
Since 0.6.0.0 and for GHC 8.6 and later, the requirement that t m
be a Monad is enforced by the implication constraint
forall m. Monad m => Monad (t m) enabled by the
QuantifiedConstraints extension.
The continuation monad transformer.
Can be used to add continuation handling to any type constructor:
the Monad instance and most of the operations do not require m
to be a monad.
ContT is not a functor on the category of monads, and many operations
cannot be lifted through it.
The continuation describes a way of choosing a 'search' or 'ranking'
strategy for r, based on a 'ranking' using r', given any a. We then
get a 'search' strategy for r.
'Extends' the possibilities considered by m to include every value of
e; this means that the potential result could be either a Left (making it
a choice of type e) or a Right (making it a choice of type a).
'Extends' the possibilities considered by m to include Nothing; this
means that Nothing gains a 'rank' (namely, a value of r), and the
potential result could also be Nothing.
Provides a read-only environment of type r to the 'strategy' function.
However, the 'ranking' function (or more accurately, representation) has no
access to r. Put another way, you can influence what values get chosen by
changing r, but not how solutions are ranked.
'Readerizes' the state: the 'ranking' function can see a value of
type s, but not modify it. Effectively, can be thought of as 'extending'
the 'ranking' by all values in s, but whichs gets given to any rank
calls is predetermined by the 'outer state' (and cannot change).
'Readerizes' the writer: the 'ranking' function can see the value
that's been accumulated (of type w), but can't add anything to the log.
Effectively, can be thought of as 'extending' the 'ranking' by all values
of w, but whichw gets given to any rank calls is predetermined by the
'outer writer' (and cannot change).
(Ordk, Ordv) => Ord (HashMapkv)Defined in unordered-containers-0.2.21 · Data.HashMap.Internal
The ordering is total and consistent with the Eq instance. However,
nothing else about the ordering is specified, and it may change from
version to version of either this package or of hashable.
Solo is the canonical lifted 1-tuple, just like Tuple2 is the canonical
lifted 2-tuple (pair) and Tuple3 is the canonical lifted 3-tuple (triple).
The most important feature of Solo is that it is possible to force its
"outside" (usually by pattern matching) without forcing its "inside",
because it is defined as a datatype rather than a newtype. One situation
where this can be useful is when writing a function to extract a value from
a data structure. Suppose you write an implementation of arrays and offer
only this function to index into them:
index :: Array a -> Int -> a
Now imagine that someone wants to extract a value from an array and store it
in a lazy-valued finite map/dictionary:
insert "hello" (arr index 12) m
This can actually lead to a space leak. The value is not actually extracted
from the array until that value (now buried in a map) is forced. That means
the entire array may be kept live by just that value! Often, the solution
is to use a strict map, or to force the value before storing it, but for
some purposes that's undesirable.
One common solution is to include an indexing function that can produce its
result in an arbitrary Applicative context:
indexA :: Applicative f => Array a -> Int -> f a
When using indexA in a pure context, Solo serves as a handy
Applicative functor to hold the result. You could write a non-leaky
version of the above example thus:
case arr indexA 12 of
Solo a -> insert "hello" a m
While such simple extraction functions are the most common uses for
unary tuples, they can also be useful for fine-grained control of
strict-spined data structure traversals, and for unifying the
implementations of lazy and strict mapping functions.
RealWorld is deeply magical. It is primitive, but it is not
unlifted (hence ptrArg). We never manipulate values of type
RealWorld; it's only used in the type system, to parameterise State#.
DataDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Data
NumDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Float · orphan
This instance implements IEEE 754 standard with all its usual pitfalls
about NaN, infinities and negative zero.
Neither addition nor multiplication are associative or distributive:
IEEE 754 Double-precision type includes not only numbers, but also
positive and negative infinities and a special element called NaN
(which can be quiet or signal).
IEEE 754-2008, section 5.11 requires that if at least one of arguments of
<=, <, >, >= is NaN then the result of the comparison is False,
and instanceOrdDouble complies with this requirement. This violates
the reflexivity: both NaN<=NaN and NaN>=NaN are False.
IEEE 754-2008, section 5.10 defines totalOrder predicate. Unfortunately,
compare on Doubles violates the IEEE standard and does not define a total order.
More specifically, both compareNaNx and comparexNaN always return GT.
Thus, users must be extremely cautious when using instanceOrdDouble.
For instance, one should avoid ordered containers with keys represented by Double,
because data loss and corruption may happen. An IEEE-compliant compare is available
in fp-ieee package as TotallyOrdered newtype.
Moving further, the behaviour of min and max with regards to NaN is
also non-compliant. IEEE 754-2008, section 5.3.1 defines that quiet NaN
should be treated as a missing data by minNum and maxNum functions,
for example, minNum(NaN, 1) = minNum(1, NaN) = 1. Some languages such as Java
deviate from the standard implementing minNum(NaN, 1) = minNum(1, NaN) = NaN.
However, min / max in base are even worse: minNaN 1 is 1, but min 1 NaN
is NaN.
IEEE 754-2008 compliant min / max can be found in ieee754 package under
minNum / maxNum names. Implementations compliant with
minimumNumber / maximumNumber from a newer
IEEE 754-2019,
section 9.6 are available from fp-ieee package.
ReadDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Read
RealDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Float · orphan
Beware that toRational generates garbage for non-finite arguments:
Example2 expressions
>>> toRational (1/0)179769313 (and 300 more digits...) % 1>>> toRational (0/0)269653970 (and 300 more digits...) % 1
RealFloatDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Float
RealFracDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Float · orphan
Beware that results for non-finite arguments are garbage:
Example2 expressions
>>> [ f x | f <- [round, floor, ceiling], x <- [-1/0, 0/0, 1/0] ] :: [Int][0,0,0,0,0,0,0,0,0]>>> map properFraction [-1/0, 0/0, 1/0] :: [(Int, Double)][(0,0.0),(0,0.0),(0,0.0)]
and get even more non-sensical if you ask for Integer instead of Int.
ShowDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Float · orphan
StorableDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Storable
Lifted, homogeneous equality. By lifted, we mean that it
can be bogus (deferred type error). By homogeneous, the two
types a and b must have the same kinds.
Coercible is a two-parameter class that has instances for types a and b if
the compiler can infer that they have the same representation. This class
does not have regular instances; instead they are created on-the-fly during
type-checking. Trying to manually declare an instance of Coercible
is an error.
Nevertheless one can pretend that the following three kinds of instances
exist. First, as a trivial base-case:
instance Coercible a a
Furthermore, for every type constructor there is
an instance that allows to coerce under the type constructor. For
example, let D be a prototypical type constructor (data or
newtype) with three type arguments, which have roles nominal,
representational resp. phantom. Then there is an instance of
the form
instance Coercible b b' => Coercible (D a b c) (D a b' c')
Note that the nominal type arguments are equal, the
representational type arguments can differ, but need to have a
Coercible instance themself, and the phantom type arguments can be
changed arbitrarily.
The third kind of instance exists for every newtype NT = MkNT T and
comes in two variants, namely
instance Coercible a T => Coercible a NT
instance Coercible T b => Coercible NT b
This instance is only usable if the constructor MkNT is in scope.
If, as a library author of a type constructor like Set a, you
want to prevent a user of your module to write
coerce :: Set T -> Set NT,
you need to set the role of Set's type parameter to nominal,
by writing
type role Set nominal
For more details about this feature, please refer to
Safe Coercions
by Joachim Breitner, Richard A. Eisenberg, Simon Peyton Jones and Stephanie Weirich.
Arbitrary precision integers. In contrast with fixed-size integral types
such as Int, the Integer type represents the entire infinite range of
integers.
Integers are stored in a kind of sign-magnitude form, hence do not expect
two's complement form when using bit operations.
If the value is small (i.e., fits into an Int), the IS constructor is
used. Otherwise IP and IN constructors are used to store a BigNat
representing the positive or the negative value magnitude, respectively.
Invariant: IP and IN are used iff the value does not fit in IS.
Instances24Enum, Eq, Integral, Data, Num, Ord, …
EnumIntegerDefined in ghc-internal-9.1003.0 · GHC.Internal.Enum
EqIntegerDefined in ghc-bignum-1.3 · GHC.Num.Integer
IntegralIntegerDefined in ghc-internal-9.1003.0 · GHC.Internal.Real
DataIntegerDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Data
NumIntegerDefined in ghc-internal-9.1003.0 · GHC.Internal.Num
OrdIntegerDefined in ghc-bignum-1.3 · GHC.Num.Integer
ReadIntegerDefined in ghc-internal-9.1003.0 · GHC.Internal.Read
RealIntegerDefined in ghc-internal-9.1003.0 · GHC.Internal.Real
ShowIntegerDefined in ghc-internal-9.1003.0 · GHC.Internal.Show
IxIntegerDefined in ghc-internal-9.1003.0 · GHC.Internal.Ix
BitsIntegerDefined in ghc-internal-9.1003.0 · GHC.Internal.Bits
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 id specialized from a -> 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 -> Int
strSum s = sum (mapMaybereadMaybe (words s))
we can deploy the function application operator:
-- | Sum numbers in a string: strSum "100 5 -7" == 98
strSum :: String -> Int
strSum s = sum$mapMaybereadMaybe$words s
($) 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:
If the first argument evaluates to True, then the result is the
second argument. Otherwise an AssertionFailed exception
is raised, containing a String with the source file and line number of the
call to assert.
Assertions can normally be turned on or off with a compiler flag
(for GHC, assertions are normally on unless optimisation is turned on
with -O or the -fignore-asserts
option is given). When assertions are turned off, the first
argument to assert is ignored, and the second argument is
returned as the result.
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 GHC.Internal.Data.List.concat=GHC.Internal.Data.List.foldr(++)[]
has linear performance, while GHC.Internal.Data.List.foldl(++)[] is prone
to quadratic slowdown
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.
A common use of join is to run an IO computation returned from
an GHC.Conc.STM transaction, since GHC.Conc.STM transactions
can't perform IO directly. Recall that
GHC.Internal.Conc.atomically :: STM a -> IO a
is used to run GHC.Conc.STM transactions atomically. So, by
specializing the types of GHC.Internal.Conc.atomically and join to
GHC.Internal.Conc.atomically :: STM (IO b) -> IO (IO b)
join :: IO (IO b) -> IO b
we can compose them as
join . GHC.Internal.Conc.atomically :: STM (IO b) -> IO b
to run an GHC.Conc.STM transaction and the IO action it
returns.
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 Just (x `div`
y) otherwise. For example:
Example1 expression
>>> safeDiv 4 0Nothing
Example1 expression
>>> 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 Monaddo-notation:
safeDiv :: Int -> Int -> Maybe Int
safeDiv x y = do
guard (y /= 0)
return (x `div` y)
Converts an arbitrary value into an object of type Dynamic.
The type of the object must be an instance of Typeable, which
ensures that only monomorphically-typed objects may be converted to
Dynamic. To convert a polymorphic object into Dynamic, give it
a monomorphic type signature. For example:
The trace function outputs the trace message given as its first argument,
before returning the second argument as its result.
For example, this returns the value of f x and outputs the message to stderr.
Depending on your terminal (settings), they may or may not be mixed.
Example2 expressions
>>> let x = 123; f = show>>> trace ("calling f with x = " ++ show x) (f x)calling f with x = 123"123"
The trace function should only be used for debugging, or for monitoring
execution. The function is not referentially transparent: its type indicates
that it is a pure function but it has the side effect of outputting the
trace message.
A value of type FunPtr a is a pointer to a function callable
from foreign code. The type a will normally be a foreign type,
a function type with zero or more arguments where
the return type is either a marshallable foreign type or has the form
IO t where t is a marshallable foreign type or ().
A value of type FunPtr a may be a pointer to a foreign function,
either returned by another foreign function or imported with a
a static address import like
The print function outputs a value of any printable type to the
standard output device.
Printable types are those that are instances of class Show; print
converts values to strings for output using the show operation and
adds a newline.
For example, a program to print the first 20 integers and their
powers of 2 could be written as:
Highly, terribly dangerous coercion from one representation type
to another. Misuse of this function can invite the garbage collector
to trounce upon your data and then laugh in your face. You don't want
this function. Really.
This type is treated magically within GHC. Any pattern match of the
form case unsafeEqualityProof of UnsafeRefl -> body gets transformed just into body.
This is ill-typed, but the transformation takes place after type-checking is
complete. It is used to implement unsafeCoerce. You probably don't want to
use UnsafeRefl in an expression, but you might conceivably want to pattern-match
on it. Use unsafeEqualityProof to create one of these.
The call inline f arranges that f is inlined, regardless of
its size. More precisely, the call inline f rewrites to the
right-hand side of f's definition. This allows the programmer to
control inlining from a particular call site rather than the
definition site of the function (c.f. INLINE pragmas).
This inlining occurs regardless of the argument to the call or the
size of f's definition; it is unconditional. The main caveat is
that f's definition must be visible to the compiler; it is
therefore recommended to mark the function with an INLINABLE
pragma at its definition so that GHC guarantees to record its
unfolding regardless of size.
If no inlining takes place, the inline function expands to the
identity function in Phase zero, so its use imposes no overhead.
The lazy function restrains strictness analysis a little. The
call lazy e means the same as e, but lazy has a magical
property so far as strictness analysis is concerned: it is lazy in
its first argument, even though its semantics is strict. After
strictness analysis has run, calls to lazy are inlined to be the
identity function.
This behaviour is occasionally useful when controlling evaluation
order. Notably, lazy is used in the library definition of
par:
par :: a -> b -> b
par x y = case (par# x) of _ -> lazy y
If lazy were not lazy, par would look strict in
y which would defeat the whole purpose of par.
The fixed point of a monadic computation.
mfix f executes the action f only once, with the eventual
output fed back as the input. Hence f should not be strict,
for then mfix f would diverge.
When a value is bound in do-notation, the pattern on the left
hand side of <- might not match. In this case, this class
provides a function to recover.
A Monad without a MonadFail instance may only be used in conjunction
with pattern that always match, such as newtypes, tuples, data types with
only a single data constructor, and irrefutable patterns (~pat).
Instances of MonadFail should satisfy the following law: fail s should
be a left zero for >>=,
fail s >>= f = fail s
If your Monad is also MonadPlus, a popular definition is
fail _ = mzero
fail s should be an action that runs in the monad itself, not an
exception (except in instances of MonadIO). In particular,
fail should not be implemented in terms of error.
The function coerce allows you to safely convert between values of
types that have the same representation with no run-time overhead. In the
simplest case you can use it instead of a newtype constructor, to go from
the newtype's concrete type to the abstract type. But it also works in
more complicated settings, e.g. converting a list of newtypes to a list of
concrete types.
When used in conversions involving a newtype wrapper,
make sure the newtype constructor is in scope.
This function is representation-polymorphic, but the
RuntimeRep type argument is marked as Inferred, meaning
that it is not available for visible type application. This means
the typechecker will accept coerce @Int @Age 42.
Examples
Example5 expressions
>>> newtype TTL = TTL Int deriving (Eq, Ord, Show)>>> newtype Age = Age Int deriving (Eq, Ord, Show)>>> coerce (Age 42) :: TTLTTL 42>>> coerce (+ (1 :: Int)) (Age 42) :: TTLTTL 43>>> coerce (map (+ (1 :: Int))) [Age 42, Age 24] :: [TTL][TTL 43,TTL 25]
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.
Constraint representing the fact that the field x belongs to
the record type r and has field type a. This will be solved
automatically, but manual instances may be provided as well.