Convert a single digit Char to the corresponding Int. This
function fails unless its argument satisfies isHexDigit, but
recognises both upper- and lower-case hexadecimal digits (that
is, '0'..'9', 'a'..'f', 'A'..'F').
Examples
Characters '0' through '9' are converted properly to
0..9:
A variant of <*> with the types of the arguments reversed. It differs from
flip(<*>) in that the effects are resolved in the order the arguments are
presented.
Parses a alphabetic or numeric Unicode characters
according to isAlphaNum. Returns the parsed character.
Note that numeric digits outside the ASCII range (such as arabic-indic digits like e.g. "٤" or U+0664),
as well as numeric characters which aren't digits, are parsed by this function
but not by digit.
Parses an alphabetic Unicode characters (lower-case, upper-case and title-case letters,
plus letters of caseless scripts and modifiers letters according to isAlpha).
Returns the parsed character.
chainl p op x parses zero or more occurrences of p,
separated by op. Returns a value obtained by a left associative
application of all functions returned by op to the values returned
by p. If there are zero occurrences of p, the value x is
returned.
chainl1 p op parses one or more occurrences of p,
separated by op Returns a value obtained by a left associative
application of all functions returned by op to the values returned
by p. This parser can for example be used to eliminate left
recursion which typically occurs in expression grammars.
expr = term `chainl1` addop
term = factor `chainl1` mulop
factor = parens expr <|> integer
mulop = do{ symbol "*"; return (*) }
<|> do{ symbol "/"; return (div) }
addop = do{ symbol "+"; return (+) }
<|> do{ symbol "-"; return (-) }
chainr p op x parses zero or more occurrences of p,
separated by op Returns a value obtained by a right associative
application of all functions returned by op to the values returned
by p. If there are no occurrences of p, the value x is
returned.
chainr1 p op x parses one or more occurrences of |p|,
separated by op Returns a value obtained by a right associative
application of all functions returned by op to the values returned
by p.
manyTill p end applies parser pzero or more times until
parser end succeeds. Returns the list of values returned by p.
This parser can be used to scan comments:
notFollowedBy p only succeeds when parser p fails. This parser
does not consume any input. This parser can be used to implement the
'longest match' rule. For example, when recognizing keywords (for
example let), we want to make sure that a keyword is not followed
by a legal identifier character, in which case the keyword is
actually an identifier (for example lets). We can program this
behaviour as follows:
parserTrace label is an impure function, implemented with Debug.Trace that
prints to the console the remaining parser state at the time it is invoked.
It is intended to be used for debugging parsers by inspecting their intermediate states.
parserTraced label p is an impure function, implemented with Debug.Trace that
prints to the console the remaining parser state at the time it is invoked.
It then continues to apply parser p, and if p fails will indicate that
the label has been backtracked.
It is intended to be used for debugging parsers by inspecting their intermediate states.
sepEndBy p sep parses zero or more occurrences of p,
separated and optionally ended by sep, ie. haskell style
statements. Returns a list of values returned by p.
buildExpressionParser table term builds an expression parser for
terms term with operators from table, taking the associativity
and precedence specified in table into account. Prefix and postfix
operators of the same precedence can only occur once (i.e. --2 is
not allowed if - is prefix negate). Prefix and postfix operators
of the same precedence associate to the left (i.e. if ++ is
postfix increment, than -2++ equals -1, not -3).
The buildExpressionParser takes care of all the complexity
involved in building expression parser. Here is an example of an
expression parser that handles prefix signs, postfix increment and
basic arithmetic.
expr = buildExpressionParser table term
<?> "expression"
term = parens expr
<|> natural
<?> "simple expression"
table = [ [prefix "-" negate, prefix "+" id ]
, [postfix "++" (+1)]
, [binary "*" (*) AssocLeft, binary "/" (div) AssocLeft ]
, [binary "+" (+) AssocLeft, binary "-" (-) AssocLeft ]
]
binary name fun assoc = Infix (do{ reservedOp name; return fun }) assoc
prefix name fun = Prefix (do{ reservedOp name; return fun })
postfix name fun = Postfix (do{ reservedOp name; return fun })
The parser p <?> msg behaves as parser p, but whenever the
parser p fails without consuming any input, it replaces expect
error messages with the expect error message msg.
This is normally used at the end of a set alternatives where we want
to return an error message in terms of a higher level construct
rather than returning all possible characters. For example, if the
expr parser from the try example would fail, the error
message is: '...: expecting expression'. Without the (<?>)
combinator, the message would be like '...: expecting "let" or
letter', which is less friendly.
parse p filePath input runs a parser p over Identity without user
state. The filePath is only used in error messages and may be the
empty string. Returns either a ParseError (Left)
or a value of type a (Right).
main = case (parse numbers "" "11, 2, 43") of
Left err -> print err
Right xs -> print (sum xs)
numbers = commaSep integer
parserZero always fails without consuming any input. parserZero is defined
equal to the mzero member of the MonadPlus class and to the empty member
of the Alternative class.
The most general way to run a parser. runParserT p state filePath
input runs parser p on the input list of tokens input,
obtained from source filePath with the initial user state st.
The filePath is only used in error messages and may be the empty
string. Returns a computation in the underlying monad m that return either a ParseError (Left) or a
value of type a (Right).
The parser token showTok posFromTok testTok accepts a token t
with result x when the function testTok t returns Just x. The
source position of the t should be returned by posFromTok t and
the token can be shown using showTok t.
This combinator is expressed in terms of tokenPrim.
It is used to accept user defined token streams. For example,
suppose that we have a stream of basic tokens tupled with source
positions. We can then define a parser that accepts single tokens as:
mytoken x
= token showTok posFromTok testTok
where
showTok (pos,t) = show t
posFromTok (pos,t) = pos
testTok (pos,t) = if x == t then Just t else Nothing
The parser tokenPrim showTok nextPos testTok accepts a token t
with result x when the function testTok t returns Just x. The
token can be shown using showTok t. The position of the next
token should be returned when nextPos is called with the current
source position pos, the current token t and the rest of the
tokens toks, nextPos pos t toks.
This is the most primitive combinator for accepting tokens. For
example, the char parser could be implemented as:
char c
= tokenPrim showChar nextPos testChar
where
showChar x = "'" ++ x ++ "'"
testChar x = if x == c then Just x else Nothing
nextPos pos x xs = updatePosChar pos x
The parser try p behaves like parser p, except that it
pretends that it hasn't consumed any input when an error occurs.
This combinator is used whenever arbitrary look ahead is needed.
Since it pretends that it hasn't consumed any input when p fails,
the (<|>) combinator will try its second alternative even when the
first parser failed while consuming input.
The try combinator can for example be used to distinguish
identifiers and reserved words. Both reserved words and identifiers
are a sequence of letters. Whenever we expect a certain reserved
word where we can also expect an identifier we have to use the try
combinator. Suppose we write:
If the user writes "lexical", the parser fails with: unexpected
'x', expecting 't' in "let". Indeed, since the (<|>) combinator
only tries alternatives when the first alternative hasn't consumed
input, the identifier parser is never tried (because the prefix
"le" of the string "let" parser is already consumed). The
right behaviour can be obtained by adding the try combinator:
The parser unexpected msg always fails with an unexpected error
message msg without consuming any input.
The parsers fail, (<?>) and unexpected are the three parsers
used to generate error messages. Of these, only (<?>) is commonly
used. For an example of the use of unexpected, see the definition
of notFollowedBy.
>>> some (putStr "la")lalalalalalalalala... * goes on forever *
Example1 expression
>>> some Nothingnothing
Example1 expression
>>> take 5 <$> some (Just 1)* hangs forever *
Note that this function can be used with Parsers based on
Applicatives. In that case some parser will attempt to
parse parser one or more times until it fails.
>>> many (putStr "la")lalalalalalalalala... * goes on forever *
Example1 expression
>>> many NothingJust []
Example1 expression
>>> take 5 <$> many (Just 1)* hangs forever *
Note that this function can be used with Parsers based on
Applicatives. In that case many parser will attempt to
parse parser zero or more times until it fails.
AlternativeZipListDefined in ghc-internal-9.1401.0 · GHC.Internal.Functor.ZipList
AlternativeMaybeDefined in ghc-internal-9.1401.0 · GHC.Internal.Base
Picks the leftmost Just value, or, alternatively, Nothing.
AlternativePDefined in ghc-internal-9.1401.0 · GHC.Internal.Text.ParserCombinators.ReadP
AlternativeReadPDefined in ghc-internal-9.1401.0 · GHC.Internal.Text.ParserCombinators.ReadP
AlternativeReadPrecDefined in ghc-internal-9.1401.0 · GHC.Internal.Text.ParserCombinators.ReadPrec
AlternativeIODefined in ghc-internal-9.1401.0 · GHC.Internal.Base
Takes the first non-throwing IO action's result.
empty throws an exception.
AlternativeObjectDefined in json-stream-0.4.6.1 · Data.JsonStream.Parser
AlternativeParserDefined in json-stream-0.4.6.1 · Data.JsonStream.Parser
Match items from the first parser, if none is matched, return items
from the second parser. Constant-space if second parser returns
constant number of items. .| is implemented using this operator.
>>> import Data.Functor.Identity (Identity(..))>>> import Data.Validation.Validation (Validation(..))>>> import Data.Validation.ValidationMonad (ValidationMonadT(..))>>> let ok = ValidatorMonadT (\_ -> ValidationMonadT (Identity (Success 1))) :: ValidatorMonadT Int [String] Identity Int>>> let ValidatorMonadT f = empty <|> ok in let ValidationMonadT (Identity r) = f 0 in rSuccess 1
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","")]
This instance is the most important instance for the Validation data
type. It's responsible for the many implementations. And it allows to accumulate
errors while performing validation or combining the results in the applicative
style.
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
FunctorHintsDefined in plutus-core-1.70.0.0 · UntypedPlutusCore.Transform.Certify.Hints
FunctorInlinePlusDefined in plutus-core-1.70.0.0 · UntypedPlutusCore.Transform.Certify.Hints
FunctorAnnotDetailsDefined in pretty-1.1.3.6 · Text.PrettyPrint.Annotated.HughesPJ
FunctorDocDefined in pretty-1.1.3.6 · Text.PrettyPrint.Annotated.HughesPJ
FunctorSpanDefined in pretty-1.1.3.6 · Text.PrettyPrint.Annotated.HughesPJ
FunctorDocDefined in prettyprinter-1.7.2 · Prettyprinter.Internal
Alter the document’s annotations.
This instance makes Doc more flexible (because it can be used in
Functor-polymorphic values), but fmap is much less readable compared to
using reAnnotate in code that only works for Doc anyway. Consider
using the latter when the type does not matter.
FunctorFlattenResultDefined in prettyprinter-1.7.2 · Prettyprinter.Internal
This instance makes SimpleDocStream more flexible (because it can be used in
Functor-polymorphic values), but fmap is much less readable compared to
using reAnnotateST in code that only works for SimpleDocStream anyway.
Consider using the latter when the type does not matter.
FunctorSimpleDocTreeDefined in prettyprinter-1.7.2 · Prettyprinter.Render.Util.SimpleDocTree
Alter the document’s annotations.
This instance makes SimpleDocTree more flexible (because it can be used in
Functor-polymorphic values), but fmap is much less readable compared to
using reAnnotateST in code that only works for SimpleDocTree anyway.
Consider using the latter when the type does not matter.
FunctorArrayDefined in primitive-0.9.1.0 · Data.Primitive.Array
FunctorSmallArrayDefined in primitive-0.9.1.0 · Data.Primitive.SmallArray
FunctorIDefined in ral-0.2.2 · Data.RAList.Internal
FunctorRAListDefined in ral-0.2.2 · Data.RAList.Internal
FunctorIDefined in ral-0.2.2 · Data.RAList.NonEmpty.Internal
FunctorNERAListDefined in ral-0.2.2 · Data.RAList.NonEmpty.Internal
FunctorDirDefined in ral-0.2.2 · Data.RAList.Tree.Internal
FunctorLeafDefined in ral-0.2.2 · Data.RAList.Tree.Internal
FunctorPoisonableDefined in rawlock-0.1.2.0 · Control.RAWLock
FunctorAcquireDefined in resourcet-1.3.0 · Data.Acquire.Internal
FunctorBlackBoxDefined in small-steps-1.1.4.0 · Control.Provenance
FunctorIDefined in sop-core-0.5.0.2 · Data.SOP.BasicFunctors
FunctorLinearTransformDefined in statistics-0.16.5.0 · Statistics.Distribution.Transform
FunctorPairDefined in statistics-0.16.5.0 · Statistics.Quantile
FunctorTestDefined in statistics-0.16.5.0 · Statistics.Test.Types
FunctorSTMDefined in stm-2.5.3.1 · Control.Sequential.STM
FunctorMaybeDefined in strict-0.5.1 · Data.Strict.Maybe
>>> import Data.Functor.Identity (Identity(..))>>> import Data.Validation.Validation (Validation(..))>>> import Data.Validation.ValidationMonad (ValidationMonadT(..))>>> let v = ValidatorMonadT (\_ -> ValidationMonadT (Identity (Success 1))) :: ValidatorMonadT Int [String] Identity Int>>> let ValidatorMonadT f = fmap (+1) v in let ValidationMonadT (Identity r) = f 0 in rSuccess 2
Functorm => Functor (DecodeStepbytesfailurem)Defined in typed-protocols-1.2.2.0 · Network.TypedProtocol.Codec
Functorw => Functor (ContsTrwm)Defined in adjunctions-4.4.4 · Control.Monad.Trans.Conts
Functorw => Functor (CoTwm)Defined in kan-extensions-5.2.8 · Control.Monad.Co
Because we ignore the second type parameter to Const,
the Applicative instance, which has
(<*>) :: Monoid m => Const m (a -> b) -> Const m a -> Const m b
essentially turns into Monoid m => m -> m -> m, which is (<>)
The abstract data type ParseError represents parse errors. It
provides the source position (SourcePos) of the error
and a list of error messages (Message). A ParseError
can be returned by the function parse. ParseError is an
instance of the Show and Eq classes.
Instances4Eq, Show, Exception, Error
EqParseErrorDefined in parsec-3.1.18.0 · Text.Parsec.Error
ShowParseErrorDefined in parsec-3.1.18.0 · Text.Parsec.Error
This data type specifies operators that work on values of type a.
An operator is either binary infix or unary prefix or postfix. A
binary operator has also an associated associativity.
The abstract data type SourcePos represents source positions. It
contains the name of the source (i.e. file name), a line number and
a column number. SourcePos is an instance of the Show, Eq and
Ord class.
Instances4Eq, Data, Ord, Show
EqSourcePosDefined in parsec-3.1.18.0 · Text.Parsec.Pos
DataSourcePosDefined in parsec-3.1.18.0 · Text.Parsec.Pos
OrdSourcePosDefined in parsec-3.1.18.0 · Text.Parsec.Pos
ShowSourcePosDefined in parsec-3.1.18.0 · Text.Parsec.Pos
ParsecT s u m a is a parser with stream type s, user state type u,
underlying monad m and return type a. Parsec is strict in the user state.
If this is undesirable, simply use a data type like data Box a = Box a and
the state type Box YourStateType to add a level of indirection.
The Semigroup instance for ParsecT is used to append the result
of several parsers, for example:
(many $ char a) <> (many $ char b)
The above will parse a string like "aabbb" and return a successful
parse result "aabbb". Compare against the below which will
produce a result of "bbb" for the same input:
(many $ char a) >> (many $ char b)
(many $ char a) *> (many $ char b)
An instance of Stream has stream type s, underlying monad m and token type t determined by the stream
Some rough guidelines for a "correct" instance of Stream:
unfoldM uncons gives the [t] corresponding to the stream
A Stream instance is responsible for maintaining the "position within the stream" in the stream state s. This is trivial unless you are using the monad in a non-trivial way.