Random Color

Mike T. Machenry dskippy@ccs.neu.edu
Thu, 21 Nov 2002 13:45:10 -0500


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

-mike

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