[英]How to nondeterministically put a value in a state?
In the following code, how can I replace put 1
with some code that insert nondeterministically 1 or 2 in the state? 在下面的代码中,如何将
put 1
替换为在该状态下插入非确定性1或2的代码?
import Control.Monad.List
import Control.Monad.Trans.State
test :: StateT Int [] Int
test = do
put 1
v <- get
return v
Your monad stack signature is already the correct one. 你的monad堆栈签名已经是正确的了。
Lift a computation from the []
monad and bind to its value. 从
[]
monad中提取计算并绑定到其值。 This will fork the computation: 这将分叉计算:
test :: StateT Int [] Int
test = do
s <- lift [1,2,3]
put s
v <- get
return v
Testing to see it works: 测试看它是否有效:
*Main> runStateT test 10
[(1,1),(2,2),(3,3)]
Not only there are many results, but the state gets included in the nondeterminism as well. 不仅有很多结果,而且国家也包含在非确定性中。
If test
had had type ListT (State Int) Int
, only the results would have been nondetermistic, the state would have been shared among all the branches in the computation: 如果
test
有类型ListT (State Int) Int
,只有结果是非确定的,状态将在计算中的所有分支之间共享 :
test :: ListT (State Int) Int
test = do
s <- ListT $ return [1,2,3]
put s
v <- get
return v
The result: 结果:
*Main> runState (runListT test) 10
([1,2,3],3)
maybe you want something like this instead: 也许你想要这样的东西:
import Control.Monad.List
import Control.Monad.Trans.State
import System.Random (randomIO)
test :: StateT Int IO Int
test = do
put1 <- liftIO $ randomIO
put (if put1 then 1 else 2)
v <- get
return v
This will use the global generator to set 1 or 2 at random 这将使用全局生成器随机设置1或2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.