[Haskell-cafe] Generating a random list
chaddai.fouche at gmail.com
Sat Mar 1 21:48:00 EST 2008
2008/3/1, Milos Hasan <mhasan at cs.cornell.edu>:
> OK, thanks, this is an important point. So maybe I should have done this?
> main = print $ foldl1' (+) $! take 1000000 randFloats
> My intuition tells me that the $! (and `seq`) just reduces one level (to
> WHNF?). If so, is there a way to force complete evaluation (so that
> nothing is reducible anymore)?
In fact with this code you won't have any problem since the foldl1'
will consume strictly the elements as soon as take produce them,
avoiding any accumulation of thunk by randoms.
Now if you were to put a sort in there (supposedly to do something
else than a simple sum...), you could have a need for a function that
reduce the list and its elements :
> forceList  = ()
> forceList (x:xs) = x `seq` forceList xs
> main = print $ foldl1' (+) $ (\xs -> forceList xs `seq` sort xs) $ take 1000000 randFloats
In Ghci it don't work (probably because the tail call in forceList
isn't optimised) but compiled it will work fine.
More information about the Haskell-Cafe