Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Turn an Elm random generator into task, allowing it to be chained with other side effects.
-- 0.19
randomToTask : Generator a -> Task x a
randomToTask generator =
Time.now
|> Task.map (Tuple.first << Random.step generator << Random.initialSeed << Time.posixToMillis)
-- 0.18
randomToTask : Generator a -> Task x a
randomToTask generator =
Time.now
|> Task.map (Tuple.first << Random.step generator << Random.initialSeed << round)
@andys8

This comment has been minimized.

Copy link

@andys8 andys8 commented Jun 17, 2019

@JoelQ Would you recommend using this? Are there libraries using it?

Had to change it to compile.

randomToTask : Generator a -> Task Never a
randomToTask generator =
    Time.now
        |> Task.map (Tuple.first << Random.step generator << Random.initialSeed << Time.posixToMillis)
@JoelQ

This comment has been minimized.

Copy link
Owner Author

@JoelQ JoelQ commented Jun 17, 2019

@andys8 because it uses the current time as a seed, the random value more guessable than it otherwise would be (note that regardless of seed value, Random is not cryptographically secure).

I think it's fine to use this but personally haven't found a need for it. I've never had to combine randomness with other side effects like HTTP requests.

@JoelQ

This comment has been minimized.

Copy link
Owner Author

@JoelQ JoelQ commented Jun 17, 2019

The original version I had up was for Elm 0.18. I've updated the gist with your modified version, labelling it as 0.19 compatible.

@andys8

This comment has been minimized.

Copy link

@andys8 andys8 commented Jun 17, 2019

Thanks for your answer. I'm aware of the effect on randomness.

I searched for a way to combine Cmds. The use case need both a Uuid (Generator) and the current Posix (Task). There is no Cmd#andThen but there is Task#andThen. This snippet is the closest solution I found so far while it's not ideal.

@andys8

This comment has been minimized.

Copy link

@andys8 andys8 commented Oct 6, 2019

Interesting discussion regarding cmd chaining
https://gist.github.com/alpacaaa/13335246234042395813d97af029b10f

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.