问题
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