Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elm Generator Int -> List Int

Tags:

elm

I want to get List out of Generator

intList : Generator (List Int)
intList =
    list 5 (int 0 100)

How could I now get a list out of it?

like image 788
Mihkel L. Avatar asked Jan 20 '26 15:01

Mihkel L.


2 Answers

You cannot get a random list out of Generator because Elm functions are always pure. The only possibility to get a list is to use a command.

A command is a way to tell Elm runtime to do some impure operation. In your case, you can tell it to generate a random list of integers. Then it will return back the result of that operation as an argument of the update function.

To send Elm runtime a command to generate a random value, you can use the function Random.generate:

generate : (a -> msg) -> Generator a -> Cmd msg

You already have Generator a (your intList), so you need to provide a function a -> msg. This function should wrap a (List Int in your case) into a message.

The final code should be something like that:

type Msg =
    RandomListMsg (List Int)
  | ... other types of messages here

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model = case msg of
    ... -> ( model, Random.generate RandomListMsg intList)
    RandomListMsg yourRandomList -> ...

If you don't know about messages and models yet, you should probably get acquainted with the Elm architecture first.

like image 74
ZhekaKozlov Avatar answered Jan 22 '26 19:01

ZhekaKozlov


You can provide your own seed value to Random.step, which will return a tuple containing a list and the next seed value. This retains purity because you will always get the same result when you pass the same seed.

Random.step intList (Random.initialSeed 123)
    |> Tuple.first

-- will always yield [69,0,6,93,2]

The answer given by @ZhekaKozlov is typically how you generate random values in an application, but it uses Random.step under the hood with the current time used as the initial seed.

like image 23
Chad Gilbert Avatar answered Jan 22 '26 19:01

Chad Gilbert