Similar: Haskell Random from Datatype
I have created a data type to contain the different weapons in the Rock Paper Scissor game.
data Weapon = Rock | Paper | Scissor
Now I would like to generate a random weapon which will be used by the computer against the user.
I have take a look at the similar link I posted at the beginning but It seems too general for me.
I am able to generate random numbers from any other type. What I can get my head around is how to make my data type an instance of the Random class.
To generate a random
Weapon, whether you makeWeaponan instance ofRandomor not, what you need is a way to map numbers toWeapons. If you deriveEnumfor the type, a map to and fromInts is defined by the compiler. So you could definefor example. With an
Enuminstance, you can also easily makeWeaponan instance ofRandom:If there is a possibility of adding or removing constructors from the type, the best way to keep the bounds for
randomRin sync with the type is to also deriveBounded, as Joachim Breitner immediately suggested: