Last active
September 30, 2016 14:10
-
-
Save jehoshua02/b4aa48d727ca57db890af82cb20a2ff6 to your computer and use it in GitHub Desktop.
Here's how I would have liked to get a random number in elm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
randomItem : List a -> Maybe a | |
randomItem xs = | |
case xs of | |
[] -> | |
Nothing | |
_ -> | |
let | |
randomInt = | |
Random.int 0 ((List.length xs) - 1) | |
i = | |
Random.generate identity randomInt | |
in | |
getAt i xs |
@rundis yeah ok, but I don't have a program! I am strictly working with modules, types, functions, and tests at the moment. It's all logic with no UI.
https://github.com/jehoshua02/elm-sudoku/blob/puzzle-solve-tests/src/Sudoku/Puzzle.elm#L62
Should I be forced to have a Program / UI just to get a random number? What if I was shipping a package full of useful, lower-level, non-ui, non-program functions for use by a ui/program developer and one of my dozen functions featured some randomness, as part of it's core logic?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Generating a random is a side effect. Side effects have to be handled by the Elm runtime. No getting around that. Like it or not. But in the bigger scheme of things that has a lot of benefits, even though in your particular case that is cumbersome.
So you'd need to do something like (which you might have already figured out for all I know):