Consider this parser that converts digit strings to int
s:
let toInt (s:string) =
match Int32.TryParse(s) with
| (true, n) -> preturn n
| _ -> fail "Number must be below 2147483648"
let naturalNum = many1Chars digit >>= toInt <?> "natural number"
When I run it on non-numeric strings like "abc"
it shows the correct error message:
Error in Ln: 1 Col: 1
abc
^
Expecting: natural number
But when I give it a numeric string exceeding the int
range it gives the following counter-productive message:
Error in Ln: 1 Col: 17
9999999999999999
^
Note: The error occurred at the end of the input stream.
Expecting: decimal digit
Other error messages:
Number must be below 2147483648
The primary message "Expecting: decimal digit"
makes no sense, because we have to many digits already.
Is there a way to get rid of it and only show "Number must be below 2147483648"
?
Full example:
open System
open FParsec
[<EntryPoint>]
let main argv =
let toInt (s:string) =
match Int32.TryParse(s) with
| (true, n) -> preturn n
| _ -> fail "Number must be below 2147483648"
let naturalNum = many1Chars digit >>= toInt <?> "natural number"
match run naturalNum "9999999999999999" with
| Failure (msg, _, _) -> printfn "%s" msg
| Success (a, _, _) -> printfn "%A" a
0
fail ...
. – Duaxmany1Chars digit
will do thefail
for us when we feed the parser"abc"
. Only intoInt
we have to do it ourselves. – Bora