This module supplies a convenient set of imports for working with the dimensional package, including aliases for common Quantitys and Dimensions,
and a comprehensive set of SI units and units accepted for use with the SI.
It re-exports the Prelude, hiding arithmetic functions whose names collide with the dimensionally-typed versions supplied by this package.
A KnownVariant is one whose term-level Dimensional values we can represent with an associated data family instance
and manipulate with certain functions, not all of which are exported from the package.
Represents a physical dimension in the basis of the 7 SI base dimensions,
where the respective dimensions are represented by type variables
using the following convention:
l: Length
m: Mass
t: Time
i: Electric current
th: Thermodynamic temperature
n: Amount of substance
j: Luminous intensity
For the equivalent term-level representation, see Dimension'
Because the power chosen impacts the Dimension of the result, it is necessary to supply a type-level representation
of the exponent in the form of a Proxy to some TypeInt. Convenience values pos1, pos2, neg1, ...
are supplied by the Numeric.NumType.DK.Integers module. The most commonly used ones are
also reexported by Numeric.Units.Dimensional.Prelude.
The intimidating type signature captures the similarity between these operations
and ensures that composite Units are NonMetric.
A physical dimension, encoded as 7 integers, representing a factorization of the dimension into the
7 SI base dimensions. By convention they are stored in the same order as
in the Dimension data kind.
A KnownDimension is one for which we can construct a term-level representation.
Each validly constructed type of kind Dimension has a KnownDimension instance.
The NRoot type family will prevent application of this operator where the result would have a fractional dimension or where n is zero.
Because the root chosen impacts the Dimension of the result, it is necessary to supply a type-level representation
of the root in the form of a Proxy to some TypeInt. Convenience values pos1, pos2, neg1, ...
are supplied by the Numeric.NumType.DK.Integers module. The most commonly used ones are
also reexported by Numeric.Units.Dimensional.Prelude.
The NRoot type family will prevent application of this operator where the result would have a fractional dimension or where n is zero.
Because the root chosen impacts the Dimension of the result, it is necessary to supply a type-level representation
of the root in the form of a Proxy to some TypeInt. Convenience values pos1, pos2, neg1, ...
are supplied by the Numeric.NumType.DK.Integers module. The most commonly used ones are
also reexported by Numeric.Units.Dimensional.Prelude.
n must not be zero. Negative roots are defined such that nroot (Proxy :: Proxy (Negate n)) x == nroot (Proxy :: Proxy n) (recip x).
A polymorphic Unit which can be used in place of the coherent
SI base unit of any dimension. This allows polymorphic quantity
creation and destruction without exposing the Dimensional constructor.
The unit one has dimension DOne and is the base unit of dimensionless values.
As detailed in 7.10 "Values of quantities expressed simply as numbers:
the unit one, symbol 1" of [1], the unit one generally does not
appear in expressions. However, for us it is necessary to use one
as we would any other unit to perform the "wrapping" of dimensionless values.
Forms a new atomic Unit by specifying its UnitName and its definition as a multiple of another Unit.
Use this variant when the scale factor of the resulting unit is irrational or Approximate. See mkUnitQ for when it is rational
and mkUnitZ for when it is an integer.
Note that supplying zero as a definining quantity is invalid, as the library relies
upon units forming a group under multiplication.
Supplying negative defining quantities is allowed and handled gracefully, but is discouraged
on the grounds that it may be unexpected by other readers.
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
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.
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:
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.
Instances86KnownMinCtxt, Num, …
NumExactPiDefined in exact-pi-0.5.0.2 · Data.ExactPi
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 Haskell Report defines no laws for Fractional. However, (+) and
(*) are customarily expected to define a division ring and have the
following properties:
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:
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 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 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
If the first list is not finite, the result is the first list.
Performance considerations
This function takes linear time in the number of elements of the
first list. Thus it is better to associate repeated
applications of (++) to the right (which is the default behaviour):
xs ++ (ys ++ zs) or simply xs ++ ys ++ zs, but not (xs ++ ys) ++ zs.
For the same reason GHC.Internal.Data.List.concat=GHC.Internal.Data.List.foldr(++)[]
has linear performance, while GHC.Internal.Data.List.foldl(++)[] is prone
to quadratic slowdown
The Ord class is used for totally ordered datatypes.
Instances of Ord can be derived for any user-defined datatype whose
constituent types are in Ord. The declared order of the constructors in
the data declaration determines the ordering in derived Ord instances. The
Ordering datatype allows a single comparison to determine the precise
ordering of two objects.
Ord, as defined by the Haskell report, implements a total order and has the
following properties:
Note that (7.) and (8.) do not require min and max to return either of
their arguments. The result is merely required to equal one of the
arguments in terms of (==).
Minimal complete definition: either compare or <=.
Using compare can be more efficient for complex types.
OrdByteArrayDefined in base-4.20.2.0 · Data.Array.Byte
Non-lexicographic ordering. This compares the lengths of
the byte arrays first and uses a lexicographic ordering if
the lengths are equal. Subject to change between major versions.
OrdDimension'Defined in dimensional-1.5 · Numeric.Units.Dimensional.Dimensions.TermLevel
OrdDynamicDimensionDefined in dimensional-1.5 · Numeric.Units.Dimensional.Dimensions.TermLevel
OrdInterchangeNameDefined in dimensional-1.5 · Numeric.Units.Dimensional.UnitNames.InterchangeNames
OrdInterchangeNameAuthorityDefined in dimensional-1.5 · Numeric.Units.Dimensional.UnitNames.InterchangeNames
OrdNameAtomTypeDefined in dimensional-1.5 · Numeric.Units.Dimensional.UnitNames.Internal
OrdPrefixDefined in dimensional-1.5 · Numeric.Units.Dimensional.UnitNames.Internal
OrdMetricalityDefined in dimensional-1.5 · Numeric.Units.Dimensional.Variants
OrdBigNatDefined in ghc-bignum-1.3 · GHC.Num.BigNat
OrdIntegerDefined in ghc-bignum-1.3 · GHC.Num.Integer
OrdNaturalDefined in ghc-bignum-1.3 · GHC.Num.Natural
OrdExtensionDefined in ghc-boot-th-9.10.3 · GHC.LanguageExtensions.Type
OrdVoidDefined in ghc-internal-9.1003.0 · GHC.Internal.Base
OrdByteOrderDefined in ghc-internal-9.1003.0 · GHC.Internal.ByteOrder
OrdClosureTypeDefined in ghc-internal-9.1003.0 · GHC.Internal.ClosureTypes
OrdBlockReasonDefined in ghc-internal-9.1003.0 · GHC.Internal.Conc.Sync
OrdThreadIdDefined in ghc-internal-9.1003.0 · GHC.Internal.Conc.Sync
OrdThreadStatusDefined in ghc-internal-9.1003.0 · GHC.Internal.Conc.Sync
OrdAllDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Semigroup.Internal
OrdAnyDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Semigroup.Internal
OrdSomeTypeRepDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Typeable.Internal
OrdUniqueDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Unique
OrdVersionDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Version
OrdTimeoutKeyDefined in ghc-internal-9.1003.0 · GHC.Internal.Event.TimeOut
OrdUniqueDefined in ghc-internal-9.1003.0 · GHC.Internal.Event.Unique
OrdErrorCallDefined in ghc-internal-9.1003.0 · GHC.Internal.Exception
OrdArithExceptionDefined in ghc-internal-9.1003.0 · GHC.Internal.Exception.Type
OrdFingerprintDefined in ghc-internal-9.1003.0 · GHC.Internal.Fingerprint.Type
OrdCBoolDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCClockDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCFloatDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCIntDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCIntMaxDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCLLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCPtrdiffDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCSCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCSUSecondsDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCShortDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCSigAtomicDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCSizeDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCTimeDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCUCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCUIntDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCUIntMaxDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCUIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCULLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCULongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCUSecondsDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCUShortDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCWcharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Ptr
OrdWordPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Ptr
OrdAssociativityDefined in ghc-internal-9.1003.0 · GHC.Internal.Generics
IEEE 754 Double-precision type includes not only numbers, but also
positive and negative infinities and a special element called NaN
(which can be quiet or signal).
IEEE 754-2008, section 5.11 requires that if at least one of arguments of
<=, <, >, >= is NaN then the result of the comparison is False,
and instanceOrdDouble complies with this requirement. This violates
the reflexivity: both NaN<=NaN and NaN>=NaN are False.
IEEE 754-2008, section 5.10 defines totalOrder predicate. Unfortunately,
compare on Doubles violates the IEEE standard and does not define a total order.
More specifically, both compareNaNx and comparexNaN always return GT.
Thus, users must be extremely cautious when using instanceOrdDouble.
For instance, one should avoid ordered containers with keys represented by Double,
because data loss and corruption may happen. An IEEE-compliant compare is available
in fp-ieee package as TotallyOrdered newtype.
Moving further, the behaviour of min and max with regards to NaN is
also non-compliant. IEEE 754-2008, section 5.3.1 defines that quiet NaN
should be treated as a missing data by minNum and maxNum functions,
for example, minNum(NaN, 1) = minNum(1, NaN) = 1. Some languages such as Java
deviate from the standard implementing minNum(NaN, 1) = minNum(1, NaN) = NaN.
However, min / max in base are even worse: minNaN 1 is 1, but min 1 NaN
is NaN.
IEEE 754-2008 compliant min / max can be found in ieee754 package under
minNum / maxNum names. Implementations compliant with
minimumNumber / maximumNumber from a newer
IEEE 754-2019,
section 9.6 are available from fp-ieee package.
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 = []
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
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.
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.
Instances17Enum, 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 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.
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:
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,
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:
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
AEqa => AEq (Maybea)Defined in ieee754-0.8.0 · Data.AEq
SingI 'NothingDefined in ghc-internal-9.1003.0 · GHC.Internal.Generics
SingIa2 => SingI ('Justa2)Defined in ghc-internal-9.1003.0 · GHC.Internal.Generics
The method names refer to the monoid of lists under concatenation,
but there are many other instances.
Some types can be viewed as a monoid in more than one way,
e.g. both addition and multiplication on numbers.
In such cases we often define newtypes and make those instances
of Monoid, e.g. Data.Semigroup.Sum and Data.Semigroup.Product.
NOTE: Semigroup is a superclass of Monoid since base-4.11.0.0.
NOTE: This method is redundant and has the default
implementation mappend = (<>) since base-4.11.0.0.
Should it be implemented manually, since mappend is a synonym for
(<>), it is expected that the two functions are defined the same
way. In a future GHC release mappend will be removed from Monoid.
For most types, the default definition for mconcat will be
used, but the function is included in the class definition so
that an optimized version can be provided for specific types.
Monoidp => Monoid (Par1p)Defined in ghc-internal-9.1003.0 · GHC.Internal.Generics
Semigroupa => Monoid (Maybea)Defined in ghc-internal-9.1003.0 · GHC.Internal.Base
Lift a semigroup into Maybe forming a Monoid according to
http://en.wikipedia.org/wiki/Monoid: "Any semigroup S may be
turned into a monoid simply by adjoining an element e not in S
and defining e*e = e and e*s = s = s*e for all s ∈ S."
Since 4.11.0: constraint on inner a value generalised from
Monoid to Semigroup.
Bitsa => Monoid (Iora)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Bits
Bitsa => Monoid (Xora)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Bits
FiniteBitsa => Monoid (Anda)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Bits
This constraint is arguably too strong. However,
as some types (such as Natural) have undefined complement, this is the
only safe choice.
FiniteBitsa => Monoid (Iffa)Defined in ghc-internal-9.1003.0 · GHC.Internal.Data.Bits
This constraint is arguably
too strong. However, as some types (such as Natural) have undefined
complement, this is the only safe choice.
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.
Instances364Show, …
ShowByteArrayDefined in base-4.20.2.0 · Data.Array.Byte
ShowTimeoutDefined in base-4.20.2.0 · System.Timeout
ShowDimension'Defined in dimensional-1.5 · Numeric.Units.Dimensional.Dimensions.TermLevel
ShowDynamicDimensionDefined in dimensional-1.5 · Numeric.Units.Dimensional.Dimensions.TermLevel
ShowAnyUnitDefined in dimensional-1.5 · Numeric.Units.Dimensional.Dynamic
ShowInterchangeNameDefined in dimensional-1.5 · Numeric.Units.Dimensional.UnitNames.InterchangeNames
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.
Instances66Monad, …
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
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:
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","")]
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.
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.
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
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.
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.
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.
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:
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.
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
Map each element of a structure to a monadic action, evaluate
these actions from left to right, and ignore the results. For a
version that doesn't ignore the results see
Data.Traversable.mapM.
mapM_ is just like traverse_, but specialised to monadic actions.
or returns the disjunction of a container of Bools. For the
result to be False, the container must be finite; True, however,
results from a True value finitely far from the left end.
Examples
Basic usage:
Example1 expression
>>> or []False
Example1 expression
>>> or [True]True
Example1 expression
>>> or [False]False
Example1 expression
>>> or [True, True, False]True
Example1 expression
>>> or (True : repeat False) -- Infinite list [True,False,False,False,...True
Evaluate each monadic action in the structure from left to right,
and ignore the results. For a version that doesn't ignore the
results see Data.Traversable.sequence.
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"]
break, applied to a predicate p and a list xs, returns a tuple where
first element is longest prefix (possibly empty) of xs of elements that
do not satisfyp and second element is the remainder of the list:
This is a partial function, it throws an error on empty lists. Use pattern matching, uncons or listToMaybe instead. Consider refactoring to use Data.List.NonEmpty.
\mathcal{O}(1). Extract the first element of a list, which must be non-empty.
To disable the warning about partiality put {-# OPTIONS_GHC -Wno-x-partial -Wno-unrecognised-warning-flags #-}
at the top of the file. To disable it throughout a package put the same
options into ghc-options section of Cabal file. To disable it in GHCi
put :set -Wno-x-partial -Wno-unrecognised-warning-flags into ~/.ghci config file.
See also the migration guide.
Examples
Example1 expression
>>> head [1, 2, 3]1
Example1 expression
>>> head [1..]1
Example1 expression
>>> head []*** Exception: Prelude.head: empty list
iteratef x returns an infinite list of repeated applications
of f to x:
iterate f x == [x, f x, f (f x), ...]
Laziness
Note that iterate is lazy, potentially leading to thunk build-up if
the consumer doesn't force each iterate. See iterate' for a strict
variant of this function.
Example1 expression
>>> take 1 $ iterate undefined 42[42]
Examples
Example1 expression
>>> take 10 $ iterate not True[True,False,True,False,True,False,True,False,True,False]
Example1 expression
>>> take 10 $ iterate (+3) 42[42,45,48,51,54,57,60,63,66,69]
replicaten x is a list of length n with x the value of
every element.
It is an instance of the more general genericReplicate,
in which n may be of any integral type.
\mathcal{O}(n). scanr is the right-to-left dual of scanl. Note that the order of parameters on the accumulating function are reversed compared to scanl.
Also note that
span, applied to a predicate p and a list xs, returns a tuple where
first element is the longest prefix (possibly empty) of xs of elements that
satisfy p and second element is the remainder of the list:
This is a partial function, it throws an error on empty lists. Replace it with drop 1, or use pattern matching or uncons instead. Consider refactoring to use Data.List.NonEmpty.
\mathcal{O}(1). Extract the elements after the head of a list, which
must be non-empty.
To disable the warning about partiality put {-# OPTIONS_GHC -Wno-x-partial -Wno-unrecognised-warning-flags #-}
at the top of the file. To disable it throughout a package put the same
options into ghc-options section of Cabal file. To disable it in GHCi
put :set -Wno-x-partial -Wno-unrecognised-warning-flags into ~/.ghci config file.
See also the migration guide.
Examples
Example1 expression
>>> tail [1, 2, 3][2,3]
Example1 expression
>>> tail [1][]
Example1 expression
>>> tail []*** Exception: Prelude.tail: empty list
zip3 takes three lists and returns a list of triples, analogous to
zip.
It is capable of list fusion, but it is restricted to its
first list argument and its resulting list.
vvaluezipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
\mathcal{O}(\min(l,m,n)). The zipWith3 function takes a function which combines three
elements, as well as three lists and returns a list of the function applied
to corresponding elements, analogous to zipWith.
It is capable of list fusion, but it is restricted to its
first list argument and its resulting list.
zipWith3 (,,) xs ys zs == zip3 xs ys zs
zipWith3 f [x1,x2,x3..] [y1,y2,y3..] [z1,z2,z3..] == [f x1 y1 z1, f x2 y2 z2, f x3 y3 z3..]
Examples
Example1 expression
>>> zipWith3 (\x y z -> [x, y, z]) "123" "abc" "xyz"["1ax","2by","3cz"]
Example1 expression
>>> zipWith3 (\x y z -> (x * y) + z) [1, 2, 3] [4, 5, 6] [7, 8, 9][11,18,27]
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.
The computation appendFilefile str function appends the string str,
to the file file.
Note that writeFile and appendFile write a literal string
to a file. To write a value of any printable type, as with print,
use the show function to convert the value to a string first.
main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
The interact function takes a function of type String->String
as its argument. The entire input from the standard input device is
passed to this function as its argument, and the resulting string is
output on the standard output device.
The read function reads input from a string, which must be
completely consumed by the input process. read fails with an error if the
parse is unsuccessful, and it is therefore discouraged from being used in
real applications. Use readMaybe or readEither for safe alternatives.
Example1 expression
>>> read "123" :: Int123
Example1 expression
>>> read "hello" :: Int*** Exception: Prelude.read: no parse
Functors representing data structures that can be transformed to
structures of the same shape by performing an Applicative (or,
therefore, Monad) action on each element from left to right.
A more detailed description of what same shape means, the various methods,
how traversals are constructed, and example advanced use-cases can be found
in the Overview section of Data.Traversable#overview.
For the class laws see the Laws section of Data.Traversable#laws.
Map each element of a structure to an action, evaluate these actions
from left to right, and collect the results. For a version that ignores
the results see traverse_.
Examples
Basic usage:
In the first two examples we show each evaluated action mapping to the
output structure.
Example1 expression
>>> traverse Just [1,2,3,4]Just [1,2,3,4]
Example1 expression
>>> traverse id [Right 1, Right 2, Right 3, Right 4]Right [1,2,3,4]
In the next examples, we show that Nothing and Left values short
circuit the created structure.
Example1 expression
>>> traverse (const Nothing) [1,2,3,4]Nothing
Example1 expression
>>> traverse (\x -> if odd x then Just x else Nothing) [1,2,3,4]Nothing
Example1 expression
>>> traverse id [Right 1, Right 2, Right 3, Right 4, Left 0]Left 0
Evaluate each action in the structure from left to right, and
collect the results. For a version that ignores the results
see sequenceA_.
Examples
Basic usage:
For the first two examples we show sequenceA fully evaluating a
a structure and collecting the results.
Example1 expression
>>> sequenceA [Just 1, Just 2, Just 3]Just [1,2,3]
Example1 expression
>>> sequenceA [Right 1, Right 2, Right 3]Right [1,2,3]
The next two example show Nothing and Just will short circuit
the resulting structure if present in the input. For more context,
check the Traversable instances for Either and Maybe.
Example1 expression
>>> sequenceA [Just 1, Just 2, Just 3, Nothing]Nothing
Example1 expression
>>> sequenceA [Right 1, Right 2, Right 3, Left 4]Left 4
Map each element of a structure to a monadic action, evaluate
these actions from left to right, and collect the results. For
a version that ignores the results see Data.Foldable.mapM_.
Examples
mapM is literally a traverse with a type signature restricted
to Monad. Its implementation may be more efficient due to additional
power of Monad.
Evaluate each monadic action in the structure from left to
right, and collect the results. For a version that ignores the
results see Data.Foldable.sequence_.
Examples
Basic usage:
The first two examples are instances where the input and
and output of sequence are isomorphic.
Example1 expression
>>> sequence $ Right [1,2,3,4][Right 1,Right 2,Right 3,Right 4]
File and directory names are values of type String, whose precise
meaning is operating system dependent. Files can be opened, yielding a
handle which can then be used to operate on the contents of that file.
The 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.
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.
Instances169Read, …
ReadIntegerDefined in ghc-internal-9.1003.0 · GHC.Internal.Read
ReadNaturalDefined in ghc-internal-9.1003.0 · GHC.Internal.Read
ReadVoidDefined in ghc-internal-9.1003.0 · GHC.Internal.Read
Reading a Void value is always a parse error, considering
Void as a data type with no constructors.
ReadByteOrderDefined in ghc-internal-9.1003.0 · GHC.Internal.ByteOrder
ReadAllDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Semigroup.Internal
ReadAnyDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Semigroup.Internal
ReadVersionDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Version
ReadCBoolDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCClockDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCFloatDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCIntDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCIntMaxDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCLLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCPtrdiffDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCSCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCSUSecondsDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCShortDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCSigAtomicDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCSizeDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCTimeDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCUCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCUIntDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCUIntMaxDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCUIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCULLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCULongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCUSecondsDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCUShortDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadCWcharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
ReadIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Ptr
ReadWordPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Ptr
ReadAssociativityDefined in ghc-internal-9.1003.0 · GHC.Internal.Generics
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.
The Either type represents values with two possibilities: a value of
type Either a b is either Left a or Right b.
The Either type is sometimes used to represent a value which is
either correct or an error; by convention, the Left constructor is
used to hold an error value and the Right constructor is used to
hold a correct value (mnemonic: "right" also means "correct").
Examples
The type EitherStringInt is the type of values which can be either
a String or an Int. The Left constructor can be used only on
Strings, and the Right constructor can be used only on Ints:
Example6 expressions
>>> let s = Left "foo" :: Either String Int>>> sLeft "foo">>> let n = Right 3 :: Either String Int>>> nRight 3>>> :type ss :: Either String Int>>> :type nn :: Either String Int
The fmap from our Functor instance will ignore Left values, but
will apply the supplied function to values contained in a Right:
Example4 expressions
>>> let s = Left "foo" :: Either String Int>>> let n = Right 3 :: Either String Int>>> fmap (*2) sLeft "foo">>> fmap (*2) nRight 6
The Monad instance for Either allows us to chain together multiple
actions which may fail, and fail overall if any of the individual
steps failed. First we'll write a function that can either parse an
Int from a Char, or fail.
Example3 expressions
>>> import Data.Char ( digitToInt, isDigit )>>> :{ let parseEither :: Char -> Either String Int parseEither c | isDigit c = Right (digitToInt c) | otherwise = Left "parse error">>> :}
The following should work, since both '1' and '2' can be
parsed as Ints.
Example2 expressions
>>> :{ let parseMultiple :: Either String Int parseMultiple = do x <- parseEither '1' y <- parseEither '2' return (x + y)>>> :}
Example1 expression
>>> parseMultipleRight 3
But the following should fail overall, since the first operation where
we attempt to parse 'm' as an Int will fail:
Example2 expressions
>>> :{ let parseMultiple :: Either String Int parseMultiple = do x <- parseEither 'm' y <- parseEither '2' return (x + y)>>> :}
The 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 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.
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.