Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the minimum code required to produce random numbers in Elm?

Tags:

random

elm

I just want to see a random number. So here's an example straight out of the docs for the Random library. I expect Random.generate to accept a generator and a seed and return a tuple containing a random value and a new seed, as in:

generate : Generator a -> Seed -> (a, Seed)

-- Main.elm

import Random

seed0 = Random.initialSeed 31415
randomNumber = Random.generate (Random.int 0 10) seed0
main = 
  -- print result of randomNumber here

The compiler errors show two type mismatches:

-- TYPE MISMATCH ---------------------------------------------------- -----------

The 2nd argument to function `generate` is causing a mismatch.

5|        Random.generate (Random.int 0 10) seed0
                                        ^^^^^
Function `generate` is expecting the 2nd argument to be:

    Random.Generator a

But it is:

    Random.Seed


The 1st argument to function `generate` is causing a mismatch.

5|        Random.generate (Random.int 0 10) seed0
                       ^^^^^^^^^^^^^^^
Function `generate` is expecting the 1st argument to be:

    a -> b

But it is:

    Random.Generator Int

What am I missing here?

like image 992
Joseph Fraley Avatar asked Aug 30 '25 18:08

Joseph Fraley


2 Answers

The version of the docs you refer to is Core 1.0.0, which is old. Current version of Core is 4.0.5. (docs for Random here)

The function with the signature you are looking for is now named step:

step : Generator a -> Seed -> (a, Seed)

So your refactored code would look something like this:

import Html exposing (text)
import Random

seed0 = Random.initialSeed 31415
(randomNumber, nextSeed) = Random.step (Random.int 0 10) seed0

main =
  text <| toString randomNumber
like image 74
wintvelt Avatar answered Sep 02 '25 11:09

wintvelt


Here is the shortest example I can think of. Because it is giving a constant seed, it will return same boolean.

If you need random number get produced at runtime, then you have to use Random.generate which produces Cmd so that elm runtime can get the randomness. In this case, some form of Platform.Program is needed because it is the only way to run Cmd.

import Html exposing (text)
import Random exposing (..)

main =
  text <| toString <| Tuple.first <| step bool (initialSeed 1)
like image 37
Tosh Avatar answered Sep 02 '25 11:09

Tosh