Skip to content

rand

Random integer sampling, string generation, selection, and shuffling.

Functions

int start … -> Int

Samples a uniformly distributed integer from [0, end) or [start, end).

Parameters

NameTypeDescription
start Int Inclusive lower bound, or the exclusive upper bound when end is omitted.
end? Int Exclusive upper bound.

Errors

Exception Condition
TypeError Either argument is not an integer
ValueError end <= 0, or end <= start if given

Example

assert_eq (int 1) 0
let n = int 10 20
assert ((n >= 10) && (n < 20))

pick[T] collection -> T

Selects one random element from an array.

Parameters

NameTypeDescription
collection Array[T] Source array.

Errors

TypeError if collection is not an array. ValueError if it is empty.

Example

let item = pick [1, 2, 3]
assert ([1, 2, 3].contains $item)

shuffle array

Shuffles an array in place using a uniform Fisher-Yates pass.

Parameters

NameTypeDescription
array Array[Value] Array to mutate.

Errors

TypeError if array is not an array.

Example

let items = [1, 2, 3, 4]
shuffle $items
let sorted = [...items]
sorted.sort()
assert_eq $sorted [1, 2, 3, 4]
Open in playground

string len … -> Str

Generates a random string by sampling characters from alphabet.

Parameters

NameTypeDescription
len Int Number of characters to emit.
:alphabet? Str Characters to sample from.
:alphabet

The alphabet is interpreted as characters, not raw UTF-8 bytes. When omitted, it is _-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.

Errors

TypeError if len is not an integer or alphabet is not a string. ValueError if len is negative or alphabet is empty.

Example

let token = string 12
assert_eq $token.len 12

let text = string 4 alphabet: "åß"
assert_eq $text.len 8