问题
I understand the Parsec
modules' parse
function, which takes a rule argument, an error message, and an input string:
parse rule text = Parsec.parse rule "(source)" text
However, I don't understand the meaning of Parsec.Parsec
, or how it's different from Parsec.ParsecT
. Why do type signatures of custom parsers use this name?
For example, in the following code snippet taken from this blogpost,
myParser :: Parsec.Parsec String () (String,String)
myParser = do
letters <- Parsec.many1 Parsec.letter
Parsec.spaces
digits <- Parsec.many1 Parsec.digit
return (letters,digits)
what does Parsec.Parsec
and ()
mean in myParser
's type signature?
回答1:
ParsecT
and Parsec
In parsec
3, ParsecT
and Parsec
are defined and explained in the Text.Parsec.Prim module:
data ParsecT s u m a
ParsecT s u m a
is a parser with stream types
, user state typeu
, underlying monadm
and return typea
.
(Examples of stream types are String
, ByteString
, and Text
.)
Parsec
is simply a version of ParsecT
specialised to the Identity monad:
type Parsec s u = ParsecT s u Identity
The signature of myParser
explained
Going back to your type signature, in
myParser :: Parsec.Parsec String () (String,String)
- the stream type is
String
; - the user state is simply the empty tuple (also known as "unit"); in other words,
myParser
parses something but doesn't keep track of any useful state; - the result type is a pair of
String
s.
Moreover, the type signature uses Parsec.Parsec
(and not simply Parsec
) because, in the blogpost you link to, Text.Parsec
is imported qualified as Parsec
.
The Parser
type synonym
If all your parsers have stream type String
and don't keep track of any state, you probably want to abstract some of that parsec
complexity away. In that case, you should use the Parser
type synonym, which the Text.Parsec.String
module defines as
type Parser = Parsec String ()
For instance, with the following import
import Text.Parsec.String ( Parser )
you can simplify myParser
's type signature to
myParser :: Parser (String, String)
来源:https://stackoverflow.com/questions/31115506/what-is-the-meaning-of-parsec-string-string-string