[Haskell-cafe] Re: Generating a random list

Milos Hasan mhasan at cs.cornell.edu
Sat Mar 1 23:06:51 EST 2008


OK, you convinced me that sort is not the problem. After all, "last (f 
1000000)" overflows too, and last is a very innocent function.

I don't know how you found the size (or structure) of the thunks (I'm 
not aware of a ghci functionality that can tell me that), could you let 
me know?

Anyway, the problem seems to be that the values pulled from the list are 
not final float values, but instead they're thunks that grow larger and 
larger as more floats are pulled from the list. That's why last and sort 
don't work, but print and foldl' do work. Also, an odd number of 
reverses helps since sort evaluates the elements from the end of the 
list first.

So I forced those values, and it fixed the problem:

-- this function returns n random floats (no thunks)
f :: Int -> [Float]
f n = take n $ randFloats $ mkStdGen 0 where
    randFloats g = x `seq` x : randFloats g' where (x, g') = random g
   
main = print $ foldl1' (+) $ sort $ f 1000000

This works without overflow, and so does "last (f 1000000)".

Would it make sense for System.Random to do this forcing by default, too?

Thanks,
Milos



More information about the Haskell-Cafe mailing list