用户状态(秒差距)

发布于 2024-11-17 06:49:19 字数 714 浏览 0 评论 0原文

我正在使用秒差距解析一个表达式,并且我想使用秒差距中的用户状态来跟踪这些表达式中的变量。不幸的是我真的不知道该怎么做。

给出以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你げ笑在眉眼 2024-11-24 06:49:19

不幸的是,Yuras 对 updateParserState 的建议并不是最佳选择(如果您想修改 Parsec 的内部状态,您也可以使用该函数);相反,您应该将一个可处理自定义用户状态(即 u -> u 类型)的函数传递给 modifyState,如本例所示:

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

或使用任意组合getStateputState 函数。对于您的情况,您需要执行以下操作:

modifyState (Set.insert v)

请参阅 此链接了解更多信息。

有关以秒差距处理用户状态的更多类似教程的介绍,此文档虽然旧,但应该是相关的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文