Random Color

Dean Herington heringto@cs.unc.edu
Thu, 21 Nov 2002 16:47:49 -0500 (EST)


On Thu, 21 Nov 2002, Mike T. Machenry wrote:

> This program yeilds:
> Fail: toEnum{Color}: tag (4) is outside of enumeration's range (0,3)
> in ghc... any ideas why?
> 
> -mike

Hmm.  The program works fine for me, using GHC 5.04.1 or Hugs of Oct 2002.

Dean


> On Thu, Nov 21, 2002 at 10:07:12AM -0500, Dean Herington wrote:
> > "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