Random Color
Dean Herington
heringto@cs.unc.edu
Thu, 21 Nov 2002 10:07:12 -0500
"Mike T. Machenry" wrote:
> Andrew and list,
>
> I am a beginer. I really don't know what I would do if I derived
> Color from Enum. You say I could create elements that way. Is there
> some simple example someone could post to the list? Thank you for
> your help.
Here's one way to generate random values from an enumerable set:
import Random
randomR_Enum :: (Enum a, RandomGen g) => (a, a) -> g -> (a, g)
randomR_Enum (lo, hi) gen = (toEnum val, gen')
where (val, gen') = randomR (fromEnum lo, fromEnum hi) gen
random_EnumBounded :: (Enum a, Bounded a, RandomGen g) => g -> (a, g)
random_EnumBounded = randomR_Enum (minBound, maxBound)
data Color = Blue | Red | Green deriving (Show, Enum, Bounded)
instance Random Color where
randomR = randomR_Enum
random = random_EnumBounded
main = do stdGen <- getStdGen
print (take 10 (randoms stdGen :: [Color]))
Dean