Feature Request: Random.generateTask

I noticed that Elm/Random has no way to generate a random value as a Task. I’m not sure if this is intended.

Currently, I am trying to build a chat with Jsonstore at the backend.
If I now want to create a new chatroom, I need to first generate a number and then create the room.

createRoom : Task Error (Maybe Room)
createRoom =
    Random.generateTask Random.int 0 Random.maxInt
    |> Task.andThen insertNewRoom

Instead, I need to split it up into two messages: one for the Random value and one for everything else.

update : Msg -> Model -> (Model,Cmd Msg)
update msg model =
    case msg of
        PressedNewRoomButton ->
            ( model
            , Random.generate Random.int 0 Random.maxInt
            )

        GeneratedRoomId int ->
            ( model
            , insertNewRoom int
                |> Task.attempt Sync
            )

Alternatively I could store a seed in the model, but as this is the only time I use a Random value, I would like to avoid it.

1 Like

Could you instead create a hash based on the current time or some data in your model that changes often? Then use that hash with Random.initialSeed.

you could use a Monad :speak_no_evil: and pretend the split didn’t happen :see_no_evil:

type Msg
    = Monad (Cmd Msg)
    -- ...

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        Monad cmd ->
            ( model, cmd )

        PressedNewRoomButton ->
            ( model
            , Random.generate
                (insertNewRoom
                    >> Task.attempt Sync
                    >> Monad
                )
                (Random.int 0 Random.maxInt)
            )

        Sync result ->
            -- ...
1 Like

I like this approach but I feel like its more of a workaround then a real solution. So i’ve created a new issue over at elm/random, let’s see if gets added.

Alternatively, as @MartinS said, I might switch to another RNG package like mgold/elm-random-pcg. As it uses Time.now for generating numbers.

Edit: Just noticed that @mgold’s package is outdated. If mgold doesn’t mind, I might start my own fork and update it to 0.19

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.