Random Numbers

Generate a list of random numbers using the roc-random package and the basic-cli platform.

Random Generators

Some languages provide a function like JavaScript’s Math.random() which can return a different number each time you call it. However, functions in Roc are guaranteed to return the same answer when given the same arguments, so something like Math.random couldn’t possibly be a valid Roc function! As such, we use a different approach to generate random numbers in Roc.

This example uses a Generator which generates pseudorandom numbers using an initial seed value and the PCG algorithm. Note that if the same seed is provided, then the same number sequence will be generated every time! The appearance of randomness comes entirely from deterministic math being done on that initial seed. (The same is true of Math.random(), except that Math.random() silently chooses a seed for you at runtime.)

Code

app [main!] {
    pf: platform "https://github.com/roc-lang/basic-cli/releases/download/0.18.0/0APbwVN1_p1mJ96tXjaoiUCr8NBGamr8G8Ac_DrXR-o.tar.br",
    rand: "https://github.com/lukewilliamboswell/roc-random/releases/download/0.4.0/Ai2KfHOqOYXZmwdHX3g3ytbOUjTmZQmy0G2R9NuPBP0.tar.br",
}

import pf.Stdout
import rand.Random

main! = \_args ->

    # Print a list of 10 random numbers in the range 25-75 inclusive.
    numbers_str =
        randomNumbers
        |> List.map Num.toStr
        |> Str.joinWith "\n"

    Stdout.line! numbers_str

# Generate a list random numbers using the seed `1234`.
# This is NOT cryptograhpically secure!
randomNumbers : List U32
randomNumbers =
    { value: numbers } = Random.step (Random.seed 1234) numbersGenerator

    numbers

# A generator that will produce a list of 10 random numbers in the range 25-75 inclusive.
# This is NOT cryptograhpically secure!
numbersGenerator : Random.Generator (List U32)
numbersGenerator =
    Random.list (Random.boundedU32 25 75) 10

expect
    actual = randomNumbers
    actual == [52, 34, 26, 69, 34, 35, 51, 74, 70, 39]

Output

Run this from the directory that has main.roc in it:

$ roc main.roc
52
34
26
69
34
35
51
74
70
39