How to parse an integer with a parsec

I expected 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 standard libraries, but I did not find it.

What is the standard way to parse prime natural numbers directly on Integer?

+4
source share
2 answers

Here is what I often do is use the expression

read <$> many1 digit

which can be of type Stream s m Char => ParsecT s u m Integer(or just Parser Integer).

I don't like the use of a partial function read, but when the parser succeeds, I know it readwill succeed and it will be somewhat readable.

+10
source

Text.Parsec.Token, , Parsec . decimal GenLanguageDef. decimal :

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

digit Text.Parsec.Char digitToInt Data.Char.

natural, .

+2

Source: https://habr.com/ru/post/1544217/


All Articles