What is the meaning of Parsec String () (String,String)?

♀尐吖头ヾ 提交于 2019-12-21 17:32:06

问题


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 type s, user state type u, underlying monad m and return type a.

(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 Strings.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!