Using global random number generator via getStdGen in Haskell

I just started to study Haskellwith a pleasant reading, "Find out that you are Haskell for the great good!" and there’s an example in the book that makes no sense to me. It says that the following code will output the same random string twice:

main = do
    gen <- getStdGen
    putStrLn $ take 20 (randomRs ('a','z') gen)
    gen2 <- getStdGen
    putStrLn $ take 20 (randomRs ('a','z') gen2)

On the other hand, if the same program is called twice, it will undoubtedly give different results. Moreover, this does not seem consistent if I compare it with the code below, which gives different values s1and s2:

main = do
    s1 <- getLine
    s2 <- getLine
    putStrLn s1
    putStrLn s2

I am wondering how these two examples differ.

+4
source share
2 answers

getStdGen: getLine, "" IO, , . , , , ( , setStdGen), IO.

, :

main = do
    file <- readFile "/etc/bash.bashrc"  -- or any other persistent system file
    putStrLn $ head (lines file)
    file2 <- readFile "/etc/bash.bashrc"
    putStrLn $ head (lines file2)
+6

:

-- |Gets the global random number generator.
getStdGen :: IO StdGen
getStdGen  = readIORef theStdGen

theStdGen :: IORef StdGen
theStdGen  = unsafePerformIO $ do
   rng <- mkStdRNG 0
   newIORef rng

mkStdRNG :: Integer -> IO StdGen
mkStdRNG o = do
    ct          <- getCPUTime
    (sec, psec) <- getTime
    return (createStdGen (sec * 12345 + psec + ct + o))

, getStdGen: IORef, .

+3

Source: https://habr.com/ru/post/1524913/


All Articles