Random Numbers in Idris
Our example demonstrates how to generate random numbers in Idris. Idris doesn’t have a built-in random number generator in its standard library, so we’ll use the random
package from the contrib
library.
To use this code, you’ll need to install the contrib
package and import System.Random
. Here’s a brief explanation of what the code does:
We use
randomRIO
to generate random numbers within a specified range. This function returns anIO
action that produces a random number.For floating-point numbers between 0.0 and 1.0, we use
randomRIO (0.0, 1.0)
.To generate floats in a different range (e.g., 5.0 to 10.0), we directly specify the range in
randomRIO
.To use a specific seed for reproducible results, we use
mkStdGen
to create a random number generator with a given seed. We then userandomR
to generate random numbers from this generator.Using the same seed will produce the same sequence of random numbers, as demonstrated in the last part of the code.
When you run this program, you might see output similar to this:
Note that the actual numbers will be different each time you run the program, except for the last two lines which use a fixed seed.
Idris’s random number generation is based on the Haskell implementation, which uses a splittable random number generator. This is different from the PCG algorithm mentioned in the original example, but it serves a similar purpose of providing pseudorandom numbers.
For more advanced random number generation techniques or different distributions, you might need to implement them yourself or look for additional libraries.