User state in Parsec

Viewed 3507

I'm parsing an expression using Parsec and I want to keep track of variables in these expressions using the user state in Parsec. Unfortunately I don't really get how to do it.

Given the following code:

import Data.Set as Set
inp = "$x = $y + $z"

data Var = V String

var = do char '$'
      n <- many1 letter
      let v = Var n
       -- I want to modify the set of variables here
      return v

parseAssignment = ... -- parses the above assignment

run = case runIdentity $ runParserT parseAssignment Set.empty "" inp of
                   Left err -> ...
                   Right -> ...

So, the u in ParsecT s u m a would be Set.Set. But how would I integrate the state update into var?

I tried something like modify $ Set.insert v, but this doesn't work, since Set.Set is not a state monad.

2 Answers
Related