[Haskell-cafe] Getting WriterT log lazily

Martijn van Steenbergen martijn at van.steenbergen.nl
Mon May 4 03:48:16 EDT 2009

Magnus Therning wrote:
> Without the `seq` the call to sleep will simply be skipped (is there an
> easier way to force evaluation there?).  Without `unsafePerformIO` all
> the sleeping is done up front, and all numbers are print at once at the
> end.
> The goal is of course to use code along the same shape to do something 
> more useful, and then `unsafePerformIO` will really be unsafe...

So what you're trying to do is run two IO actions at the same time: one 
to produce values, the other to consume values.

If you want to be really safe use threads (does that sound 
paradoxical?), as Ertegrul suggested, although I'd use channels instead 
of an MVar since this seems to be a perfect example for them.

Otherwise, you can use unsafeInterleaveIO: no unsafePerformIO or seq 
needed, but there's still "unsafe" in that name there. This works for me:

> foo :: WriterT [Int] IO ()
> foo = let
>         _tell i = do
>             a <- lift $ unsafeInterleaveIO $ threadDelay 100000 >> return 0
>             tell [i + a]
>     in do
>         mapM_ _tell [1..10]


More information about the Haskell-Cafe mailing list