ReadP and choice
Ian Lynagh
igloo at earth.li
Sat Feb 25 23:21:30 CET 2012
Hi all,
The code below defines a ReadP parser which can parse either a keyword
"wrapper" or an arbitrary identifier. I was hoping that it would give
the output
(CWrapper1,"")
(CWrapper2,"")
(CFunction "wrapper","")
but it actually gives
(CWrapper2,"")
(CFunction "wrapper","")
(CWrapper1,"")
i.e. completed parses are returned before the parse that needs to "look"
at the remaining input.
I can see the logic behind the current behaviour, but in this case at
least it's quite inconvenient.
What do you think?
Did I miss a better way to solve the problem?
Should the behaviour be changed?
If so, is changing it easy?
import Data.Char
import Control.Applicative ((<$>))
import Text.ParserCombinators.ReadP as ReadP
main :: IO ()
main = mapM_ print test
test :: [(CImportSpec, String)]
test = readP_to_S parse "wrapper"
where parse = do r <- choice [
token "wrapper" >> return CWrapper1,
string "wrapper" >> return CWrapper2,
CFunction <$> many1 (satisfy isAlpha)
]
eof
return r
token str = do _ <- string str
toks <- look
case toks of
c : _
| isAlpha c -> pfail
_ -> return ()
data CImportSpec = CFunction String
| CWrapper1
| CWrapper2
deriving Show
Thanks
Ian
More information about the Libraries
mailing list