[Haskell-cafe] unsafeInerleaveIO and randomIO

Bertram Felgenhauer bertram.felgenhauer at googlemail.com
Tue Apr 17 06:35:25 EDT 2007


Marc Weber wrote:
> stefan has pointed me a nice version:
> 
> Anyway I'm curious why 
> 
> =============  =======================================================
> randomInts :: IO [Int]
> randomInts = unsafeInterleaveIO $ 
>     sequence $ cycle [unsafeInterleaveIO randomIO]
> =============  =======================================================
> 
> doesn't return.

sequence isn't lazy (not in the IO monad at least); it will try to run
to completion, returning an infinite list of (as yet unevaluated, due
to unsafeInterleaveIO) thunks. The construction of that list will never
finish though.

I think you want something like (untested)

> unsafeInterleaveSequence :: [IO a] -> IO [a]
> unsafeInterleaveSequence []     = return []
> unsafeInterleaveSequence (x:xs) =
>      unsafeInterleaveIO $ liftM2 (:) x (unsafeInterleaveSequence xs)
> 
> randomInts = unsafeInterleaveSequence $ repeat randomIO

or maybe (unsafeInterleaveIO randomIO) instead of randomIO.

Bertram


More information about the Haskell-Cafe mailing list