Random
Click the blue “Edit” button to see this example in action. Generate a couple random numbers, and look through the code to try to figure out how it works. Click the blue button now!
The new thing here is command issued in the function:
Generating random values works a bit different than in languages like JavaScript, Python, Java, etc. So let’s see how it works in Elm!
The core idea is that we have random Generator
that describes how to generate a random value. For example:
So here we have three random generators. The roll
generator is saying it will produce an Int
, and more specifically, it will produce an integer between 1
and 6
inclusive. Likewise, the usuallyTrue
generator is saying it will produce a , and more specifically, it will be true 80% of the time.
The point is that we are not actually generating the values yet. We are just describing how to generate them. From there you use the to turn it into a command:
When the command is performed, the Generator
produces some value, and then that gets turned into a message for your update
function. So in our example, the Generator
produces a value between 1 and 6, and then it gets turned into a message like NewFace 1
or NewFace 4
. That is all we need to know to get our random dice rolls, but generators can do quite a bit more!
Combining Generators
We first create Symbol
to describe the pictures that can appear on the slot machine. We then create a random generator that generates each symbol with equal probability.
From there we use map3
to combine them into a new spin
generator. It says to generate three symbols and then put them together into a Spin
.
The point here is that from small building blocks, we can create a Generator
that describes pretty complex behavior. And then from our application, we just have to say something like Random.generate NewSpin spin
to get the next random value.