[Haskell-beginners] questions about randomness

Michael Mossey mpm at alumni.caltech.edu
Sat Oct 10 03:59:15 EDT 2009


I would like to know if this is a good way to do this job, both from the
point of view of elegance and efficiency. Maybe it needs to be more
strict? I may create lists of 100,000 elements and don't want to run into
space/time problems.

I want to create an infinite list of Floats (for purposes of lazily
zipping or writing later), with the following form: a random number of
zeros, followed by a single random non-zero value, repeat the pattern. I
call it a "break series" for reasons I won't go into here, but in
practice, I want to choose the number of zeros in each section from a
range of integers, and I want the non-zero values to have a particular
frequency distribution. Here's some code I wrote:



import System.Random
import Control.Monad
import Control.Monad.Random

breakSeries :: Rand StdGen [Float]
breakSeries = do
  x <- getRandomR (0.0::Float, 1.0)
  -- Hacking a simple frequency distribution of values of d.
  d <- if x < 0.6
         then getRandomR (5.0::Float, 8.0)
         else if x < 0.8
                then getRandomR (12.0::Float   , 24.0)
                else getRandomR (60.0::Float   , 90.0)
  n <- getRandomR (4::Int, 6)
  let bits = replicate n 0.0 ++ [d]
  liftM (bits++) breakSeries

test = print . take 20 . evalRand breakSeries =<< newStdGen



More information about the Beginners mailing list