The rand library - pf-lang/pipefish GitHub Wiki
The math/rand library makes use of the functions found in Golang's math/rand library. For this reason, like its Golang equivalent, it should not be used for cryptographic applications.
The API is quite different from the Go version, because getting a random number from the RNG is necessarily a command.
Types
We define the following types:
Exponential = struct()
Normal = struct()
Random = struct(elements)
Seed = struct()
Shuffle = struct(elements)
Zipf = struct(s, v float, imax int)
Then the following commands are available:
Commands
put (i int) into (seed Seed)
This seeds the random number generator for when you need it to be deterministic. If you don't, it's given a strong random seed on initialization.
get (x ref) from (r Random)
This chooses a random value from the range given by the elements field of the Random value, according to the type of elements:
- If
elementsis a list, it selects a random element of the list. E.g:get x from Random ["one", "two", "three]. - If it's an integer
i, it selects a random integer in0::i. - If it's
int, it selects a random integer from the whole 64-bit range of integers. - If it's a float
x, it selects a random float between 0 andx. - If it's
float, it selects a random float between 0 and 1. - If it's
bool, it selects randomly fromtrueandfalse. - If it's the name of an enum type, it selects a random element of the enum.
- If it's a pair of integers, it selects a random integer from the range.
- If it's a pair of floats, it selects a random float from the range.
get (x ref) from (s Shuffle)
This returns a random permutation of the range given by the elements field of the Shuffle value, according to the type of elements:
- If
elementsis a list, it returns a permutation of the list. - If it's the name of an enum type, it returns a permutation of the elements of the enum.
- If it's a pair of integers, if returns a permutation of the integers in that range, e.g.
get x from Shuffle 0::10will get a permutation of the numbers0...9.
get (x ref) from (e Exponential)
This gets a random float greater than or equal to 0, with an exponential distribution and mean both equal to 1.
get (x ref) from (n Normal)
This returns a random float with a normal distribution having mean 0 and standard deviation 1.
get (x ref) from (z Zipf)
This gets values k ∈ [0, z[imax]] such that P(k) is proportional to (z.v+k)^(-z.s). Note that in this one case, the top of the range (z[imax]) is among the possibilities.