我正在尝试使用randomRIO生成无限数量的随机数。
import System.Random
g :: IO [Integer]
g = do
n <- randomRIO (1,6) :: IO Integer
f <- g
return (n : f)
Run Code Online (Sandbox Code Playgroud)
它可以编译但在运行时挂起。
好吧,您不能,原因mapMState与您不能懒惰地结束(然后使用结果状态)的原因大致相同。randomRIO生成单个值,并且仅在生成该值后才处理 monadic 程序流。
产生无限随机值流的方法当然是randomRs. 您可以轻松地将其与以下内容结合getStdRandom以生成此类流IO:
import Control.Arrow
randomRsIO :: Random a => (a,a) -> IO [a]
randomRsIO range = getStdRandom $ split >>> first (randomRs range)
Run Code Online (Sandbox Code Playgroud)
接着就,随即,
g :: IO [Integer]
g = randomRsIO (1,6)
Run Code Online (Sandbox Code Playgroud)
The problem with your code is that it never teminates. Whenever you execute g, it initially calcuates the first random number and stores it in n. Then it again recursively calls back to the same function g which goes on and on. To get an infinite list you can use the randomRs function:
g2 :: IO [Integer]
g2 = do
g <- newStdGen
return $ randomRs (1,6) g
Run Code Online (Sandbox Code Playgroud)
And then you can produce any number of random numbers using it:
?> g2 >>= \x -> return $ take 5 $ x
[5,4,6,5,6]
Run Code Online (Sandbox Code Playgroud)