문제

I want to do some tracing/debugging in my attoparsec parser. Here's minimal [not] 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 i have to do in order to use IO actions in my parser?

도움이 되었습니까?

해결책

If you had used the Parsec library, you would have had the possibility of using the Parsec monad transformer for mixing IO and parser commands in your code.

Attoparsec, however, is a pure parser, so you will have to use the Debug.Trace.trace function 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"]

The messages will be printed when the associated value (here the result of the expression stuff ++ ...) is evaluated.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top