prng

Package Version Hex Docs

🎲 A Pure Random Number Generator (PRNG) for Gleam

⚙️ This package works for both the Erlang and JavaScript target

Installation

To add this package to your Gleam project:

gleam add prng

Generating random values

This package can help you generate any kind of random values you can think of. It can be useful in many different scenarios: when you need to simulate non-deterministic actions, like rolling a dice or flipping a coin; when you need to write property based tests; or to make fun interactive games where you can spawn randomly generated enemies!

A mindset shift

The way random values are generated may be a bit confusing at first, especially coming from other languages like JavaScript. In such languages, random number generation can be as simple as this:

const random_value: number = Math.random()

However, this should raise a lot of questions: what if I need those numbers to be in a certain range? How can I generate more complex values, like lists of numbers? Can I set the random seed to get deterministic and reproducible results in a test environment?

The random package tries to address all these questions by providing a nice interface to define random value generators. Let’s have a look at an example to get a taste of what generating random values will look like:

let generator: Generator(Float) = random.float(0.0, 1.0)
let random_value: Float = random.sample(generator)

Notice a subtle but fundamental difference: you’re no longer simply generating a value, you’re describing the values you want to generate and you can take those out of a generator with a variety of functions, like sample.

This neat trick can give two great features:

References

This package and its documentation are based on the awesome Elm implementation of Permuted Congruential Generators. They have great documentation full of clear and useful examples; if you are curious, give it a look and show Elm some love!

Contributing

If you think there’s any way to improve this package, or if you spot a bug don’t be afraid to open PRs, issues or requests of any kind! Any contribution is welcome 💜

Search Document