So I’m still trying to get comfortable using Parsec, but I’m slowly working it into my toolbox.
When I have a file I need to parse, I find myself reading the file in as a string, and then passing the contents to parsec:
problem <- readFile input
case runParser myParser () input problem of
Left err -> hPutStrLn stderr $ "Error: " ++ show err
Right cs -> -- continue processing...
This seems like a fairly common pattern though – is there some existing function that I can use that takes a ParsecT String u IO a and a FilePath and parses the contents? I can’t find anything in hoogle, but that might just be a failure of imagination.
Not
ParsecT, but there’sparseFromFile:: Parser a -> String -> IO (Either ParseError a). However, if your code snippet is accurate, you don’t actually need theIOin your parser, so this shouldn’t be a problem. Something like this should produce the behaviour you want:It’s still a little verbose, but you can define
reportsomewhere common and use it throughout your program; thenparseis a one-liner.