简单Haskell Monad -随机数



我试图扩展这篇文章中的代码(接受的答案),以允许我能够调用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检索种子。

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 

最新更新