Generate a random value from a user-defined data type in Haskell

Viewed 4435

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.

5 Answers

A coworker suggested to me an alternative to Alekseev's solution which I find a little bit more readable (I'm still learning Haskell so it's probably more on the reader than the code).

{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE UndecidableInstances #-}

instance {-# OVERLAPPABLE #-} (Bounded a, Enum a) => Random a where
  random = randomR (minBound, maxBound)

  randomR (f, t) gen =
    let (rndInt, nxtGen) = randomR (fromEnum f, fromEnum t) gen
     in (toEnum rndInt, nxtGen)

data Weapon = Rock | Paper | Scissor deriving (Eq, Show, Ord, Bounded, Enum)

You could then do: getRandomWeapon = randomRIO (minBound, maxBound) :: IO Weapon and then extract one with weaponChoice <- getRandomWeapon

Related