我正在尝试扩展代码这个帖子 https://stackoverflow.com/questions/3944170/haskell-and-state(接受的答案)允许我能够基于以种子作为参数的函数 randomGen 调用 randomGen2 来获取随机数。但是每次我调用 randomGen2 时,尽管返回一个 Int,我都会收到一个关于无法打印 Random 的错误(事实上我只是尝试打印 Int)。
<interactive>:3:1:
No instance for (Show (Random Int))
arising from a use of `print'
Possible fix: add an instance declaration for (Show (Random Int))
In a stmt of an interactive GHCi command: print it
这是代码:
import Control.Monad.State
type Seed = Int
randomGen :: Seed -> (Int, Seed)
randomGen seed = (seed,seed+1)
type Random a = State Seed a
randomGen2 :: Random Int
randomGen2 = do
seed <- get
let (x,seed') = randomGen seed
put seed'
return x
有任何想法吗?
更新 - 预期行为我希望能够通过口译员(例如 GHCI)来做这件事 -
> getRandomInit 1
> -- some other stuff, e.g. 2 + 3
> getRandom
即我可以使用种子设置 getRandom 函数,然后使用put
,然后该函数返回并退出。然后我做了一些其他的事情,然后再次调用 getRandom,然后从存储种子的 Monad 中检索种子。
randomGen2
返回一个Random Int
这是一个State Seed Int
所以你需要使用runState
通过提供种子值来获得结果,例如
runState randomGen2 1
如果你想继续重复应用randomGen2
您可以创建一个函数,例如:
genRandoms :: Seed -> [Int]
genRandoms s = let (v, s') = runState randomGen2 s in v : genRandoms s'
或者你可以使用sequence
:
genRandoms :: Seed -> [Int]
genRandoms s = fst $ runState (sequence (repeat randomGen2)) s
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)