haskell / haskell/parsec

integer dosen't fail for leading white spaces

Open
#39 11 comments 0 reactions 0 assignees View on GitHub
Dominant language
Haskell
Stars
892
Forks
99
PR merge metrics
No merged PRs in 30d

Description

[integer](https://hackage.haskell.org/package/parsec-3.1.9/docs/Text-Parsec-Token.html#v:integer) doesn't behave properly for input with leading white spaces.

```
import Text.Parsec
import Text.Parsec.String (Parser)
import qualified Text.Parsec.Token as P
import Text.Parsec.Language (emptyDef)

lexer =
P.makeTokenParser emptyDef

integer = P.integer lexer
natural = P.natural lexer

integer' :: Parser Integer
integer' = do
f <- option id sign'
n <- natural
return $ f n

sign' :: Parser (Integer -> Integer)
sign' = (char '-' >> return negate)
<|> (char '+' >> return id)

main = do
print . (parse natural "input") $ "1"
print . (parse integer "input") $ "1"
print . (parse integer' "input") $ "1"

print . (parse natural "input") $ " 1"
print . (parse integer "input") $ " 1"
print . (parse integer' "input") $ " 1"

print . (parse natural "input") $ " 1"
print . (parse integer "input") $ " +1"
print . (parse integer' "input") $ " +1"
```

The prime version (`integer'`) is provided to illustrate the expected behavior. The output of above program is:

```
Right 1
Right 1
Right 1
Left "input" (line 1, column 1):
unexpected " "
expecting natural
Right 1
Left "input" (line 1, column 1):
unexpected " "
expecting "-", "+" or natural
Left "input" (line 1, column 1):
unexpected " "
expecting natural
Left "input" (line 1, column 2):
unexpected "+"
expecting digit
Left "input" (line 1, column 1):
unexpected " "
expecting "-", "+" or natural
```

The `integer` parser doesn't fail for `1`, while it should, and it gives misleading error message for `+1`. On the other hand, the error message for `integer'` is more understandable.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.