如何在两个 monad 之间共享状态?
我遇到了以下 monad 问题:
假设我有一个标准 monad 状态,状态为 S = (LS, RS)。我还有另一个 monad:
newtype StateP a = StateP {runP :: S -> (a, RS)}
我想使用 StateP 执行一些计算,然后将状态与 State monad 中的状态合并:
merge m :: StateP() -> State()
merge m = do
s@(l,r) <- get
put (l, snd (runP m s))
它不起作用,但我不明白为什么?还有其他方法可以实现这样的功能吗?
I am stuck with following monad problem:
Let's say I have a standard monad State with state S = (LS, RS). I also have another monad:
newtype StateP a = StateP {runP :: S -> (a, RS)}
I want to perform some computation using StateP then merge state with state in State monad:
merge m :: StateP() -> State()
merge m = do
s@(l,r) <- get
put (l, snd (runP m s))
It is not working, but I don't get why? Is there another way to achieve such functionality?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的代码几乎正确,请尝试
但您确实需要向我们提供更多详细信息。
On the off-chance that your code is nearly right, try
But you need to give us more details really.
您可以使用 monad 转换器,使用两个 monad 堆栈更明确地对这些需求进行建模:一个只能读取
LS
,另一个可以读取和写入LS
。要在
ReadWriteLS
中运行ReadOnlyLS
,我们只需从最外层的状态层中提取出LS
,并将其交给内部计算的读取层即可并将计算结果提升回外部 monad:You can use monad transformers to model these requirements more explicitly using two monad stacks: one that can only read
LS
and one that can both read and writeLS
.To run a
ReadOnlyLS
withinReadWriteLS
, we just need to extractLS
from the outermost state layer, give it to the reader layer of the inner computation and lift the resulting computation back into the outer monad:RunP的功能是如何实现的?你是否为它重新定义了一个 monad 实例并拥有 getP/putP ?你的代码看起来不错,你能提供你使用的m吗?你有什么样的不当行为?
How do you achieve the functionality of RunP? Do you redefine a monad instance for it and have getP/putP? Your code seems fine, can you provide the m you use? What kind of misbehaviour do you get?