[Haskell-beginners] Problem with Parser combinators

Baa aquagnu at gmail.com
Fri Nov 3 11:43:40 UTC 2017


Hello, all!

I try this parser for `Read` instance:

  import qualified Text.ParserCombinators.ReadP    as P
  import qualified Text.ParserCombinators.ReadPrec as RP
  import Data.Text                                 as T

  instance Read RV where
    readPrec = parens $ do
      RP.lift P.skipSpaces
      s <- RP.look
      guard (not $ null s)
      (RP.+++) (RV1 <$> readPrec::RP.ReadPrec RV) (pure $ RV2 $ T.pack s)

And see that `+++` (or <|>) works in strange way (I don't understand
what happens). IMHO if first parser fails (i.e. `RV1 <$> readPrec::RP.ReadPrec RV`)
then second should return `RV2 $ T.pack s`). But seems that if 1st
fails then all fail too! I tried `+++`, `<++`, `<|>` - the same result.
How is it possible?!

I need to return something if parsing fails. Best is to return another
parser but initial problem was that alternative parser must return the
same type as first one. So, I decided to return "constant" - here it is
`RV2 $ T.pack s`. Guarding from empty string is needed for this
alternative value which I'll return when 1st parser fails. But... seems
something is wrong.


===
Best regards, Paul


More information about the Beginners mailing list