Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 了解RandomGen#下一步_Haskell - Fatal编程技术网

Haskell 了解RandomGen#下一步

Haskell 了解RandomGen#下一步,haskell,Haskell,看一看,医生说: next :: g -> (Int, g) The next operation returns an Int that is uniformly distributed in the range returned by genRange (including both end points), and a new generator. 在REPL中使用它,我希望x next打印出相同的数字 ghci> let x = getStdRandom ghci>

看一看,医生说:

next :: g -> (Int, g)

The next operation returns an Int that is uniformly distributed in the range 
returned by genRange (including both end points), and a new generator.
在REPL中使用它,我希望
x next
打印出相同的数字

ghci> let x = getStdRandom
ghci> x next
169285648
ghci> x next
473378030
ghci> x next
896978399

为什么
x next
引用不是透明的,即调用
x next
总是返回相同的输出?

看看
getStdRandom
的定义:

getStdRandom :: (StdGen -> (a,StdGen)) -> IO a
getStdRandom f = atomicModifyIORef theStdGen (swap . f)
换句话说,它是这样做的(但原子性):


要了解这里发生了什么,您需要检查
getStdRandom
的类型签名

> :t getStdRandom
getStdRandom :: (StdGen -> (a, StdGen)) -> IO a
getStdRandom返回
IO a
,因此使用相同的输入返回相同的值不一定在表中

说明其“从当前全局随机生成器获取值,并使用新生成器更新全局生成器”的文档。因此,每次呼叫都会更新全局生成器。

确实如此!不过,您处于
IO()
状态。
ghci> x <- getStdGen
ghci> next x
(803259519,803300211 40692)
ghci> next x
(803259519,803300211 40692)
ghci> next x
(803259519,803300211 40692)
> :t getStdRandom
getStdRandom :: (StdGen -> (a, StdGen)) -> IO a