I decided to parse versions for an application I’m working on. I haven’t used the elm/parser package very much, and ran into something I didn’t understand, and was hoping someone could help me explain. Given this program:
type alias Version =
( Int, Int, Int )
parser : Parser Version
parser =
Parser.succeed (\ma mi pa -> ( ma, mi, pa ))
|= Parser.int
|. Parser.symbol "."
|= Parser.int
|. Parser.symbol "."
|= Parser.int
I tried to run Parser.run parser "3.0.0", which resulted in Err [{ col = 1, problem = ExpectingInt, row = 1 }]
the “.”-symbol in combination with integers seem to cause the issue, as everything works great if I try to parse “,”-symbols on a string like “3,0,0”.
The problem is the way that the Elm parser works for ints is it parses a number, and then treats anything that isn’t an int as invalid (specifically, int is implemented using number), so it ends up parsing 3.0.0 as the floating point number 3.0 and then failing because that’s not an integer.
You probably need to change to parse for digit characters and then later convert those digits into ints to avoid this.
Yes - like my example using commas I was more interested in finding out why an integer-parser changes behavior based on a character that has nothing to do with integers AFAIK
I think the parser is trying to give an error in the case where it’s parsing a float instead of int. Thus when it sees your “.” it thinks “oh, this is a float, i must fail!” and does so. It is not technically wrong, but it’s an inconvenient design for this case. It would be nice to have one that just accepts the integer once there are no more numbers. I can recommend reading the source if you want to understand further!