Good Pactice using elm/random

I’m using random values a lot in my games; so the seed gets changed a lot during one update. That’s why I started using generators instead of always passing the seed.

My model typically looks like this

type Model = (State, Seed)

stateGenerator : Msg -> State -> Generator (State,Cmd Msg) 

update : Msg -> Model -> (Model,Cmd Msg)
update (state,seed) =
        ((newState,cmd),newSeed) = Random.step (stateGenerator state) seed

Can this be done better?

Can you give an example of the seed changing “a lot”?

Maybe the update code could be written in another way.

Lets say you have a dungeon with some enemies. (i dont know how many they are)
each tick all enemies will need to move in a random direction.
previously i would write a Generator Direction then one after another call Random.step for each enemy. Now im just writing a Dungeon -> Generator Dungeon instead.

Generators, not seeds, are the primary data structure of the Random library. I tried to communicate this by placing Generator at the top of the docs and Seed at the bottom.

Generators describe work to be done. They can be as complicated as you like, using randomness in parallel (mapN) and in series (andThen) along with pure functions (map) and values (constant). Keep your seeds confined to update.

It just occurred to me that maybe we should rename Generator a to Random a. Dungeon -> Random Dungeon doesn’t look so bad…


I really had problems understanding what a generator should do: Having a Generator Model if the only thing, that is actually generating stuff is Generator Direction felt counter-intuitive. So renaming it to Random would be awesome. :+1:

1 Like

Pro-Tip: Don’t import exposing Generator. Then you get the nicer signature of Random.Generator a, which is more descriptive.


Generator Dungeon is definitely the way to go compared to seeds, here’s my version of it:

This starts with a simple wall generator, then rooms, then A* variant of corridors then levels until you get to a full dungeon.

This was one of the first things I had to learn in FP and in Elm to make random things bearable, prior to this, I had seed''''' in Elm 0.17

I think the problem isn’t in the naming or having Generator on top and seed on the bottom. For me, coming from a OO/imperative background, I only knew about seeds so I just searched for seeds, completely ignored the weird ‘Generator’ thing that I didn’t understand. Breaking the paradigm was the hurdle for me, only then, could I learn what a Generator was.

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