I am trying to get a better intution of the readP
library :
Why does this:
pLookIf :: Parser String
pLookIf = (do
looked <- look --munch isDigit
e1 <- munch isDigit
if looked == e1 then return ( "(" e1 ")" )
else return "88"
return looked
)
parseString input = readP_to_S (do
e <- pLookIf
eof
return e) input
return:
ghci> parseString "8888888888888"
[("8888888888888","")]
When this
pLook :: Parser String
pLook = (do
looked <- look
return looked
)
parseString input = readP_to_S (do
e <- pLook
eof
return e) input
Returns:
ghci> parseString "8888888888888"
[]
In both cases some value should be returned, considering the signature: look :: ReadP String
CodePudding user response:
Look-ahead: returns the part of the input that is left, without consuming it.
So, we look
at the rest of the input. Then we try eof
, but since we haven't consumed anything we are not at the end of the input and eof
fails, so there are no successful parses.
In pLookIf
we have munch isDigit
which consumes the rest of the input, so we are at the end and eof
succeeds.
To fix pLook
you either need to add something similar to parse up to the end, or just test without the eof
until you have a parser that works on the whole input.