[Haskell-beginners] IO ( stuff )

Henk-Jan van Tuyl hjgtuyl at chello.nl
Sat Dec 10 09:09:32 CET 2011


On Fri, 09 Dec 2011 23:05:15 +0100, David McBride <toad3k at gmail.com> wrote:

> data Monster = Orc | Wolf | Dragon deriving (Show, Enum)
>
> randomMonster :: RandomGen g => Rand g Monster
> randomMonster = do
>   x <- getRandomR (0,2::Int)
>   return $ case x of
>     0 -> Orc
>     1 -> Dragon
>     2 -> Wolf

You have already created an Enum instance of Monster, so why not use it:

  randomMonster :: RandomGen g => Rand g Monster
  randomMonster =
    do
      x <- getRandomR (0,2::Int)
      return $ toEnum x

Or:
  randomMonster :: RandomGen g => Rand g Monster
  randomMonster = toEnum <$> getRandomR (0,2::Int)

where <$> is imported from module Data.Functor or Control.Applicative.

Regards,
Henk-Jan van Tuyl


-- 
http://Van.Tuyl.eu/
http://members.chello.nl/hjgtuyl/tourdemonad.html
--



More information about the Beginners mailing list