Random numbers

A pseudo-random number generator (PRNG) is a function g -> (a, g) where the sequence of a values from its repeated application to the g values meets certain criteria. The System.Random module of the random package for Haskell exports a class RandomGen g which promises functions including genWord64 :: g -> (Word64, g). It also exports type StdGen and its instance of the class.

State processor

A PRNG is a state processor. In that regard, the Control.Monad.State.Lazy module of the mtl package exports type StateT:

and type synonym State s a = StateT s Identity a.

The modules also exports class MonadState s m with declaration:

The instances of MonadState include:

Mersenne twister

The System.Random.Mersenne.Pure64 module of the mersenne-random-pure64 package exports type PureMT and its orphan instance of class RandonGen. It also exports functions such as randomWord64 :: PureMT -> (Word64, PureMT).


Some PRNG algorithms involve mutable data structures. The System.Random.Stateful module of the random package exports a class Monad m => StatefulGen g m, a type StateGenM g and an instance:

There is an instance MonadState g (State g).

The following is also exported:

If type g is an instance of RandomGen and type a is an instance of UniformRange (see below), uniformRM can have type StateGenM g -> State g a, and runStateGen g or runStateGen_ g can be applied to it. For example (in GHCi):

Uniform and UniformRange

Module System.Random.Stateful also exports classes UniformRange and Uniform. UniformRange promises method uniformRM :: StatefulGen g m => (a, a) -> g -> m a, and the module exports instances of the class for commonly used types.

Uniform promises method uniformM :: StatefulGen g m => g -> m a, and the module exports instances of the class for commonly used types that are instances of the class Bounded. For example, there is an instance for Int (which is bounded) but not for Integer (which is unbounded).

The functions provided by the instances yield uniform distributions, either from the given range ((a, a)) or from all the values of the type a (which is why a has to be bounded).

Module System.Random exports uniformR :: (RandomGen g, UniformRange a) => (a, a) -> g -> (a, g) and uniform :: (RandomGen g, Uniform a) => g -> (a, g).

Marsaglia’s MWC256

The System.Random.MWC module of the mwc-random package exports type Gen s and instance:

It also exports create :: PrimMonad m => m (Gen (PrimState m)), which is a generator based on a fixed seed. (IO is an instance of PrimMonad and PrimState m is a type synonym associated with the class.)

For example: