The Lean Language Reference

15.10. Random Numbers

🔗def
IO.setRandSeed (n : Nat) : BaseIO Unit
IO.setRandSeed (n : Nat) : BaseIO Unit

Seeds the random number generator state used by IO.rand.

🔗def
IO.rand (lo hi : Nat) : BaseIO Nat
IO.rand (lo hi : Nat) : BaseIO Nat

Returns a pseudorandom number between lo and hi, using and updating a saved random generator state.

This state can be seeded using IO.setRandSeed.

🔗def
randBool.{u} {gen : Type u} [RandomGen gen] (g : gen) : Bool × gen
randBool.{u} {gen : Type u} [RandomGen gen] (g : gen) : Bool × gen

Generates a random Boolean.

🔗def
randNat.{u} {gen : Type u} [RandomGen gen] (g : gen) (lo hi : Nat) : Nat × gen
randNat.{u} {gen : Type u} [RandomGen gen] (g : gen) (lo hi : Nat) : Nat × gen

Generates a random natural number in the interval [lo, hi].

15.10.1. Random Generators

🔗type class
RandomGen.{u} (g : Type u) : Type u
RandomGen.{u} (g : Type u) : Type u

Interface for random number generators.

Instance Constructor

RandomGen.mk.{u}

Methods

range : gNat × Nat

range returns the range of values returned by the generator.

next : gNat × g

next operation returns a natural number that is uniformly distributed the range returned by range (including both end points), and a new generator.

split : gg × g

The 'split' operation allows one to obtain two distinct random number generators. This is very useful in functional programs (for example, when passing a random number generator down to recursive calls).

🔗structure
StdGen : Type
StdGen : Type

"Standard" random number generator.

🔗def
stdRange : Nat × Nat
stdRange : Nat × Nat

The range of values returned by StdGen

🔗def
stdNext : StdGenNat × StdGen
stdNext : StdGenNat × StdGen

The next value from a StdGen, paired with an updated generator state.

🔗def
stdSplit : StdGenStdGen × StdGen
stdSplit : StdGenStdGen × StdGen

Splits a StdGen into two separate states.

🔗def
mkStdGen (s : Nat := 0) : StdGen
mkStdGen (s : Nat := 0) : StdGen

Returns a standard number generator.

15.10.2. System Randomness

🔗opaque
IO.getRandomBytes (nBytes : USize) : IO ByteArray
IO.getRandomBytes (nBytes : USize) : IO ByteArray

Reads bytes from a system entropy source. It is not guaranteed to be cryptographically secure.

If nBytes is 0, returns immediately with an empty buffer.