HORIZON HASKELLDocslts/ghc-10.0.xaa25b892026-10-10Search names, modules, packages, or :: a typeCtrl K

GHC 10.0.0.20260917 · lts/ghc-10.0.x · aa25b89 · 2026-10-10

  • Packagerandom-1.3.1
  • Exports105
  • LanguageHaskell2010
  • LicenceBSD-3-Clause
  • SourceStateful.hs

Pure Random Generator

42 declarations
valuegenByteString :: RandomGen g => Int -> g -> (ByteString, g)
#

Deprecated. In favor of uniformByteString

Generates a ByteString of the specified size using a pure pseudo-random number generator. See uniformByteStringM for the monadic version.

Examples
Example5 expressions
import System.Randomimport Data.ByteStringlet pureGen = mkStdGen 137:seti -Wno-deprecationsunpack . fst . genByteString 10 $ pureGen[51,123,251,37,49,167,90,109,1,4]
valuegetStdRandom :: MonadIO m => (StdGen -> (a, StdGen)) -> m a
#

Uses the supplied function to get a value from the current global random generator, and updates the global generator with the new generator returned by the function. For example, rollDice produces a pseudo-random integer between 1 and 6:

Example2 expressions
rollDice = getStdRandom (randomR (1, 6))replicateM 10 (rollDice :: IO Int)[1,1,1,4,5,6,1,2,2,5]

This is an outdated function and it is recommended to switch to its equivalent applyAtomicGen instead, possibly with the globalStdGen if relying on the global state is acceptable.

Example3 expressions
import System.Random.StatefulrollDice = applyAtomicGen (uniformR (1, 6)) globalStdGenreplicateM 10 (rollDice :: IO Int)[2,1,1,5,4,3,6,6,3,2]
valueinitStdGen :: MonadIO m => m StdGen
#

Initialize StdGen using system entropy (i.e. /dev/urandom) when it is available, while falling back on using system time as the seed.

valuerandomIO :: (Random a, MonadIO m) => m a
#

A variant of randomM that uses the global pseudo-random number generator globalStdGen.

Example2 expressions
import Data.IntrandomIO :: IO Int32114794456

This function is equivalent to getStdRandom random and is included in this interface for historical reasons and backwards compatibility. It is recommended to use uniformM instead, possibly with the globalStdGen if relying on the global state is acceptable.

Example2 expressions
import System.Random.StatefuluniformM globalStdGen :: IO Int32-1768545016
valuerandomRIO :: (Random a, MonadIO m) => (a, a) -> m a
#

A variant of randomRM that uses the global pseudo-random number generator globalStdGen

Example1 expression
randomRIO (2020, 2100) :: IO Int2028

Similar to randomIO, this function is equivalent to getStdRandom randomR and is included in this interface for historical reasons and backwards compatibility. It is recommended to use uniformRM instead, possibly with the globalStdGen if relying on the global state is acceptable.

Example2 expressions
import System.Random.StatefuluniformRM (2020, 2100) globalStdGen :: IO Int2044
valueuniform :: (Uniform a, RandomGen g) => g -> (a, g)
#

Generates a value uniformly distributed over all possible values of that type.

This is a pure version of uniformM.

Examples
Example3 expressions
import System.Randomlet pureGen = mkStdGen 137uniform pureGen :: (Bool, StdGen)(True,StdGen {unStdGen = SMGen 11285859549637045894 7641485672361121627})

You can use type applications to disambiguate the type of the generated numbers:

Example2 expressions
:seti -XTypeApplicationsuniform @Bool pureGen(True,StdGen {unStdGen = SMGen 11285859549637045894 7641485672361121627})
valueuniformByteString :: RandomGen g => Int -> g -> (ByteString, g)
#

Generates a ByteString of the specified size using a pure pseudo-random number generator. See uniformByteStringM for the monadic version.

Examples
Example4 expressions
import System.Randomimport Data.ByteString (unpack)let pureGen = mkStdGen 137unpack . fst $ uniformByteString 10 pureGen[51,123,251,37,49,167,90,109,1,4]
valueuniformFillMutableByteArray
  1. :: RandomGen g
  2. => MutableByteArray s

    Mutable array to fill with random bytes

  3. -> Int

    Offset into a mutable array from the beginning in number of bytes. Offset will be clamped into the range between 0 and the total size of the mutable array

  4. -> Int

    Number of randomly generated bytes to write into the array. This number will be clamped between 0 and the total size of the array without the offset.

  5. -> g
  6. -> ST s g
#

Fill in a slice of a mutable byte array with randomly generated bytes. This function does not fail, instead it clamps the offset and number of bytes to generate into a valid range.

valueuniformList :: (Uniform a, RandomGen g) => Int -> g -> ([a], g)
#

Produce a list of the supplied length with elements generated uniformly.

See uniformListM for a stateful counterpart.

Examples
Example3 expressions
let gen = mkStdGen 2023import Data.Word (Word16)uniformList 5 gen :: ([Word16], StdGen)([56342,15850,25292,14347,13919],StdGen {unStdGen = SMGen 6446154349414395371 1920468677557965761})
valueuniformListR
  1. :: (UniformRange a, RandomGen g)
  2. => Int
  3. -> (a, a)
  4. -> g
  5. -> ([a], g)
#

Produce a list of the supplied length with elements generated uniformly.

See uniformListM for a stateful counterpart.

Examples
Example2 expressions
let gen = mkStdGen 2023uniformListR 10 (20, 30) gen :: ([Int], StdGen)([26,30,27,24,30,25,27,21,27,27],StdGen {unStdGen = SMGen 12965503083958398648 1920468677557965761})
valueuniformR :: (UniformRange a, RandomGen g) => (a, a) -> g -> (a, g)
#

Generates a value uniformly distributed over the provided range, which is interpreted as inclusive in the lower and upper bound.

  • uniformR (1 :: Int, 4 :: Int) generates values uniformly from the set \{1,2,3,4\}

  • uniformR (1 :: Float, 4 :: Float) generates values uniformly from the set \{x\;|\;1 \le x \le 4\}

The following law should hold to make the function always defined:

uniformR (a, b) = uniformR (b, a)

This is a pure version of uniformRM.

Examples
Example3 expressions
import System.Randomlet pureGen = mkStdGen 137uniformR (1 :: Int, 4 :: Int) pureGen(4,StdGen {unStdGen = SMGen 11285859549637045894 7641485672361121627})

You can use type applications to disambiguate the type of the generated numbers:

Example2 expressions
:seti -XTypeApplicationsuniformR @Int (1, 4) pureGen(4,StdGen {unStdGen = SMGen 11285859549637045894 7641485672361121627})
valueuniformRs :: (UniformRange a, RandomGen g) => (a, a) -> g -> [a]
#

Produce an infinite list of pseudo-random values in a specified range. Same as uniforms, integrates nicely with list fusion. There is no way to recover the final generator, therefore either use split before calling uniformRs or use uniformListR instead.

Similar to randomRs, except it relies on UniformRange type class instead of Random.

Examples
Example2 expressions
let gen = mkStdGen 2023take 5 $ uniformRs (10, 100) gen :: [Int][32,86,21,57,39]
valueuniformShuffleList :: RandomGen g => [a] -> g -> ([a], g)
#

Shuffle elements of a list in a uniformly random order.

Examples
Example1 expression
uniformShuffleList "ELVIS" $ mkStdGen 252("LIVES",StdGen {unStdGen = SMGen 17676540583805057877 5302934877338729551})
valueuniforms :: (Uniform a, RandomGen g) => g -> [a]
#

Produce an infinite list of pseudo-random values. Integrates nicely with list fusion. Naturally, there is no way to recover the final generator, therefore either use split before calling uniforms or use uniformList instead.

Similar to randoms, except it relies on Uniform type class instead of Random

Examples
Example3 expressions
let gen = mkStdGen 2023import Data.Word (Word16)take 5 $ uniforms gen :: [Word16][56342,15850,25292,14347,13919]
valuemkStdGen64 :: Word64 -> StdGen
#

Constructs a StdGen deterministically from a Word64 seed.

The difference between mkStdGen is that mkStdGen64 will work the same on 64-bit and 32-bit architectures, while the former can only use 32-bit of information for initializing the psuedo-random number generator on 32-bit operating systems

valueuniformByteArray
  1. :: RandomGen g
  2. => Bool

    Should byte array be allocated in pinned or unpinned memory.

  3. -> Int

    Number of bytes to generate

  4. -> g

    Pure pseudo-random numer generator

  5. -> (ByteArray, g)
#

Efficiently generates a sequence of pseudo-random bytes in a platform independent manner.

valueseedGenTypeName :: SeedGen g => String
#

This is a function that shows the name of the generator type, which is useful for error reporting.

valuewithSeed :: SeedGen g => Seed g -> (g -> (a, g)) -> (a, Seed g)
#

Helper function that allows for operating directly on the Seed, while supplying a function that uses the pseudo-random number generator that is constructed from that Seed.

Example
Example3 expressions
:set -XTypeApplicationsimport System.RandomwithSeed (nonEmptyToSeed (pure 2024) :: Seed StdGen) (uniform @Int)(1039666877624726199,Seed [0xe9, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
valuewithSeedFile
  1. :: (SeedGen g, MonadIO m)
  2. => FilePath
  3. -> Seed g -> m (a, Seed g)
  4. -> m a
#

Read the seed from a file and use it for constructing a pseudo-random number generator. After supplied action has been applied to the constructed generator, the resulting generator will be converted back to a seed and written to the same file.

classclass Random a where
#

The class of types for which random values can be generated. Most instances of Random will produce values that are uniformly distributed on the full range, but for those types without a well-defined "full range" some sensible default subrange will be selected.

Random exists primarily for backwards compatibility with version 1.1 of this library. In new code, use the better specified Uniform and UniformRange instead.

Methods

  • randomR :: RandomGen g => (a, a) -> g -> (a, g)

    Takes a range (lo,hi) and a pseudo-random number generator g, and returns a pseudo-random value uniformly distributed over the closed interval [lo,hi], together with a new generator. It is unspecified what happens if lo>hi, but usually the values will simply get swapped.

    Example3 expressions
    let gen = mkStdGen 26fst $ randomR ('a', 'z') gen'z'fst $ randomR ('a', 'z') gen'z'

    For continuous types there is no requirement that the values lo and hi are ever produced, but they may be, depending on the implementation and the interval.

    There is no requirement to follow the Ord instance and the concept of range can be defined on per type basis. For example product types will treat their values independently:

    Example1 expression
    fst $ randomR (('a', 5.0), ('z', 10.0)) $ mkStdGen 26('z',5.22694980853051)

    In case when a lawful range is desired uniformR should be used instead.

  • random :: RandomGen g => g -> (a, g)

    The same as randomR, but using a default range determined by the type:

    • For bounded types (instances of Bounded, such as Char), the range is normally the whole type.

    • For floating point types, the range is normally the closed interval [0,1].

    • For Integer, the range is (arbitrarily) the range of Int.

  • randomRs :: RandomGen g => (a, a) -> g -> [a]

    Plural variant of randomR, producing an infinite list of pseudo-random values instead of returning a new generator.

  • randoms :: RandomGen g => g -> [a]

    Plural variant of random, producing an infinite list of pseudo-random values instead of returning a new generator.

Instances43Random, …
classclass Finite a where
#

A type class for data with a finite number of inhabitants. This type class is used in the default implementation of System.Random.Stateful.Uniform.

Users are not supposed to write instances of Finite manually. There is a default implementation in terms of Generic instead.

Example4 expressions
:seti -XDeriveGeneric -XDeriveAnyClassimport GHC.Generics (Generic)data MyBool = MyTrue | MyFalse deriving (Generic, Finite)data Action = Code MyBool | Eat (Maybe Bool) | Sleep deriving (Generic, Finite)
Instances23Finite, …
classclass RandomGen g where
#

RandomGen is an interface to pure pseudo-random number generators.

StdGen is the standard RandomGen instance provided by this library.

Methods

Instances8RandomGen, …
newtypenewtype Seed g
#

This is a binary form of pseudo-random number generator's state. It is designed to be safe and easy to use for input/output operations like restoring from file, transmitting over the network, etc.

Constructor is not exported, becasue it is important for implementation to enforce the invariant of the underlying byte array being of the exact same length as the generator has specified in SeedSize. Use mkSeed and unSeed to get access to the raw bytes in a safe manner.

Instances4Eq, Ord, Show, Uniform
  • Eq (Seed g)Defined in random-1.3.1 · System.Random.Internal
  • Ord (Seed g)Defined in random-1.3.1 · System.Random.Internal
  • Show (Seed g)Defined in random-1.3.1 · System.Random.Internal
  • SeedGen g => Uniform (Seed g)Defined in random-1.3.1 · System.Random.Seed · orphan
classclass RandomGen g => SplitGen g where
#

Pseudo-random generators that can be split into two separate and independent psuedo-random generators should provide an instance for this type class.

Historically this functionality was included in the RandomGen type class in the split function, however, few pseudo-random generators possess this property of splittability. This lead the old split function being usually implemented in terms of error.

Methods

  • splitGen :: g -> (g, g)

    Returns two distinct pseudo-random number generators.

    Implementations should take care to ensure that the resulting generators are not correlated.

Instances8SplitGen, …
newtypenewtype StdGen
#

The standard pseudo-random number generator.

Instances7Eq, Show, NFData, RandomGen, SplitGen, SeedGen, …
classclass Uniform a where
#

The class of types for which a uniformly distributed value can be drawn from all possible values of the type.

Instances42Uniform, …
classclass UniformRange a where
#

The class of types for which a uniformly distributed value can be drawn from a range.

Instances45UniformRange, …
classclass (KnownNat (SeedSize g), 1 <= SeedSize g, Typeable g) => SeedGen g where
#

Interface for converting a pure pseudo-random number generator to and from non-empty sequence of bytes. Seeds are stored in Little-Endian order regardless of the platform it is being used on, which provides cross-platform compatibility, while providing optimal performance for the most common platform type.

Conversion to and from a Seed serves as a building block for implementing serialization for any pure or frozen pseudo-random number generator.

It is not trivial to implement platform independence. For this reason this type class has two alternative ways of creating an instance for this class. The easiest way for constructing a platform indepent seed is by converting the inner state of a generator to and from a list of 64 bit words using toSeed64 and fromSeed64 respectively. In that case cross-platform support will be handled automaticaly.

Example6 expressions
:set -XDataKinds -XTypeFamiliesimport Data.Word (Word8, Word32)import Data.Bits ((.|.), shiftR, shiftL)import Data.List.NonEmpty (NonEmpty ((:|)))data FiveByteGen = FiveByteGen Word8 Word32 deriving Show:{instance SeedGen FiveByteGen where  type SeedSize FiveByteGen = 5  fromSeed64 (w64 :| _) =    FiveByteGen (fromIntegral (w64 `shiftR` 32)) (fromIntegral w64)  toSeed64 (FiveByteGen x1 x4) =    let w64 = (fromIntegral x1 `shiftL` 32) .|. fromIntegral x4     in (w64 :| []):}
Example4 expressions
FiveByteGen 0x80 0x01020304FiveByteGen 128 16909060fromSeed (toSeed (FiveByteGen 0x80 0x01020304))FiveByteGen 128 16909060toSeed (FiveByteGen 0x80 0x01020304)Seed [0x04, 0x03, 0x02, 0x01, 0x80]toSeed64 (FiveByteGen 0x80 0x01020304)549772722948 :| []

However, when performance is of utmost importance or default handling of cross platform independence is not sufficient, then an adventurous developer can try implementing conversion into bytes directly with toSeed and fromSeed.

Properties that must hold:

> fromSeed (toSeed gen) == gen
> fromSeed64 (toSeed64 gen) == gen

Note, that there is no requirement for every Seed to roundtrip, eg. this proprty does not even hold for StdGen:

Example2 expressions
let seed = nonEmptyToSeed (0xab :| [0xff00]) :: Seed StdGenseed == toSeed (fromSeed seed)False

Associated types

  • type family SeedSize g :: Nat

    Number of bytes that is required for storing the full state of a pseudo-random number generator. It should be big enough to satisfy the roundtrip property:

    > fromSeed (toSeed gen) == gen
    

Methods

  • fromSeed :: Seed g -> g

    Convert from a binary representation to a pseudo-random number generator

  • toSeed :: g -> Seed g

    Convert to a binary representation of a pseudo-random number generator

  • fromSeed64 :: NonEmpty Word64 -> g

    Construct pseudo-random number generator from a list of words. Whenever list does not have enough bytes to satisfy the SeedSize requirement, it will be padded with zeros. On the other hand when it has more than necessary, extra bytes will be dropped.

    For example if SeedSize is set to 2, then only the lower 16 bits of the first element in the list will be used.

  • toSeed64 :: g -> NonEmpty Word64

    Convert pseudo-random number generator to a list of words

    In case when SeedSize is not a multiple of 8, then the upper bits of the last word in the list will be set to zero.

Instances8SeedGen, …
familytype family SeedSize g :: Nat
#

Number of bytes that is required for storing the full state of a pseudo-random number generator. It should be big enough to satisfy the roundtrip property:

> fromSeed (toSeed gen) == gen
Instances8SeedSize, …

Monadic Random Generator

0 declarations

This module provides type classes and instances for the following concepts:

Monadic pseudo-random number generators

StatefulGen

is an interface to monadic pseudo-random number generators.

Monadic adapters

StateGenM

,

AtomicGenM

,

IOGenM

,

STGenM

and

TGenM

turn a

RandomGen

instance into a

StatefulGen

instance.

Drawing from a range

UniformRange

is used to generate a value of a type uniformly within a range.

This library provides instances of UniformRange for many common numeric types.

Drawing from the entire domain of a type

Uniform

is used to generate a value of a type uniformly over all possible values of that type.

This library provides instances of Uniform for many common bounded numeric types.

Usage

0 declarations

In monadic code, use the relevant Uniform and UniformRange instances to generate pseudo-random values via uniformM and uniformRM, respectively.

As an example, rollsM generates n pseudo-random values of Word in the range [1, 6] in a StatefulGen context; given a monadic pseudo-random number generator, you can run this probabilistic computation using mwc-random as follows:

Example2 expressions
import Control.Monad (replicateM):{let rollsM :: StatefulGen g m => Int -> g -> m [Word]    rollsM n = replicateM n . uniformRM (1, 6):}
import qualified System.Random.MWC as MWC
>>> monadicGen <- MWC.create
>>> rollsM 10 monadicGen :: IO [Word]
[3,4,3,1,4,6,1,6,1,4]

Given a pure pseudo-random number generator, you can run the monadic pseudo-random number computation rollsM in StateT, IO, ST or STM context by applying a monadic adapter like StateGenM, AtomicGenM, IOGenM, STGenM or TGenM (see monadic-adapters) to the pure pseudo-random number generator.

Example2 expressions
let pureGen = mkStdGen 42newIOGenM pureGen >>= rollsM 10 :: IO [Word][1,1,3,2,4,5,3,4,6,2]

Mutable pseudo-random number generator interfaces

11 declarations

Pseudo-random number generators come in two flavours: pure and monadic.

RandomGen: pure pseudo-random number generators

See

System.Random

module.

StatefulGen: monadic pseudo-random number generators

These generators mutate their own state as they produce pseudo-random values. They generally live in

StateT

,

ST

,

IO

or

STM

or some other transformer on top of those monads.

classclass Monad m => StatefulGen g (m :: Type -> Type) where
#

StatefulGen is an interface to monadic pseudo-random number generators.

Methods

Instances5StatefulGen
classclass StatefulGen (MutableGen f m) m => FrozenGen f (m :: Type -> Type) where
#

This class is designed for mutable pseudo-random number generators that have a frozen imutable counterpart that can be manipulated in pure code.

It also works great with frozen generators that are based on pure generators that have a RandomGen instance.

Here are a few laws, which are important for this type class:

  • Roundtrip and complete destruction on overwrite:

overwriteGen mg fg >> freezeGen mg = pure fg
  • Modification of a mutable generator:

overwriteGen mg fg = modifyGen mg (const ((), fg)
  • Freezing of a mutable generator:

freezeGen mg = modifyGen mg (fg -> (fg, fg))

Associated types

Methods

  • freezeGen :: MutableGen f m -> m f

    Saves the state of the pseudo-random number generator as a frozen seed.

  • modifyGen :: MutableGen f m -> (f -> (a, f)) -> m a

    Apply a pure function to the frozen pseudo-random number generator.

  • overwriteGen :: MutableGen f m -> f -> m ()

    Overwrite contents of the mutable pseudo-random number generator with the supplied frozen one

Instances5FrozenGen
classclass FrozenGen f m => ThawedGen f (m :: Type -> Type) where
#

Functionality for thawing frozen generators is not part of the FrozenGen class, becase not all mutable generators support functionality of creating new mutable generators, which is what thawing is in its essence. For this reason StateGen does not have an instance for this type class, but it has one for FrozenGen.

Here is an important law that relates this type class to FrozenGen

  • Roundtrip and independence of mutable generators:

traverse thawGen fgs >>= traverse freezeGen = pure fgs

Methods

  • thawGen :: f -> m (MutableGen f m)

    Create a new mutable pseudo-random number generator from its frozen state.

Instances4ThawedGen
valuewithMutableGen :: ThawedGen f m => f -> (MutableGen f m -> m a) -> m (a, f)
#

Runs a mutable pseudo-random number generator from its FrozenGen state.

Examples
Example2 expressions
import Data.Int (Int8)withMutableGen (IOGen (mkStdGen 217)) (uniformListM 5) :: IO ([Int8], IOGen StdGen)([-74,37,-50,-2,3],IOGen {unIOGen = StdGen {unStdGen = SMGen 4273268533320920145 15251669095119325999}})
valuewithMutableGen_ :: ThawedGen f m => f -> (MutableGen f m -> m a) -> m a
#

Same as withMutableGen, but only returns the generated value.

Examples
Example3 expressions
import System.Random.Statefullet pureGen = mkStdGen 137withMutableGen_ (IOGen pureGen) (uniformRM (1 :: Int, 6 :: Int))4
valuewithSeedMutableGen
  1. :: (SeedGen g, ThawedGen g m)
  2. => Seed g
  3. -> MutableGen g m -> m a
  4. -> m (a, Seed g)
#

Just like withMutableGen, except uses a Seed instead of a frozen generator.

Examples

Here is good example of how withSeedMutableGen can be used with withSeedFile, which uses a locally stored seed.

First we define a reportSeed function that will print the contents of a seed file as a list of bytes:

Example3 expressions
import Data.ByteString as BS (readFile, writeFile, unpack):seti -XOverloadedStringslet reportSeed fp = print . ("Seed: " <>) . show . BS.unpack =<< BS.readFile fp

Given a file path, write an StdGen seed into the file:

Example2 expressions
:seti -XFlexibleContexts -XScopedTypeVariableslet writeInitSeed fp = BS.writeFile fp (unSeedToByteString (toSeed (mkStdGen 2025)))

Apply a StatefulGen monadic action that uses IOGen StdGen, restored from the seed in the given path:

Example1 expression
let withMutableSeedFile fp action = withSeedFile fp (\(seed :: Seed (IOGen StdGen)) -> withSeedMutableGen seed action)

Given a path and an action initialize the seed file and apply the action using that seed:

Example1 expression
let withInitSeedFile fp action = writeInitSeed fp *> reportSeed fp *> withMutableSeedFile fp action <* reportSeed fp

For the sake of example we will use a temporary directory for storing the seed. Here we report the contents of the seed file before and after we shuffle a list:

Example2 expressions
import UnliftIO.Temporary (withSystemTempDirectory)withSystemTempDirectory "random" (\fp -> withInitSeedFile (fp ++ "/seed.bin") (uniformShuffleListM [1..10]))"Seed: [183,178,143,77,132,163,109,14,157,105,82,99,148,82,109,173]""Seed: [60,105,117,203,187,138,69,39,157,105,82,99,148,82,109,173]"[7,5,4,3,1,8,10,6,9,2]
valuerandomM :: (Random a, RandomGen g, FrozenGen g m) => MutableGen g m -> m a
#

Generates a pseudo-random value using monadic interface and Random instance.

Examples
Example4 expressions
import System.Random.Statefullet pureGen = mkStdGen 139g <- newIOGenM pureGenrandomM g :: IO Double0.33775117339631733

You can use type applications to disambiguate the type of the generated numbers:

Example2 expressions
:seti -XTypeApplicationsrandomM @Double g0.9156875994165681
valuerandomRM
  1. :: (Random a, RandomGen g, FrozenGen g m)
  2. => (a, a)
  3. -> MutableGen g m
  4. -> m a
#

Generates a pseudo-random value using monadic interface and Random instance.

Examples
Example4 expressions
import System.Random.Statefullet pureGen = mkStdGen 137g <- newIOGenM pureGenrandomRM (1, 100) g :: IO Int52

You can use type applications to disambiguate the type of the generated numbers:

Example2 expressions
:seti -XTypeApplicationsrandomRM @Int (1, 100) g2
valuesplitGenM :: (SplitGen f, FrozenGen f m) => MutableGen f m -> m f
#

Splits a pseudo-random number generator into two. Overwrites the mutable pseudo-random number generator with one of the immutable pseudo-random number generators produced by a split function and returns the other.

Deprecated

classclass (RandomGen r, StatefulGen g m) => RandomGenM g r (m :: Type -> Type) | g -> r where
#

Deprecated. In favor of FrozenGen

Interface to operations on RandomGen wrappers like IOGenM and StateGenM.

Methods

Instances5RandomGenM

Monadic adapters for pure pseudo-random number generators

0 declarations

Pure pseudo-random number generators can be used in monadic code via the adapters StateGenM, AtomicGenM, IOGenM, STGenM and TGenM

  • StateGenM can be used in any state monad. With strict StateT there is no performance overhead compared to using the RandomGen instance directly. StateGenM is not safe to use in the presence of exceptions and concurrency.

  • AtomicGenM is safe in the presence of exceptions and concurrency since it performs all actions atomically.

  • IOGenM is a wrapper around an IORef that holds a pure generator. IOGenM is safe in the presence of exceptions, but not concurrency.

  • STGenM is a wrapper around an STRef that holds a pure generator. STGenM is safe in the presence of exceptions, but not concurrency.

  • TGenM is a wrapper around a TVar that holds a pure generator. TGenM can be used in a software transactional memory monad STM. It is not as performant as AtomicGenM, but it can provide stronger guarantees in a concurrent setting.

Pure adapter in MonadState

newtypenewtype StateGen g
#

Wrapper for pure state gen, which acts as an immutable seed for the corresponding stateful generator StateGenM

Constructors

Instances11Eq, Ord, Show, Storable, NFData, RandomGen, …
valuerunStateGen :: RandomGen g => g -> (StateGenM g -> State g a) -> (a, g)
#

Runs a monadic generating action in the State monad using a pure pseudo-random number generator.

Examples
Example3 expressions
import System.Random.Statefullet pureGen = mkStdGen 137runStateGen pureGen randomM :: (Int, StdGen)(7879794327570578227,StdGen {unStdGen = SMGen 11285859549637045894 7641485672361121627})
valuerunStateGen_ :: RandomGen g => g -> (StateGenM g -> State g a) -> a
#

Runs a monadic generating action in the State monad using a pure pseudo-random number generator. Returns only the resulting pseudo-random value.

Examples
Example3 expressions
import System.Random.Statefullet pureGen = mkStdGen 137runStateGen_ pureGen randomM :: Int7879794327570578227
valuerunStateGenT
  1. :: RandomGen g
  2. => g
  3. -> StateGenM g -> StateT g m a
  4. -> m (a, g)
#

Runs a monadic generating action in the StateT monad using a pure pseudo-random number generator.

Examples
Example3 expressions
import System.Random.Statefullet pureGen = mkStdGen 137runStateGenT pureGen randomM :: IO (Int, StdGen)(7879794327570578227,StdGen {unStdGen = SMGen 11285859549637045894 7641485672361121627})
valuerunStateGenT_
  1. :: (RandomGen g, Functor f)
  2. => g
  3. -> StateGenM g -> StateT g f a
  4. -> f a
#

Runs a monadic generating action in the StateT monad using a pure pseudo-random number generator. Returns only the resulting pseudo-random value.

Examples
Example3 expressions
import System.Random.Statefullet pureGen = mkStdGen 137runStateGenT_ pureGen randomM :: IO Int7879794327570578227

Mutable thread-safe adapter in IO

newtypenewtype AtomicGen g
#

Frozen version of mutable AtomicGenM generator

Constructors

Instances12Eq, Ord, Show, Storable, NFData, RandomGen, …
newtypenewtype AtomicGenM g
#

Wraps an IORef that holds a pure pseudo-random number generator. All operations are performed atomically.

  • AtomicGenM is safe in the presence of exceptions and concurrency.

  • AtomicGenM is the slowest of the monadic adapters due to the overhead of its atomic operations.

Constructors

Instances2StatefulGen, RandomGenM
valueapplyAtomicGen :: MonadIO m => (g -> (a, g)) -> AtomicGenM g -> m a
#

Atomically applies a pure operation to the wrapped pseudo-random number generator.

Examples
Example4 expressions
import System.Random.Statefullet pureGen = mkStdGen 137g <- newAtomicGenM pureGenapplyAtomicGen random g :: IO Int7879794327570578227

Global mutable standard pseudo-random number generator. This is the same generator that was historically used by randomIO and randomRIO functions.

Example2 expressions
import Control.Monad (replicateM)replicateM 10 (uniformRM ('a', 'z') globalStdGen)"tdzxhyfvgr"

Mutable adapter in IO

newtypenewtype IOGen g
#

Frozen version of mutable IOGenM generator

Constructors

Instances12Eq, Ord, Show, Storable, NFData, RandomGen, …
newtypenewtype IOGenM g
#

Wraps an IORef that holds a pure pseudo-random number generator.

An example use case is writing pseudo-random bytes into a file:

Example3 expressions
import UnliftIO.Temporary (withSystemTempFile)import Data.ByteString (hPutStr)let ioGen g = withSystemTempFile "foo.bin" $ \_ h -> uniformRM (0, 100) g >>= flip uniformByteStringM g >>= hPutStr h

and then run it:

Example1 expression
newIOGenM (mkStdGen 1729) >>= ioGen

Constructors

Instances2StatefulGen, RandomGenM
valueapplyIOGen :: MonadIO m => (g -> (a, g)) -> IOGenM g -> m a
#

Applies a pure operation to the wrapped pseudo-random number generator.

Examples
Example4 expressions
import System.Random.Statefullet pureGen = mkStdGen 137g <- newIOGenM pureGenapplyIOGen random g :: IO Int7879794327570578227

Mutable adapter in ST

newtypenewtype STGen g
#

Frozen version of mutable STGenM generator

Constructors

Instances12Eq, Ord, Show, Storable, NFData, RandomGen, …
valueapplySTGen :: (g -> (a, g)) -> STGenM g s -> ST s a
#

Applies a pure operation to the wrapped pseudo-random number generator.

Examples
Example3 expressions
import System.Random.Statefullet pureGen = mkStdGen 137(runSTGen pureGen (\g -> applySTGen random g)) :: (Int, StdGen)(7879794327570578227,StdGen {unStdGen = SMGen 11285859549637045894 7641485672361121627})
valuerunSTGen :: RandomGen g => g -> (forall s. STGenM g s -> ST s a) -> (a, g)
#

Runs a monadic generating action in the ST monad using a pure pseudo-random number generator.

Examples
Example3 expressions
import System.Random.Statefullet pureGen = mkStdGen 137(runSTGen pureGen (\g -> applySTGen random g)) :: (Int, StdGen)(7879794327570578227,StdGen {unStdGen = SMGen 11285859549637045894 7641485672361121627})
valuerunSTGen_ :: RandomGen g => g -> (forall s. STGenM g s -> ST s a) -> a
#

Runs a monadic generating action in the ST monad using a pure pseudo-random number generator. Returns only the resulting pseudo-random value.

Examples
Example3 expressions
import System.Random.Statefullet pureGen = mkStdGen 137(runSTGen_ pureGen (\g -> applySTGen random g)) :: Int7879794327570578227

Mutable thread-safe adapter in STM

newtypenewtype TGen g
#

Frozen version of mutable TGenM generator

Constructors

Instances12Eq, Ord, Show, Storable, NFData, RandomGen, …
valueapplyTGen :: (g -> (a, g)) -> TGenM g -> STM a
#

Applies a pure operation to the wrapped pseudo-random number generator.

Examples
Example6 expressions
import Control.Concurrent.STMimport System.Random.Statefulimport Data.Int (Int32)let pureGen = mkStdGen 137stmGen <- newTGenMIO pureGenatomically $ applyTGen uniform stmGen :: IO Int32637238067

Pseudo-random values of various types

5 declarations

This library provides two type classes to generate pseudo-random values:

  • UniformRange is used to generate a value of a type uniformly within a range.

  • Uniform is used to generate a value of a type uniformly over all possible values of that type.

Types may have instances for both or just one of UniformRange and Uniform. A few examples illustrate this:

  • Int, Word16 and Bool are instances of both UniformRange and Uniform.

  • Integer, Float and Double each have an instance for UniformRange but no Uniform instance.

  • A hypothetical type Radian representing angles by taking values in the range [0, 2π) has a trivial Uniform instance, but no UniformRange instance: the problem is that two given Radian values always span two ranges, one clockwise and one anti-clockwise.

  • It is trivial to construct a Uniform (a, b) instance given Uniform a and Uniform b (and this library provides this tuple instance).

  • On the other hand, there is no correct way to construct a UniformRange (a, b) instance based on just UniformRange a and UniformRange b.

classclass Uniform a where
#

The class of types for which a uniformly distributed value can be drawn from all possible values of the type.

Methods

  • uniformM :: StatefulGen g m => g -> m a

    Generates a value uniformly distributed over all possible values of that type.

    There is a default implementation via Generic:

    Example7 expressions
    :seti -XDeriveGeneric -XDeriveAnyClassimport GHC.Generics (Generic)import System.Random.Statefuldata MyBool = MyTrue | MyFalse deriving (Show, Generic, Finite, Uniform)data Action = Code MyBool | Eat (Maybe Bool) | Sleep deriving (Show, Generic, Finite, Uniform)gen <- newIOGenM (mkStdGen 42)uniformListM 10 gen :: IO [Action][Code MyTrue,Code MyTrue,Eat Nothing,Code MyFalse,Eat (Just False),Eat (Just True),Eat Nothing,Eat (Just False),Sleep,Code MyFalse]
Instances42Uniform, …
valueuniformViaFiniteM
  1. :: (StatefulGen g m, Generic a, GFinite (Rep a))
  2. => g
  3. -> m a
#

A definition of Uniform for Finite types. If your data has several fields of sub-Word cardinality, this instance may be more efficient than one, derived via Generic and GUniform.

Example7 expressions
:seti -XDeriveGeneric -XDeriveAnyClassimport GHC.Generics (Generic)import System.Random.Statefuldata Triple = Triple Word8 Word8 Word8 deriving (Show, Generic, Finite)instance Uniform Triple where uniformM = uniformViaFiniteMgen <- newIOGenM (mkStdGen 42)uniformListM 5 gen :: IO [Triple][Triple 60 226 48,Triple 234 194 151,Triple 112 96 95,Triple 51 251 15,Triple 6 0 208]
classclass UniformRange a where
#

The class of types for which a uniformly distributed value can be drawn from a range.

Methods

  • uniformRM :: StatefulGen g m => (a, a) -> g -> m a

    Generates a value uniformly distributed over the provided range, which is interpreted as inclusive in the lower and upper bound.

    • uniformRM (1 :: Int, 4 :: Int) generates values uniformly from the set \{1,2,3,4\}

    • uniformRM (1 :: Float, 4 :: Float) generates values uniformly from the set \{x\;|\;1 \le x \le 4\}

    The following law should hold to make the function always defined:

    uniformRM (a, b) = uniformRM (b, a)

    The range is understood as defined by means of isInRange, so

    isInRange (a, b) <$> uniformRM (a, b) gen == pure True

    but beware of floating point number caveats.

    There is a default implementation via Generic:

    Example8 expressions
    :seti -XDeriveGeneric -XDeriveAnyClassimport GHC.Generics (Generic)import Data.Word (Word8)import Control.Monad (replicateM)import System.Random.Statefulgen <- newIOGenM (mkStdGen 42)data Tuple = Tuple Bool Word8 deriving (Show, Generic, UniformRange)replicateM 10 (uniformRM (Tuple False 100, Tuple True 150) gen)[Tuple False 102,Tuple True 118,Tuple False 115,Tuple True 113,Tuple True 126,Tuple False 127,Tuple True 130,Tuple False 113,Tuple False 150,Tuple False 125]
  • isInRange :: (a, a) -> a -> Bool

    A notion of (inclusive) ranges prescribed to a.

    Ranges are symmetric:

    isInRange (lo, hi) x == isInRange (hi, lo) x

    Ranges include their endpoints:

    isInRange (lo, hi) lo == True

    When endpoints coincide, there is nothing else:

    isInRange (x, x) y == x == y

    Endpoints are endpoints:

    isInRange (lo, hi) x ==>
    isInRange (lo, x) hi == x == hi

    Ranges are transitive relations:

    isInRange (lo, hi) lo' && isInRange (lo, hi) hi' && isInRange (lo', hi') x
    ==> isInRange (lo, hi) x

    There is a default implementation of isInRange via Generic. Other helper function that can be used for implementing this function are isInRangeOrd and isInRangeEnum.

    Note that the isRange method from Data.Ix is not a suitable default implementation of isInRange. Unlike isInRange, isRange is not required to be symmetric, and many isRange implementations are not symmetric in practice.

Instances45UniformRange, …
valueisInRangeOrd :: Ord a => (a, a) -> a -> Bool
#

Utilize Ord instance to decide if a value is within the range. Designed to be used for implementing isInRange

Lists

valueuniformListM :: (StatefulGen g m, Uniform a) => Int -> g -> m [a]
#

Generates a list of pseudo-random values.

Examples
Example4 expressions
import System.Random.Statefullet pureGen = mkStdGen 137g <- newIOGenM pureGenuniformListM 10 g :: IO [Bool][True,True,True,True,False,True,True,False,False,False]
valueuniformListRM
  1. :: (StatefulGen g m, UniformRange a)
  2. => Int
  3. -> (a, a)
  4. -> g
  5. -> m [a]
#

Generates a list of pseudo-random values in a specified range.

Examples
Example4 expressions
import System.Random.Statefullet pureGen = mkStdGen 137g <- newIOGenM pureGenuniformListRM 10 (20, 30) g :: IO [Int][23,21,28,25,28,28,26,25,29,27]
valueuniformShuffleListM :: StatefulGen g m => [a] -> g -> m [a]
#

Shuffle elements of a list in a uniformly random order.

Examples
Example2 expressions
import System.Random.StatefulrunStateGen_ (mkStdGen 127) $ uniformShuffleListM "ELVIS""LIVES"

Generators for sequences of pseudo-random bytes

Helper functions for createing instances

0 declarations

Sequences of bytes

Floating point numbers

Enum types

valueuniformEnumM :: (Enum a, Bounded a, StatefulGen g m) => g -> m a
#

Generates uniformly distributed Enum. One can use it to define a Uniform instance:

data Colors = Red | Green | Blue deriving (Enum, Bounded)
instance Uniform Colors where uniformM = uniformEnumM
valueuniformEnumRM :: (Enum a, StatefulGen g m) => (a, a) -> g -> m a
#

Generates uniformly distributed Enum in the given range. One can use it to define a UniformRange instance:

data Colors = Red | Green | Blue deriving (Enum)
instance UniformRange Colors where
  uniformRM = uniformEnumRM
  inInRange (lo, hi) x = isInRange (fromEnum lo, fromEnum hi) (fromEnum x)

Word

Appendix

0 declarations

How to implement StatefulGen

Typically, a monadic pseudo-random number generator has facilities to save and restore its internal state in addition to generating pseudo-random numbers.

Here is an example instance for the monadic pseudo-random number generator from the mwc-random package:

import qualified System.Random.MWC as MWC
import qualified Data.Vector.Generic as G
instance (s ~ PrimState m, PrimMonad m) => StatefulGen (MWC.Gen s) m where
  uniformWord8 = MWC.uniform
  uniformWord16 = MWC.uniform
  uniformWord32 = MWC.uniform
  uniformWord64 = MWC.uniform
  uniformByteArrayM isPinned n g = stToPrim (fillByteArrayST isPinned n (MWC.uniform g))
instance PrimMonad m => FrozenGen MWC.Seed m where
  type MutableGen MWC.Seed m = MWC.Gen (PrimState m)
  freezeGen = MWC.save
  overwriteGen (Gen mv) (Seed v) = G.copy mv v
instance PrimMonad m => ThawedGen MWC.Seed m where
  thawGen = MWC.restore
FrozenGen

FrozenGen gives us ability to use most of stateful pseudo-random number generator in its immutable form, if one exists that is. The biggest benefit that can be drawn from a polymorphic access to a stateful pseudo-random number generator in a frozen form is the ability to serialize, deserialize and possibly even use the stateful generator in a pure setting without knowing the actual type of a generator ahead of time. For example we can write a function that accepts a frozen state of some pseudo-random number generator and produces a short list with random even integers.

Example3 expressions
import Data.Int (Int8)import Control.Monad (replicateM):{myCustomRandomList :: ThawedGen f m => f -> m [Int8]myCustomRandomList f =  withMutableGen_ f $ \gen -> do    len <- uniformRM (5, 10) gen    replicateM len $ do      x <- uniformM gen      pure $ if even x then x else x + 1:}

and later we can apply it to a frozen version of a stateful generator, such as STGen:

Example1 expression
print $ runST $ myCustomRandomList (STGen (mkStdGen 217))[-50,-2,4,-8,-58,-40,24,-32,-110,24]

Alternatively, instead of discarding the final state of the generator, as it happens above, we could have used withMutableGen, which together with the result would give us back its frozen form. This would allow us to store the end state of our generator somewhere for the later reuse.

Floating point number caveats

valuescaleFloating
  1. :: (RealFloat a, Integral w, Bounded w, FiniteBits w)
  2. => a

    Low

  3. -> a

    High

  4. -> w

    Uniformly distributed unsigned integral value that will be used for converting to a floating point value and subsequent scaling to the specified range

  5. -> a
#

This is the function that is used to scale a floating point value from random word range to the custom [low, high] range.

Due to rounding errors, floating point operations are neither associative nor distributive the way the corresponding operations on real numbers are. Additionally, floating point numbers admit special values NaN as well as negative and positive infinity.

The UniformRange instances for Float and Double use the following procedure to generate a random value in a range for uniformRM (l, h) g:

  • If l == h, return: l.

  • If isInfinite l == True or isInfinite h == True, return: l + h

  • Otherwise:

    1. Generate an unsigned integral of matching width w uniformly.

    2. Check whether h - l overflows to infinity and, if it does, then convert w to a floating point number in [0.0, 1.0] range through division of w by the highest possible value:

      x = fromIntegral w / fromIntegral maxBound
      

      Then we scale and clamp it before returning it:

      max (min (x * l + (1 - x) * h) (max l h)) (min l h)
      

      Clamping is necessary, because otherwise it would be possible to run into a degenerate case when a scaled value is outside the specified range due to rounding errors.

    3. Whenever h - l does not overflow, we use this common formula for scaling: l + (h - l) * x. However, instead of using [0.0, 1.0] range we use the top most bit of w to decide whether we will treat the generated floating point value as [0.0, 0.5] range or [0.5, 1.0] range and use the left over bits to produce a floating point value in the half unit range:

      x = fromIntegral (clearBit w 31) / fromIntegral maxBound
      

      Further scaling depends on the top most bit:

      if testBit w 31
         then l + (h - l) * x
         else h + (l - h) * x
      

      Because of this clever technique the result does not need clamping, since scaled values are guaranteed to stay within the specified range. Another reason why this tecnique is used for the common case instead of the one described in 2. is because it avoids usage of 1 - x, which consequently reduces loss of randomness due to rounding.

What happens when NaN or Infinity are given to uniformRM? We first define them as constants:

Example3 expressions
nan = read "NaN" :: Floatinf = read "Infinity" :: Floatg <- newIOGenM (mkStdGen 2024)
  • If at least one of l or h is NaN, the result is NaN.

    Example2 expressions
    uniformRM (nan, 1) gNaNuniformRM (-1, nan) gNaN
  • If l and h are both Infinity with opposing signs, then the result is NaN.

    Example2 expressions
    uniformRM (-inf, inf) gNaNuniformRM (inf, -inf) gNaN
  • Otherwise, if l is Infinity or -Infinity, the result is l.

    Example2 expressions
    uniformRM (inf, 1) gInfinityuniformRM (-inf, 1) g-Infinity
  • Otherwise, if h is Infinity or -Infinity, the result is h.

    Example2 expressions
    uniformRM (1, inf) gInfinityuniformRM (1, -inf) g-Infinity

Note that the GCC 10.1.0 C++ standard library, the Java 10 standard library and CPython 3.8 use a similar procedure to generate floating point values in a range.

References

0 declarations
  1. Guy L. Steele, Jr., Doug Lea, and Christine H. Flood. 2014. Fast splittable pseudorandom number generators. In Proceedings of the 2014 ACM International Conference on Object Oriented Programming Systems Languages & Applications (OOPSLA '14). ACM, New York, NY, USA, 453-472. DOI: https://doi.org/10.1145/2660193.2660195