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.
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.
Instances98Num, …
NumABCDDefined in HTTP-4000.4.1 · Network.HTTP.MD5Aux
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:
Numa => Num (Opab)Defined in base-4.20.2.0 · Data.Functor.Contravariant
Num (fa) => Num (Altfa)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Semigroup.Internal
Numa => Num (Constab)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Functor.Const
(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 Binary class provides put and get, methods to encode and
decode a Haskell value to a lazy ByteString. It mirrors the Read and
Show classes for textual representation of Haskell types, and is
suitable for serialising Haskell values to disk, over the network.
For decoding and generating simple external binary formats (e.g. C
structures), Binary may be used, but in general is not suitable
for complex protocols. Instead use the Put and Get primitives
directly.
Instances of Binary should satisfy the following property:
decode . encode == id
That is, the get and put methods should be the inverse of each
other. A range of instances are provided for basic Haskell types.
Encode a list of values in the Put monad.
The default implementation may be overridden to be more efficient
but must still have the same encoding format.
Instances337Binary, …
BinaryModuleShapeDefined in Cabal-3.12.1.0 · Distribution.Backpack.ModuleShape
BinaryModTimeDefined in Cabal-3.12.1.0 · Distribution.Compat.Time
BinaryBuildTargetDefined in Cabal-3.12.1.0 · Distribution.Simple.BuildTarget
BinaryCompilerDefined in Cabal-3.12.1.0 · Distribution.Simple.Compiler
(Orda, Binarya) => Binary (NubLista)Defined in Cabal-3.12.1.0 · Distribution.Utils.NubList
Binary instance for 'NubList a' is the same as for '[a]'. For put, we
just pull off constructor and put the list. For get, we get the list and
make a NubList out of it using toNubList.
Structureda => Binary (Taga)Defined in Cabal-syntax-3.12.1.0 · Distribution.Utils.Structured
Binary (SymbolicPathfromto)Defined in Cabal-syntax-3.12.1.0 · Distribution.Utils.Path
Binary (Fixeda)Defined in binary-0.8.9.3 · Data.Binary.Class
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.
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.
Instances373Read, …
ReadModTimeDefined in Cabal-3.12.1.0 · Distribution.Compat.Time
ReadCompilerDefined in Cabal-3.12.1.0 · Distribution.Simple.Compiler
ReadDebugInfoLevelDefined in Cabal-3.12.1.0 · Distribution.Simple.Compiler
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
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.
ReadRTLDFlagsDefined in unix-2.8.7.0 · System.Posix.DynamicLinker.Prim
ReadCAttributesDefined in unix-2.8.7.0 · System.Posix.Files.Common
ReadStatxFlagsDefined in unix-2.8.7.0 · System.Posix.Files.Common
ReadStatxMaskDefined in unix-2.8.7.0 · System.Posix.Files.Common
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.
Instances256Data, …
DataOpenModuleDefined in Cabal-syntax-3.12.1.0 · Distribution.Backpack
DataOpenUnitIdDefined in Cabal-syntax-3.12.1.0 · Distribution.Backpack
DataCabalSpecVersionDefined in Cabal-syntax-3.12.1.0 · Distribution.CabalSpecVersion
DataCompilerFlavorDefined in Cabal-syntax-3.12.1.0 · Distribution.Compiler
DataLicenseDefined in Cabal-syntax-3.12.1.0 · Distribution.License
DataModuleNameDefined in Cabal-syntax-3.12.1.0 · Distribution.ModuleName
DataLicenseDefined in Cabal-syntax-3.12.1.0 · Distribution.SPDX.License
DataLicenseExceptionIdDefined in Cabal-syntax-3.12.1.0 · Distribution.SPDX.LicenseExceptionId
DataLicenseExpressionDefined in Cabal-syntax-3.12.1.0 · Distribution.SPDX.LicenseExpression
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.
>>> 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.
Instances53Alternative, …
AlternativeMatchDefined in Cabal-3.12.1.0 · Distribution.Simple.BuildTarget
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.
Instances106Monad, …
MonadInstMDefined in Cabal-3.12.1.0 · Distribution.Backpack.ReadyComponent
MonadMatchDefined in Cabal-3.12.1.0 · Distribution.Simple.BuildTarget
MonadLogProgressDefined in Cabal-3.12.1.0 · Distribution.Utils.LogProgress
MonadWriterDefined in Cabal-3.12.1.0 · Distribution.ZinzaPrelude
MonadLexDefined in Cabal-syntax-3.12.1.0 · Distribution.Fields.LexerMonad
MonadParseResultDefined in Cabal-syntax-3.12.1.0 · Distribution.Fields.ParseResult
MonadParsecParserDefined in Cabal-syntax-3.12.1.0 · Distribution.Parsec
MonadConditionDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.Condition
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
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 Prelude.>> and Prelude.>>= operations from the Prelude.Monad
class.
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 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.
OrdLicenseIdDefined in Cabal-syntax-3.12.1.0 · Distribution.SPDX.LicenseId
OrdLicenseListVersionDefined in Cabal-syntax-3.12.1.0 · Distribution.SPDX.LicenseListVersion
OrdLicenseRefDefined in Cabal-syntax-3.12.1.0 · Distribution.SPDX.LicenseReference
OrdArchDefined in Cabal-syntax-3.12.1.0 · Distribution.System
OrdOSDefined in Cabal-syntax-3.12.1.0 · Distribution.System
OrdPlatformDefined in Cabal-syntax-3.12.1.0 · Distribution.System
OrdBenchmarkDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.Benchmark
OrdBenchmarkInterfaceDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.BenchmarkInterface
OrdBenchmarkTypeDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.BenchmarkType
OrdBuildInfoDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.BuildInfo
OrdBuildTypeDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.BuildType
OrdComponentIdDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.ComponentId
OrdComponentNameDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.ComponentName
OrdNotLibComponentNameDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.ComponentName
OrdDependencyDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.Dependency
OrdExeDependencyDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.ExeDependency
OrdExecutableDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.Executable
OrdExecutableScopeDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.ExecutableScope
OrdFlagAssignmentDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.Flag
OrdFlagNameDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.Flag
OrdForeignLibDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.ForeignLib
OrdLibVersionInfoDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.ForeignLib
OrdForeignLibOptionDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.ForeignLibOption
OrdForeignLibTypeDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.ForeignLibType
OrdIncludeRenamingDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.IncludeRenaming
OrdLegacyExeDependencyDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.LegacyExeDependency
OrdLibraryDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.Library
OrdLibraryNameDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.LibraryName
OrdLibraryVisibilityDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.LibraryVisibility
OrdMixinDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.Mixin
OrdModuleDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.Module
OrdModuleReexportDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.ModuleReexport
OrdModuleRenamingDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.ModuleRenaming
OrdMungedPackageIdDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.MungedPackageId
OrdMungedPackageNameDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.MungedPackageName
OrdPackageDescriptionDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.PackageDescription
OrdPackageIdentifierDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.PackageId
OrdPackageNameDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.PackageName
OrdPkgconfigDependencyDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.PkgconfigDependency
OrdPkgconfigNameDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.PkgconfigName
OrdPkgconfigVersionDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.PkgconfigVersion
OrdPkgconfigVersionRangeDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.PkgconfigVersionRange
OrdSetupBuildInfoDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.SetupBuildInfo
OrdKnownRepoTypeDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.SourceRepo
OrdRepoKindDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.SourceRepo
OrdRepoTypeDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.SourceRepo
OrdSourceRepoDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.SourceRepo
OrdTestSuiteDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.TestSuite
OrdTestSuiteInterfaceDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.TestSuiteInterface
OrdTestTypeDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.TestType
OrdDefUnitIdDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.UnitId
OrdUnitIdDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.UnitId
OrdUnqualComponentNameDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.UnqualComponentName
OrdVersionDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.Version
OrdLowerBoundDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.VersionInterval.Legacy
lb1 <= lb2 holds iff interval lb1.. is contained in interval lb2...
OrdUpperBoundDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.VersionInterval.Legacy
ub1 <= ub2 holds iff interval 0..ub1 is contained in interval 0..ub2.
OrdVersionRangeDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.VersionRange.Internal
OrdShortTextDefined in Cabal-syntax-3.12.1.0 · Distribution.Utils.ShortText
OrdStructureDefined in Cabal-syntax-3.12.1.0 · Distribution.Utils.Structured
OrdExtensionDefined in Cabal-syntax-3.12.1.0 · Language.Haskell.Extension
OrdKnownExtensionDefined in Cabal-syntax-3.12.1.0 · Language.Haskell.Extension
OrdLanguageDefined in Cabal-syntax-3.12.1.0 · Language.Haskell.Extension
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.
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.
OrdReportLevelDefined in cabal-install-3.12.1.0 · Distribution.Client.BuildReports.Types
OrdConfigPathDefined in cabal-install-3.12.1.0 · Distribution.Client.CmdPath
OrdPathCompilerInfoDefined in cabal-install-3.12.1.0 · Distribution.Client.CmdPath
OrdPathOutputFormatDefined in cabal-install-3.12.1.0 · Distribution.Client.CmdPath
OrdPathOutputsDefined in cabal-install-3.12.1.0 · Distribution.Client.CmdPath
OrdPreSolverDefined in cabal-install-3.12.1.0 · Distribution.Client.Dependency.Types
OrdSolverDefined in cabal-install-3.12.1.0 · Distribution.Client.Dependency.Types
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.
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 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.
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"
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]
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,
List of elements of a structure, from left to right. If the entire
list is intended to be reduced via a fold, just fold the structure
directly bypassing the list.
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
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
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.
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:
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
Prelude.minBound and Prelude.maxBound from the Prelude.Bounded class.
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:
Strict (call-by-value) application operator. It takes a function and an
argument, evaluates the argument to weak head normal form (WHNF), then calls
the function with that value.
The 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.
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.
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.
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:
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)>>> :}
This is just a convenience function intended for valid module strings. It is
an error if it is used with a string that is not a valid module name. If you
are parsing user input then use simpleParse instead.
IsStringAbiHashDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.AbiHash
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
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:
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 (Option'a)Defined in Cabal-syntax-3.12.1.0 · Distribution.Compat.Semigroup
Semigroupa => Monoid (ComponentDepsa)Defined in cabal-install-solver-3.12.1.0 · Distribution.Solver.Types.ComponentDeps
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.
Semigroupd => Monoid (DepTestRsltd)Defined in Cabal-syntax-3.12.1.0 · Distribution.PackageDescription.Configuration
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.
Numa => Monoid (Producta)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Semigroup.Internal
Numa => Monoid (Suma)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Semigroup.Internal
Orda => Monoid (NubLista)Defined in Cabal-3.12.1.0 · Distribution.Utils.NubList
Monoid operations on NubLists.
For a valid Monoid instance we need to satisfy the required monoid laws;
identity, associativity and closure.
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.
The Semigroup instance for ParsecT is used to append the result
of several parsers, for example:
(many $ char a) <> (many $ char b)
The above will parse a string like "aabbb" and return a successful
parse result "aabbb". Compare against the below which will
produce a result of "bbb" for the same input:
(many $ char a) >> (many $ char b)
(many $ char a) *> (many $ char b)
Semigroupc => Semigroup (K1icp)Defined in ghc-internal-9.1003.0 · GHC.Internal.Generics
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
Instances214Functor, …
FunctorWithSourceDefined in Cabal-3.12.1.0 · Distribution.Backpack.ModuleScope
FunctorInstMDefined in Cabal-3.12.1.0 · Distribution.Backpack.ReadyComponent
FunctorArgDescrDefined in Cabal-3.12.1.0 · Distribution.GetOpt
FunctorOptDescrDefined in Cabal-3.12.1.0 · Distribution.GetOpt
FunctorReadEDefined in Cabal-3.12.1.0 · Distribution.ReadE
FunctorMatchDefined in Cabal-3.12.1.0 · Distribution.Simple.BuildTarget
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.
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:
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.
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 Prelude.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
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
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.
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""
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:
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"]
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.
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:
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]
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.
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
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.
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.
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]])
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.
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.
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","")]
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
Instances88Traversable, …
TraversableWithSourceDefined in Cabal-3.12.1.0 · Distribution.Backpack.ModuleScope
TraversableFlagDefined in Cabal-3.12.1.0 · Distribution.Simple.Flag
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.
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.
Instances4Eq, Show, Exception, MonadError
EqIOExceptionDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Exception
ShowIOExceptionDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Exception
ExceptionIOExceptionDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Exception
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
EnumStatxFlagsDefined in unix-2.8.7.0 · System.Posix.Files.Common
EnumStatxMaskDefined in unix-2.8.7.0 · System.Posix.Files.Common
EnumBaudRateDefined in unix-2.8.7.0 · System.Posix.Terminal.Common
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 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,
Prelude.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.
Instances8RealFloat, …
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
The Haskell Report defines no laws for Fractional. However, (+) and
(*) are customarily expected to define a division ring and have the
following properties:
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.
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.
Instances1035Show, …
ShowFullUnitIdDefined in Cabal-3.12.1.0 · Distribution.Backpack.FullUnitId
ShowModuleShapeDefined in Cabal-3.12.1.0 · Distribution.Backpack.ModuleShape
ShowPreModuleShapeDefined in Cabal-3.12.1.0 · Distribution.Backpack.PreModuleShape
ShowAsyncCancelledDefined in Cabal-3.12.1.0 · Distribution.Compat.Async
ShowModTimeDefined in Cabal-3.12.1.0 · Distribution.Compat.Time
ShowBITargetDefined in Cabal-3.12.1.0 · Distribution.PackageDescription.Check.Target
ShowCETypeDefined in Cabal-3.12.1.0 · Distribution.PackageDescription.Check.Warning
ShowCheckExplanationDefined in Cabal-3.12.1.0 · Distribution.PackageDescription.Check.Warning
ShowCheckExplanationIDDefined in Cabal-3.12.1.0 · Distribution.PackageDescription.Check.Warning
ShowPackageCheckDefined in Cabal-3.12.1.0 · Distribution.PackageDescription.Check.Warning
Broken Show instance (not bijective with Read), alas external packages
depend on it.
ShowWarnLangDefined in Cabal-3.12.1.0 · Distribution.PackageDescription.Check.Warning
ShowAutogenFileDefined in Cabal-3.12.1.0 · Distribution.Simple.Build
ShowBuildTargetDefined in Cabal-3.12.1.0 · Distribution.Simple.BuildTarget
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.
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
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:
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.
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
The law does not hold for Float, Double, CFloat,
CDouble, etc., because these types contain non-finite values,
which cannot be roundtripped through Rational.
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:
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.
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 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.
\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 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,"!")]
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 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 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.
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)
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 (<>)
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 !_ = ()
Instances266NFData, …
NFDataIODataDefined in Cabal-3.12.1.0 · Distribution.Utils.IOData
NFDataOpenModuleDefined in Cabal-syntax-3.12.1.0 · Distribution.Backpack
NFDataOpenUnitIdDefined in Cabal-syntax-3.12.1.0 · Distribution.Backpack
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])
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.
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).
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:
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.
Generically generate a Semigroup (<>) operation for any type
implementing Generic. This operation will append two values
by point-wise appending their component fields. It is only defined
for product types.
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:
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.
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 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.
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.
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:
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).
PrettyMungedPackageNameDefined in Cabal-syntax-3.12.1.0 · Distribution.Types.MungedPackageName
Computes the package name for a library. If this is the public
library, it will just be the original package name; otherwise,
it will be a munged package name recording the original package
name as well as the name of the internal library.
A lot of tooling in the Haskell ecosystem assumes that if something
is installed to the package database with the package name foo,
then it actually is an entry for the (only public) library in package
foo. With internal packages, this is not necessarily true:
a public library as well as arbitrarily many internal libraries may
come from the same package. To prevent tools from getting confused
in this case, the package name of these internal libraries is munged
so that they do not conflict the public library proper. A particular
case where this matters is ghc-pkg: if we don't munge the package
name, the inplace registration will OVERRIDE a different internal
library.
We munge into a reserved namespace, "z-", and encode both the
component name and the package name of an internal library using the
following format: