[Haskell-cafe] monte carlo trouble

Chad Scherrer chad.scherrer at gmail.com
Wed Aug 15 13:33:52 EDT 2007

There's a problem I've been struggling with for a long time...

I need to build a function
buildSample :: [A] -> State StdGen [(A,B,C)]

given lookup functions
f :: A -> [B]
g :: A -> [C]

The idea is to first draw randomly form the [A], then apply each
lookup function and draw randomly from the result of each.

It's actually slightly more complicated than this, since for the real
problem I start with type [[A]], and want to map buildSample over
these, and sample from the results.

There seem to be so many ways to deal with random numbers in Haskell.
After some false starts, I ended up doing something like

sample :: [a] -> State StdGen [a]
sample [] = return []
sample xs = do
  g <- get
  let (g', g'') = split g
      bds = (1, length xs)
      xArr = listArray bds xs
  put g''
  return . map (xArr !) $ randomRs bds g'

buildSample xs = sample $ do
  x <- xs
  y <- f x
  z <- g x
  return (x,y,z)

This is really bad, since it builds a huge array of all the
possibilities and then draws from that. Memory is way leaky right now.
I'd like to be able to just have it apply the lookup functions as

Also, I'm still using GHC 6.6, so I don't have
Control.Monad.State.Strict. Not sure how much difference this makes,
but I guess I could just copy the source for that module if I need to.

Any help is greatly appreciated!


Chad Scherrer

"Time flies like an arrow; fruit flies like a banana" -- Groucho Marx

More information about the Haskell-Cafe mailing list