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.10.0/vNe6s9hWzoTZtFmNkvEICPErI9ptji_ySjicO6CkucY.tar.br",
    rand: "https://github.com/lukewilliamboswell/roc-random/releases/download/0.0.1/x_XwrgehcQI4KukXligrAkWTavqDAdE5jGamURpaX-M.tar.br",
}

import pf.Stdout
import pf.Task
import rand.Random

# Print a list of 10 random numbers in the range 25-75 inclusive.
main =

    # Initialize "randomness"
    initialSeed = Random.seed 42

    # Create a generator for values from 25-75 (inclusive)
    generator = Random.int 25 75

    # Create a list of random numbers
    result = randomList initialSeed generator

    # Format as a string
    numbersListStr =
        result.numbers
        |> List.map Num.toStr
        |> Str.joinWith ","
    Stdout.line! "Random numbers are: $(numbersListStr)"

# Generate a list of numbers using the seed and generator provided
# This is NOT cryptograhpically secure!
randomList = \initialSeed, generator ->
    List.range { start: At 0, end: Before 10 }
    |> List.walk { seed: initialSeed, numbers: [] } \state, _ ->
        # Use the generator to get a new seed and value
        random = generator state.seed

        # Update seed so it can be used to generate the next value
        seed = random.state

        # Append the latest random value to the list of numbers
        numbers = List.append state.numbers random.value

        { seed, numbers }

Output

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

$ roc run
Random numbers are: 29,30,71,64,48,33,55,68,53,28