User state in Parsec

萝らか妹 提交于 2019-12-04 17:23:19

问题


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.


回答1:


Unfortunately, Yuras' suggestion of updateParserState is not optimal (you'd use that function if you're looking to modify Parsec's internal state as well); instead you should pass a function that works over your custom user state (i.e. of type u -> u) to modifyState, such as in this example:

expr  = do
  x <- identifier
  modifyState (+1)
  -- ^ in this example, our type u is Int
  return (Id x)

or use any combination of the getState and putState functions. For your case, you'd do something like:

modifyState (Set.insert v)

See this link for more info.

For a more tutorial-like introduction to working with user state in Parsec, this document, though old, should be relevant.




回答2:


You can use updateParserState



来源:https://stackoverflow.com/questions/6477541/user-state-in-parsec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!