用户状态(秒差距)
我正在使用秒差距解析一个表达式,并且我想使用秒差距中的用户状态来跟踪这些表达式中的变量。不幸的是我真的不知道该怎么做。
给出以下代码:
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 -> ...
因此,ParsecT sum a
中的 u
将是 Set.Set
。但是我如何将状态更新集成到 var
中?
我尝试了类似 modify $ Set.insert v
的方法,但这不起作用,因为 Set.Set
不是状态单子。
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 '
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不幸的是,Yuras 对 updateParserState 的建议并不是最佳选择(如果您想修改 Parsec 的内部状态,您也可以使用该函数);相反,您应该将一个可处理自定义用户状态(即
u -> u
类型)的函数传递给modifyState
,如本例所示:或使用任意组合
getState
和putState
函数。对于您的情况,您需要执行以下操作:请参阅 此链接了解更多信息。
有关以秒差距处理用户状态的更多类似教程的介绍,此文档虽然旧,但应该是相关的。
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 typeu -> u
) tomodifyState
, such as in this example:or use any combination of the
getState
andputState
functions. For your case, you'd do something like: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.
您可以使用 更新解析器状态
You can use updateParserState