HORIZON HASKELLDocslts/ghc-9.10.xc74966e2026-09-27Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · c74966e · 2026-09-27

Moduleparsec1-1.0.0.8Haskell98

Text.ParserCombinators.Parsec.Prim

The primitive parser combinators.

  • 3 types
  • 26 values
  • Packageparsec1-1.0.0.8
  • Exports35
  • LanguageHaskell98
  • LicenceBSD-3-Clause
  • SourcePrim.hs
method(*>) :: f a -> f b -> f b
#

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.Charimport GHC.Internal.Text.ParserCombinators.ReadPlet p = string "my name is " *> munch1 isAlpha <* eofreadP_to_S p "my name is Simon"[("Simon","")]
method(<$) :: a -> f b -> f a
#

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
value(<$>) :: Functor f => (a -> b) -> f a -> f b
#

An infix synonym for fmap.

The name of this operator is an allusion to Prelude.$. Note the similarities between their types:

 ($)  ::              (a -> b) ->   a ->   b
(<$>) :: Functor f => (a -> b) -> f a -> f b

Whereas Prelude.$ is function application, <$> is function application lifted over a Functor.

Examples

Convert from a Maybe Int to a Maybe String using show:

Example1 expression
show <$> NothingNothing
Example1 expression
show <$> Just 3Just "3"

Convert from an Either Int Int to an Either Int String using show:

Example1 expression
show <$> Left 17Left 17
Example1 expression
show <$> Right 17Right "17"

Double each element of a list:

Example1 expression
(*2) <$> [1,2,3][2,4,6]

Apply even to the second element of a pair:

Example1 expression
even <$> (2,2)(2,True)
method(<*) :: f a -> f b -> f a
#

Sequence actions, discarding the value of the second argument.

method(<*>) :: f (a -> b) -> f a -> f b
#

Sequential application.

A few functors support an implementation of <*> that is more efficient than the default one.

Example

Used in combination with (Data.Functor.<$>), (<*>) can be used to build a record.

Example1 expression
data MyState = MyState {arg1 :: Foo, arg2 :: Bar, arg3 :: Baz}
Example3 expressions
produceFoo :: Applicative f => f FooproduceBar :: Applicative f => f BarproduceBaz :: Applicative f => f Baz
Example2 expressions
mkState :: Applicative f => f MyStatemkState = MyState <$> produceFoo <*> produceBar <*> produceBaz
value(<?>) :: GenParser tok st a -> String -> GenParser tok st a
#

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.

method(<|>) :: f a -> f a -> f a
#

An associative binary operation

newtypenewtype GenParser tok st a
#
Instances6Monad, Functor, MonadFail, Applicative, Alternative, MonadPlus
  • Monad (GenParser tok st)Defined in parsec1-1.0.0.8 · Text.ParserCombinators.Parsec.Prim
  • Functor (GenParser tok st)Defined in parsec1-1.0.0.8 · Text.ParserCombinators.Parsec.Prim
  • MonadFail (GenParser tok st)Defined in parsec1-1.0.0.8 · Text.ParserCombinators.Parsec.Prim
  • Applicative (GenParser tok st)Defined in parsec1-1.0.0.8 · Text.ParserCombinators.Parsec.Prim
  • Alternative (GenParser tok st)Defined in parsec1-1.0.0.8 · Text.ParserCombinators.Parsec.Prim
  • MonadPlus (GenParser tok st)Defined in parsec1-1.0.0.8 · Text.ParserCombinators.Parsec.Prim
valueparse :: GenParser tok () a -> SourceName -> [tok] -> Either ParseError a
#

parse p filePath input runs a parser p 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 
valueparseTest :: Show a => GenParser tok () a -> [tok] -> IO ()
#

The expression parseTest p input applies a parser p against input input and prints the result to stdout. Used for testing parsers.

valuerunParser
  1. :: GenParser tok st a
  2. -> st
  3. -> SourceName
  4. -> [tok]
  5. -> Either ParseError a
#

The most general way to run a parser. runParser 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 either a ParseError (Left) or a value of type a (Right).

 parseFromFile p fname = do
   input <- readFile fname
   return (runParser p () fname input) 
valuetoken
  1. :: tok -> String
  2. -> tok -> SourcePos
  3. -> tok -> Maybe a
  4. -> GenParser tok st a
#

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 than 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 
valuetokenPrim
  1. :: tok -> String
  2. -> SourcePos -> tok -> [tok] -> SourcePos
  3. -> tok -> Maybe a
  4. -> GenParser tok st a
#

The parser token 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 
valuetokenPrimEx
  1. :: tok -> String
  2. -> SourcePos -> tok -> [tok] -> SourcePos
  3. -> Maybe (SourcePos -> tok -> [tok] -> st -> st)
  4. -> tok -> Maybe a
  5. -> GenParser tok st a
#

The most primitive token recogniser. The expression tokenPrimEx show nextpos mbnextstate test, recognises tokens when test returns Just x (and returns the value x). Tokens are shown in error messages using show. The position is calculated using nextpos, and finally, mbnextstate, can hold a function that updates the user state on every token recognised (nice to count tokens :-). The function is packed into a Maybe type for performance reasons.

valuetry :: GenParser tok st a -> GenParser tok st a
#

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:

 expr        = letExpr <|> identifier <?> "expression"

 letExpr     = string "let" *> ...
 identifier  = many1 letter

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:

 expr        = letExpr <|> identifier <?> "expression"

 letExpr     = try (string "let") *>
 identifier  = many1 letter 
valueunexpected :: String -> GenParser tok st a
#

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.

methodmany :: f a -> f [a]
#

Zero or more.

Examples
Example1 expression
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.

valueskipMany :: GenParser tok st a -> GenParser tok st ()
#

skipMany p applies the parser p zero or more times, skipping its result.

 spaces = skipMany space 
valueupdateState :: (st -> st) -> GenParser tok st ()
#

updateState f applies function f to the user state. Suppose that we want to count identifiers in a source, we could use the user state as:

 expr  = do
   x <- identifier
   updateState (+1)
   return (Id x) 
valuesetInput :: [tok] -> GenParser tok st ()
#

setInput input continues parsing with input.