Skip to content

JanCVanB/roc-random

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

49 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Randomness for Roc

A Roc library for random number generation

Status

This works, but there's much more it could do.

Contributions & feedback are very welcome! :)

Examples

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

    # Initialise "randomness"
    initialSeed = Random.seed16 42

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

    # Create a list of random numbers
    result =
        List.range { start: At 0, end: Before 10 }
        |> List.walk { seed: initialSeed, numbers: [] } \state, _ ->

            random = u16 state.seed
            seed = random.state
            numbers = List.append state.numbers random.value

            { seed, numbers }

    # Format as a string
    numbersListStr =
        result.numbers
        |> List.map Num.toStr
        |> Str.joinWith ","

    Stdout.line "Random numbers are: \(numbersListStr)"

See the examples/*.roc files for more examples.

Documentation

See the library documentation site for more info about its API.

However, the single library file itself should be self-documenting.

Goals

  • An external API that is similar to that of Elm's Random library
  • An internal implementation that is similar to that of Rust's Rand library
  • Compatible with every Roc platform (though some platforms may provide poor/constant seeding)
  • Provides a variety of ergonomic abstractions

Seeding

In order to receive a different sequence of outputs from this library between executions of your application, your Roc platform of choice must provide a random/pseudorandom/varying seed. Otherwise, your pure functions will be responsible for providing Random's pure functions with a constant seed that will merely choose which predictable sequence you'll receive.