Skip to content

std::random

Pseudo-random values from a seed. A random.Generator<T> describes how to produce a T. Generator.step runs it with a random.Seed and returns the value and the next seed. The same seed always gives the same value, so a draw can be repeated and tested. There is no global generator and nothing is mutated: a program passes the seed along itself, or composes generators with map and flat_map. Two functions read the operating system’s entropy instead: Seed.from_os, for a starting seed, and random.secure_bytes, for keys, tokens and salts, which a seeded generator must never make.

seed = Seed.from_int(42)

die = Generator.int(1..=6)

(roll, seed) = die |> Generator.step(seed)

(next, _) = die |> Generator.step(seed) // the new seed gives a new draw

When several draws are known up front, compose them into one generator and step once. Pass the random.Seed along by hand only when other work happens between the draws, such as across turns of an interactive loop. There are no map2 or map3 functions: flat_map and map build any composite generator.

Import with import std::random.

subtype FiniteRange BoundedRange<Float> when fn r -> Float.is_finite(Range.start(r)) and Float.is_finite(Maybe.with_default(Range.stop(r), Float.nan()))

A range of Floats that holds a value and has an end, both ends finite: what Generator.float draws from, since an infinite end has no uniform draw. It narrows BoundedRange<Float> to finite ends, so it has no NaN end either, and a backwards or empty literal breaks NonEmptyRange’s rule. A literal with finite ends, 0.0..1.0, is checked when the program is compiled; FiniteRange.try_from(r) checks a range computed when it runs.

subtype: FiniteRange is a subtype of BoundedRange<Float> is a subtype of NonEmptyRange<Float> is a subtype of Range<Float>. A literal where a FiniteRange is expected is checked when the program is compiled; FiniteRange.try_from(...) checks a value when it runs.

import std::random.FiniteRange

r: FiniteRange = 0.0..=1.0
assert Range.contains(r, 0.5)
assert FiniteRange.try_from(Float.negative_infinity()..1.0) == None
assert FiniteRange.try_from(0.0..Float.positive_infinity()) == None
assert FiniteRange.try_from(1.0..0.0) == None
assert FiniteRange.try_from(0.0..1.0) == Some(0.0..1.0)
fn try_from(value: Range<Float>) -> Maybe<FiniteRange>

type function on FiniteRange

Some of the value when it satisfies FiniteRange’s rules, None when it does not.

enum Error
    InvalidWeight { weight: Float }
    ZeroWeightTotal
    OsEntropy { reason: String }
end

Errors returned when weights cannot make a generator, or when OS entropy is unavailable.

impl Display for Error

fn to_string(e: Error) -> String

impl Display.to_string

impl Debug for Error

fn inspect(value: Error) -> String

impl Debug.inspect

impl Equatable for Error

fn equal(a: Error, b: Error) -> Bool

impl Equatable.equal

type Seed Int

opaque — construction surface is private to its defining module

The state of the pseudo-random sequence (a splitmix64 register). It is never mutated: Generator.step takes one and returns the next. Seed.from_int makes a seed that repeats, and Seed.from_os one that does not.

fn from_int(n: Int) -> Seed

type function on Seed

A seed from an integer. The same n gives the same sequence on every platform and in every release, since splitmix64 is fully specified.

seed = Seed.from_int(123)
(roll, _) = Generator.step(Generator.int(1..=6), seed)
assert roll == 2
fn from_os() -> Result<Seed, Error>

type function on Seed

A seed from the operating system’s entropy, different on every run. It is the only function of Seed that is not pure. A program seeded with it cannot repeat its draws, so tests use from_int.

impl Debug for Seed

fn inspect(value: Seed) -> String

impl Debug.inspect

fn secure_bytes(count: NonNegativeInt) -> Bytes

count bytes from the operating system’s cryptographically secure random source, for keys, tokens, salts and nonces. Unlike a Generator it takes no seed and never repeats, so a test cannot predict its bytes. count is a NonNegativeInt.

import std::random

key = random.secure_bytes(32)
assert Bytes.length(key) == 32
assert Bytes.length(random.secure_bytes(0)) == 0
struct Generator<T>

opaque — construction surface is private to its defining module

A description of how to produce a T from a seed. Build one with Generator.int, Generator.float, Generator.bool, Generator.uniform or Generator.weighted, change it with map and flat_map, then run it with Generator.step. Generator.weighted returns a Result, since its weights may come from data: unwrap it with ? or case before composing.

fn step<T>(gen: Generator<T>, seed: Seed) -> (T, Seed)

type function on Generator

Produces a value and the next seed. The same generator and seed always give the same pair.

die = Generator.int(1..=6)

(n, _) = die |> Generator.step(Seed.from_int(42))
gen = Generator.constant("heads")
(value, _) = Generator.step(gen, Seed.from_int(1))
assert value == "heads"
fn int(range: BoundedRange<Int>) -> Generator<Int>

type function on Generator

Uniform integer in range, a BoundedRange: 1..=6 draws 1 to 6 and 0..10 draws 0 to 9. A backwards or empty range (6..=1, 4..4) is an error when the program is compiled, and a range computed when it runs goes through BoundedRange.try_from. Any range draws uniformly, the whole of Int included.

die = Generator.int(1..=6)
(roll, _) = Generator.step(die, Seed.from_int(123))
assert roll >= 1 and roll <= 6
(only, _) = Generator.step(Generator.int(4..=4), Seed.from_int(123))
assert only == 4
(below, _) = Generator.step(Generator.int(4..5), Seed.from_int(123))
assert below == 4
(n, _) = Generator.step(Generator.int(-5..=9_223_372_036_854_775_807), Seed.from_int(7))
assert n >= -5
huge = Int.pow(10, 30)
wide = BoundedRange.try_from(huge..=huge * 2)!
(big, _) = Generator.step(Generator.int(wide), Seed.from_int(7))
assert big >= huge and big <= huge * 2
fn float(range: FiniteRange) -> Generator<Float>

type function on Generator

Uniform float in range, a FiniteRange: 1.5..2.5 draws from 1.5 up to but not including 2.5. An inclusive range draws the same way, so x..=x always draws x. A backwards or empty range is an error when the program is compiled, and a range computed when it runs goes through FiniteRange.try_from, which also refuses a NaN or an infinite end. Ends whose difference is too large for a Float still draw uniformly.

import std::random.FiniteRange

gen = Generator.float(1.5..2.5)
(x, _) = Generator.step(gen, Seed.from_int(123))
assert x >= 1.5 and x < 2.5
(same, _) = Generator.step(Generator.float(0.5..=0.5), Seed.from_int(123))
assert same == 0.5
(wide, _) = Generator.step(Generator.float(-1.0e308..1.0e308), Seed.from_int(7))
assert Float.is_finite(wide)
low = 0.25
(y, _) = Generator.step(Generator.float(FiniteRange.try_from(low..1.0)!), Seed.from_int(7))
assert y >= low and y < 1.0
fn bool() -> Generator<Bool>

type function on Generator

True or False with equal probability.

(value, _) = Generator.step(Generator.bool(), Seed.from_int(123))
assert value == True or value == False
fn constant<T>(value: T) -> Generator<T>

type function on Generator

Always produces value, and returns the seed it was given.

(value, _) = Generator.step(Generator.constant("fixed"), Seed.from_int(123))
assert value == "fixed"
fn uniform<T>(options: NonEmptyList<T>) -> Generator<T>

type function on Generator

Uniform choice among options, a NonEmptyList, which a list literal with an element is; a list built while the program runs goes through NonEmptyList.try_from.

Generator.uniform(["rock", "paper", "scissors"])
(choice, _) =
    Generator.uniform(["rock", "paper", "scissors"])
    |> Generator.step(Seed.from_int(123))

assert choice == "paper" or choice == "rock" or choice == "scissors"
fn weighted<T>(options: NonEmptyList<(NonNegativeFloat, T)>) -> Result<Generator<T>, Error>

type function on Generator

Weighted choice among options, a NonEmptyList; each option carries a relative weight, a NonNegativeFloat, and the weights need not sum to 1. The result is Err(Error.ZeroWeightTotal) when every weight is zero, and Err(Error.InvalidWeight{...}) when a weight or their sum is infinite.

assert Ok(gen) = Generator.weighted([(1.0, "always")])
(choice, _) = Generator.step(gen, Seed.from_int(123))
assert choice == "always"
assert Err(Error.ZeroWeightTotal) = Generator.weighted([(0.0, "never")])
endless = NonNegativeFloat.try_from(Float.positive_infinity())!
assert Err(Error.InvalidWeight{weight: _}) = Generator.weighted([(endless, "all")])
fn map<T, U>(gen: Generator<T>, f: (T) -> U) -> Generator<U>

type function on Generator

A generator of f applied to each value gen produces.

gen = Generator.constant(21) |> Generator.map(&(&1 * 2))

(value, _) = Generator.step(gen, Seed.from_int(123))
assert value == 42
fn flat_map<T, U>(gen: Generator<T>, f: (T) -> Generator<U>) -> Generator<U>

type function on Generator

A generator that draws from gen, then from the generator f returns for that value: a draw that depends on an earlier one.

gen = Generator.int(1..=6)

gen |> Generator.flat_map(fn n -> Generator.list(Generator.bool(), n))
gen =
    Generator.constant(3)
    |> Generator.flat_map(fn n -> Generator.constant(n * 10))

(value, _) = Generator.step(gen, Seed.from_int(123))
assert value == 30
fn list<T>(gen: Generator<T>, length: NonNegativeInt) -> Generator<List<T>>

type function on Generator

A list of length independent draws from gen. length is a NonNegativeInt, and a length of 0 is an empty list.

(hand, _) =
    Generator.int(1..=6)
    |> Generator.list(5)
    |> Generator.step(Seed.from_int(7))

assert hand == [4, 1, 1, 4, 5]

gen = Generator.constant("ha") |> Generator.list(3)

(values, _) = Generator.step(gen, Seed.from_int(123))
assert values == ["ha", "ha", "ha"]

impl Debug for Generator<T>

fn inspect<T>(value: Generator<T>) -> String where T: Debug

impl Debug.inspect