Standard Library: std.random
● Intermediate5 min
Every type, method and function of std.random: what the spec lists, then each declaration in its source, with its examples and the line that declares it.
Spec 14.15 · learn it in Random Numbers.
A declaration below shows what a program writes against: a type's fields, a function's parameters, what it gives, its contracts (require, ensure) and its examples. kavach test runs every example, so each one is true of the code.
What the spec lists
| Function | Gives |
|---|---|
random.int(from, until) -> Int | A whole number from from up to, not including, until; each equally likely. until must be greater than from (a require) |
random.float() -> Float | A number from 0.0 up to, not including, 1.0 |
random.bool() -> Bool | true or false, each half the time |
random.pick<T>(items) -> T? | One of items, each equally likely; none when there are none |
random.shuffle<T>(items) -> [T] | A copy of items in a random order, every order equally likely |
random.bytes(n) -> Bytes | n random bytes. n is from 0 to 65,536 (a require), as in browsers' crypto.getRandomValues; for more, call it again |
std.random · random.kav
use std.random: 0 types and 6 functions. stdlib/random/random.kav
int function
A whole number from from up to, not including, until, each equally likely.
pub fn int(from: Int, until: Int) -> Int uses Random
require until > from
require from >= 0 or until <= largest() + from
ensure result >= from and result < untilfloat function
A number from 0.0 up to, not including, 1.0.
pub fn float() -> Float uses Random
ensure result >= 0.0 and result < 1.0bool function
true or false, each half the time.
pub fn bool() -> Bool uses Randompick function
One of items, each equally likely; none when there are none.
pub fn pick<T>(items: [T]) -> T? uses Randomshuffle function
A copy of items in a random order, every order equally likely (Fisher and Yates' shuffle).
pub fn shuffle<T>(items: [T]) -> [T] uses Randombytes function
n random bytes, up to 64 KiB at a time.
pub fn bytes(n: Int) -> Bytes uses Random
require n >= 0 and n <= 65_536
ensure result.len() == n