How to parse an Integer with parsec

£可爱£侵袭症+ 提交于 2019-12-10 14:14:06

问题


I was expecting to find a function

integer :: Stream s m Char => ParsecT s u m Integer

or maybe even

natural :: Stream s m Char => ParsecT s u m Integer

in the standard libraries, but I did not find one.

What is the standard way of parsing plain natural numbers directly to an Integer?


回答1:


Here is what I often do is to use the expression

read <$> many1 digit

which can have type Stream s m Char => ParsecT s u m Integer (or simply Parser Integer).

I don’t like the use of the the partial function read, but when the parser succeeds I know that the read will succeed, and it is somewhat readable.




回答2:


Looking at the source of Text.Parsec.Token, it seems Parsec doesn't have a dedicated function for it. They do give a default definition for the decimal field of GenLanguageDef. decimal is defined similar to:

decimal = do
    digits <- many1 baseDigit
    let n = foldl (\x d -> base*x + toInteger (digitToInt d)) 0 digits
    seq n (return n)
  where
    base = 10
    baseDigit = digit

Here, digit is taken from Text.Parsec.Char and digitToInt from Data.Char.

There's also a default definition for natural, which, by default, also parses octal and hexadecimal numbers, and skips trailing whitespace.



来源:https://stackoverflow.com/questions/24171005/how-to-parse-an-integer-with-parsec

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