How to add IO to attorarsec Parser correctly?
I want to do some tracing / debugging in the attoparsec parser. Here's a minimal working example:
import Data.Text as T
import Data.Attoparsec.Text
import Data.Attoparsec.Combinator
import Control.Applicative ((<*), (*>))
parseSentences :: Parser [T.Text]
parseSentences = many1 $ takeWhile1 (/= '.') <* char '.' <* skipSpace
parser :: Parser [T.Text]
parser = do
stuff <- parseSentences
-- putStrLn $ "Got stuff: " ++ show stuff
tail <- takeText
-- putStrLn $ "Got tail: " ++ show tail
return $ stuff ++ [tail, T.pack "more stuff"]
main = do
let input = T.pack "sample. example. bang"
print $ parseOnly parser input
What do I need to do to use IO actions in my parser?
+3
source to share
1 answer
If you used the Parsec library, you would be able to use the Parsec monad transformer to mix I / O and parser commands in your code.
Attoparsec, however, is a pure parser, so you will need to use a function Debug.Trace.trace
to output messages to the terminal for debugging purposes.
parser = do
stuff <- parseSentences
tail <- takeText
return .
trace ("Got stuff: " + show stuff) .
trace ("Got tail: " + show tail) $
stuff ++ [tail, T.pack "more stuff"]
Messages will be printed when the associated value is evaluated (here the result of the expression stuff ++ ...
).
+5
source to share