Chomik: Generating Random Numbers


In the last article, we learned how to read integers from a file. Today, we will move on to something equally important in many programs: random numbers.
At first glance, generating random numbers may not look like an input/output (I/O) operation. However, in Chomik I decided to model it as if it were one. Why? Because it lets us reuse the same language constructs we already use for reading from files. This way, the mechanism stays consistent and easy to understand.
Creating a Random Number Stream
In Chomik, random numbers are produced through a special kind of stream called a random number stream. To create one, you need to provide:
the type of numbers (for now:
"integer"
),the lower bound,
the upper bound.
Here is an example where we create a stream for random integers between 0 and 100:<create new input random number stream "integer" 0 100>;
let my random stream index = <the created stream index>;
Just like when opening a file, the stream creation command updates the predefined variablethe created stream index
, which we can store in our own variable (here: my random stream index
).
Reading from the Random Number Stream
Once the stream exists, we need to tell Chomik which stream we want to read from. We do this by assigning our stream index to the predefined variable the read from stream source stream index
:
let the read from stream source stream index = <my random stream index>;
Now we can read an integer from the stream:
<read from stream "integer">;
This updates another predefined variable:
the read from stream result "integer"
Using the Random Value
We can store the result in our own variable and use it as needed:let x = <the read from stream result "integer">;
<print <x>>;
Every time you execute the read from stream "integer"
instruction, you will get a new random integer in the given range.
Complete Example
Here is the full program in one piece:
<create new input random number stream "integer" 0 100>;
let my random stream index = <the created stream index>;
let the read from stream source stream index = <my random stream index>;
<read from stream "integer">;
let x = <the read from stream result "integer">;
<print <x>>;
This program prints a random integer between 0 and 100.
Summary
Random numbers in Chomik are modeled as streams, just like files.
You create a stream by giving a lower and upper bound.
Reading from the stream updates a predefined variable with the result.
You can use this value anywhere in your program.
This design may feel unusual at first, but it keeps the language consistent: all input operations look the same, whether you read from a file or from randomness itself.
Subscribe to my newsletter
Read articles from Pawel Biernacki directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Pawel Biernacki
Pawel Biernacki
I was born in 1973, in Cracow, Poland. I am a software engineer.