【发布时间】:2014-05-11 16:54:56
【问题描述】:
我正在尝试扩展 this post(已接受的答案)中的代码,以允许我能够调用 randomGen2 以获取随机数,基于以种子为参数的函数 randomGen。但是每次我调用 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 中检索种子。
【问题讨论】:
-
getRandomInit是System.Random.setStdGen。请注意,setStdGen采用StdGen而不是Int。您可以使用mkStdGen从Int创建一个。getRandom是System.Random.randomIO。查看文档以获取更多详细信息。还要记住,如果你想要一个全局状态,它必须存在于IO中——你不能使用State。
标签: haskell random state monads random-seed