[Haskell-cafe] better way to do this?

Duncan Coutts duncan.coutts at googlemail.com
Sun Oct 4 07:52:51 EDT 2009

On Sun, 2009-10-04 at 02:52 -0700, Michael Mossey wrote:
> I'm looking for a hint to write the following code with less redundancy. I
> have a constructor called BoxBounds, and I want to make one with random
> values.
> randomBox :: IO BoxBounds
> randomBox = do
>   x <- getStdRandom (randomR (-10,10))
>   y <- getStdRandom (randomR (-70,70))
>   t <- getStdRandom (randomR (5,10))
>   b <- getStdRandom (randomR (5,10))
>   l <- getStdRandom (randomR (5,10))
>   r <- getStdRandom (randomR (5,10))
>   return (BoxBounds x y l r t b)

Others have already answered but I'd like to suggest that you avoid
using IO here. There's no need for this to be impure. The getStdRandom
function is one that should be avoided IMHO (and indeed removed from the
Random module).

A much nicer way to do the above is using some random monad, for example
from the MonadRandom package. The suggestions from Felipe and Eugene
will work just as well using Rand monad as the IO monad.


More information about the Haskell-Cafe mailing list