smilingbuddha
smilingbuddha

Reputation: 14670

Meaning of the string representation of an StdGen type in Haskell

I would like to clarify my understanding of how the System.Random of Haskell works after reading the I/O chapter of Learn You a Haskell For A Great Good.

From what I understand, a value of type StdGen behaves like the generating seed of a random-sequence. That would mean the StdGen type is nothing but a kind of tagged (but random) integer, with the tag being StdGen. Is this correct?

Also getStdGen queries the operating system (or something else possibly?) for a starting seed and the result of executing that action gets stored in gen.

Whenever I try to print a value of type StdGen I see two largish integers always separated by a white-space, as you can see below. I would have imagined that this value would have been a single integer. So what does that white-space stand for?

Prelude System.Random> gen <- getStdGen
Prelude System.Random> 
Prelude System.Random> gen
751404879 1655838864
Prelude System.Random> 

Upvotes: 4

Views: 280

Answers (2)

ErikR
ErikR

Reputation: 52049

StdGen is just a pseudo-random number generator which uses two seed values.

The authors of StdGen have decided to implement its Show instance as just showing the two seed values separated by a space instead of using a more conventional format.

The exact algorithm is given by stdNext in System.Random.

Upvotes: 5

Daniel Wagner
Daniel Wagner

Reputation: 153102

From what I understand, a value of type StdGen behaves like the generating seed of a random-sequence.

This is correct.

That would mean the StdGen type is nothing but a kind of tagged (but random) integer, with the tag being StdGen.

This does not follow. There is no a priori reason to believe that the internal state of a PRNG is a completely unstructured number. Different algorithms use different internal data structures. In the case of StdGen, you can read the source:

data StdGen 
 = StdGen !Int32 !Int32

For this particular algorithm, the internal state is two 32-bit numbers. Other algorithms use more complicated data structures.

Also getStdGen queries the operating system (or something else possibly?) for a starting seed

There is a global IORef containing the seed that notionally gets initialized to mkStdRNG 0 at program startup; you can see the details here.

Whenever I try to print a value of type StdGen I see two largish integers always separated by a white-space, as you can see below. So what does that white-space stand for?

It separates the two Int32 values contained in a StdGen.

Upvotes: 6

Related Questions