Does Attoparsec support saving and changing user state?

I am using Attoparsec, and I would like to track the value of the user state while parsing the task.

I am familiar with the monadic functions getState, putState and modifyState from Parsec, but I can not find an analog in Attoparsec. Is there a trivial way to do this with something internal to Attoparsec or using the state monad?

+6
source share
1 answer

You can use StateT s Parser , just remember that rollback in the parser also rolls back the state, so you only get these actions with the state that were called in the code path with successful analysis.

 {-# LANGUAGE OverloadedStrings #-} import Data.Attoparsec.ByteString.Char8 import Control.Monad.State import Control.Applicative test :: StateT Int Parser () test = do many $ choice [ (modify (+1) *> lift (string "car")), (modify (+1) *> lift (string "cat"))] pure () parseOnly (runStateT test 0) "catcatcat" -- Right ((),3) 

In addition, we can use most Attoparsec harvesters Attoparsec of the box, because they have common types with the restrictions Alternative , MonadPlus , Applicative or Monad , and StateT through examples for them. We can use lift for the main Parser -s.

+5
source

Source: https://habr.com/ru/post/988087/


All Articles