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.
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 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.
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)>>> :}
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 = []
(Enuma, Ca) => Enum (Ta)Defined in non-negative-0.1.2 · Numeric.NonNegative.ChunkyPrivate
(Orda, Numa, Enuma) => Enum (Ta)Defined in non-negative-0.1.2 · Numeric.NonNegative.Wrapper
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 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:
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.
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
Instances163Functor, …
FunctorGenDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Gen
FunctorBlindDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
FunctorFixedDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
FunctorLargeDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
FunctorNegativeDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
FunctorNonEmptyListDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
FunctorNonNegativeDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
FunctorNonPositiveDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
FunctorNonZeroDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
FunctorOrderedListDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
FunctorPositiveDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
FunctorShrink2Defined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
FunctorSmallDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
FunctorSmartDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
FunctorSortedListDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
FunctorRoseDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
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 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.
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
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.
Instances80Monad, …
MonadGenDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Gen
MonadRoseDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
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
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.
OrdASCIIStringDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
OrdPrintableStringDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
OrdUnicodeStringDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
OrdOrdADefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Poly
OrdOrdBDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Poly
OrdOrdCDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Poly
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.
OrdIntSetDefined in containers-0.7 · Data.IntSet.Internal
OrdBigNatDefined in ghc-bignum-1.3 · GHC.Num.BigNat
OrdIntegerDefined in ghc-bignum-1.3 · GHC.Num.Integer
OrdNaturalDefined in ghc-bignum-1.3 · GHC.Num.Natural
OrdExtensionDefined in ghc-boot-th-9.10.3 · GHC.LanguageExtensions.Type
OrdVoidDefined in ghc-internal-9.1003.0 · GHC.Internal.Base
OrdByteOrderDefined in ghc-internal-9.1003.0 · GHC.Internal.ByteOrder
OrdClosureTypeDefined in ghc-internal-9.1003.0 · GHC.Internal.ClosureTypes
OrdBlockReasonDefined in ghc-internal-9.1003.0 · GHC.Internal.Conc.Sync
OrdThreadIdDefined in ghc-internal-9.1003.0 · GHC.Internal.Conc.Sync
OrdThreadStatusDefined in ghc-internal-9.1003.0 · GHC.Internal.Conc.Sync
OrdAllDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Semigroup.Internal
OrdAnyDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Semigroup.Internal
OrdSomeTypeRepDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Typeable.Internal
OrdUniqueDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Unique
OrdVersionDefined in ghc-internal-9.1003.0 · GHC.Internal.Data.Version
OrdTimeoutKeyDefined in ghc-internal-9.1003.0 · GHC.Internal.Event.TimeOut
OrdUniqueDefined in ghc-internal-9.1003.0 · GHC.Internal.Event.Unique
OrdErrorCallDefined in ghc-internal-9.1003.0 · GHC.Internal.Exception
OrdArithExceptionDefined in ghc-internal-9.1003.0 · GHC.Internal.Exception.Type
OrdFingerprintDefined in ghc-internal-9.1003.0 · GHC.Internal.Fingerprint.Type
OrdCBoolDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCClockDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCDoubleDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCFloatDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCIntDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCIntMaxDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCLLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCPtrdiffDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCSCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCSUSecondsDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCShortDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCSigAtomicDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCSizeDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCTimeDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCUCharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCUIntDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCUIntMaxDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCUIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCULLongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCULongDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCUSecondsDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCUShortDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdCWcharDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.C.Types
OrdIntPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Ptr
OrdWordPtrDefined in ghc-internal-9.1003.0 · GHC.Internal.Foreign.Ptr
OrdAssociativityDefined in ghc-internal-9.1003.0 · GHC.Internal.Generics
IEEE 754 Double-precision type includes not only numbers, but also
positive and negative infinities and a special element called NaN
(which can be quiet or signal).
IEEE 754-2008, section 5.11 requires that if at least one of arguments of
<=, <, >, >= is NaN then the result of the comparison is False,
and instanceOrdDouble complies with this requirement. This violates
the reflexivity: both NaN<=NaN and NaN>=NaN are False.
IEEE 754-2008, section 5.10 defines totalOrder predicate. Unfortunately,
compare on Doubles violates the IEEE standard and does not define a total order.
More specifically, both compareNaNx and comparexNaN always return GT.
Thus, users must be extremely cautious when using instanceOrdDouble.
For instance, one should avoid ordered containers with keys represented by Double,
because data loss and corruption may happen. An IEEE-compliant compare is available
in fp-ieee package as TotallyOrdered newtype.
Moving further, the behaviour of min and max with regards to NaN is
also non-compliant. IEEE 754-2008, section 5.3.1 defines that quiet NaN
should be treated as a missing data by minNum and maxNum functions,
for example, minNum(NaN, 1) = minNum(1, NaN) = 1. Some languages such as Java
deviate from the standard implementing minNum(NaN, 1) = minNum(1, NaN) = NaN.
However, min / max in base are even worse: minNaN 1 is 1, but min 1 NaN
is NaN.
IEEE 754-2008 compliant min / max can be found in ieee754 package under
minNum / maxNum names. Implementations compliant with
minimumNumber / maximumNumber from a newer
IEEE 754-2019,
section 9.6 are available from fp-ieee package.
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.
Instances206Read, …
ReadASCIIStringDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
ReadPrintableStringDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
ReadUnicodeStringDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
ReadQCGenDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Random
ReadArgsDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Test
ReadByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Internal.Type
ReadByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Lazy.Internal
ReadShortByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Short.Internal
ReadIntSetDefined in containers-0.7 · Data.IntSet.Internal
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
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.
Instances476Show, …
ShowASCIIStringDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
ShowPrintableStringDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
ShowUnicodeStringDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Modifiers
ShowADefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Poly
ShowBDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Poly
ShowCDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Poly
ShowOrdADefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Poly
ShowOrdBDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Poly
ShowOrdCDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Poly
ShowWitnessDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
ShowQCGenDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Random
ShowConfidenceDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.State
ShowArgsDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Test
ShowResultDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Test
ShowCellDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Text
ShowStrDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Text
ShowByteArrayDefined in base-4.20.2.0 · Data.Array.Byte
ShowTimeoutDefined in base-4.20.2.0 · System.Timeout
ShowBuilderDefined in bytestring-0.12.2.0 · Data.ByteString.Builder · orphan
ShowFormatModeDefined in bytestring-0.12.2.0 · Data.ByteString.Builder.RealFloat
ShowFloatingDecimalDefined in bytestring-0.12.2.0 · Data.ByteString.Builder.RealFloat.D2S
ShowFloatingDecimalDefined in bytestring-0.12.2.0 · Data.ByteString.Builder.RealFloat.F2S
ShowByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Internal.Type
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.
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.
and returns the conjunction of a container of Bools. For the
result to be True, the container must be finite; False, however,
results from a False value finitely far from the left end.
Examples
Basic usage:
Example1 expression
>>> and []True
Example1 expression
>>> and [True]True
Example1 expression
>>> and [False]False
Example1 expression
>>> and [True, True, False]False
Example1 expression
>>> and (False : repeat True) -- Infinite list [False,True,True,True,...False
The 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]])
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.
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:
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
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:
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:
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]
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
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.
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]
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.
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
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:
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.
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.
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 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""
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
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).
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
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 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
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
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.
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]
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.
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
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.
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"]
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]