monad 转换器中的内部 monad 是否有 `replicateM` 函数?
假设我有这样的东西:
data Environment = ...
data MyState = ...
data Report = ...
updateState :: Environment -> MyState -> MyState
updateState = ...
report :: MyState -> Report
report = ...
foo :: ReaderT Environment (State MyState) Report
foo = do env <- ask
state <- lift get
let newState = updateState env state
lift $ put newState
return $ report newState
我脑子里是对时间过程的模拟,其中我有将存储在Environment
中的参数,动态状态将存储在MyState
中> 我希望在模拟的每个时间步中收集的信息将存储在报告
中。
现在,我不想运行此模拟的许多步骤并获取包含每个时间步骤的报告的列表。
我通常在没有 ReaderT
的情况下执行此操作,并用于传递如下参数:
foo :: Enviroment -> State MyState Report
然后我会这样做:
manySteps :: Int -> Enviroment -> State MyState [Report]
manySteps n env = replicate n $ (foo env)
我对 lift
和 的类型感到困惑复制M。是否有一个组合可以在变压器内复制 State MyState monad?
将来我会将 ReaderT Environment (State MyState) Report
替换为 ReaderT Environment (StateT MyState (Rand StdGen)) Report
,因此最好在执行此操作之前先把事情做好怪物类型:(。
编辑:作为一个附带问题-是否有比使用ReaderT环境(State MyState)报告
更好的策略?
Suppose I have something like this:
data Environment = ...
data MyState = ...
data Report = ...
updateState :: Environment -> MyState -> MyState
updateState = ...
report :: MyState -> Report
report = ...
foo :: ReaderT Environment (State MyState) Report
foo = do env <- ask
state <- lift get
let newState = updateState env state
lift $ put newState
return $ report newState
What's in my head are simulations of a time process in which I have parameters that will be stored in Environment
, the dynamical state will be stored in MyState
and info I wish to collect in each time step of the simulation will be stored in Report
.
Now, I wan't to run many steps of this simulation and get a list with the reports for each time step.
I usually did this without a ReaderT
and used to pass the parameters like this:
foo :: Enviroment -> State MyState Report
Then I would just do:
manySteps :: Int -> Enviroment -> State MyState [Report]
manySteps n env = replicate n $ (foo env)
I'm getting confused with the types of lift
and replicateM
. Is there a combination that would replicate the State MyState
monad inside the transformer?
In the future I'll replace ReaderT Environment (State MyState) Report
for ReaderT Environment (StateT MyState (Rand StdGen)) Report
so it's better to get things right before having this monster type :(.
edit: as a side question - is there a better strategy than using ReaderT Environment (State MyState) Report
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里有一个replicateM的具体例子:
请注意,我删除了“lift”,因为ReaderT有一个MonadState传递实例。运行 foo 一次给出:
我可以连续运行 foo 七次:
上面的内容需要更多说明吗?
A concrete example of replicateM here:
Note that I removed the "lift" since the ReaderT has a MonadState pass-through instance. Running foo once gives:
I can run foo seven times in a row:
What in the above needs more clarification?
有时,如果您不确定如何使用
GHCi 中的某些内容,那么证明类型就足够了
Sometimes it's enough to prove type if you unsure in the way to use something
Than in GHCi