[Haskell-cafe] Getting WriterT log lazily

Magnus Therning magnus at therning.org
Mon May 4 05:13:48 EDT 2009


Martijn van Steenbergen wrote:
> 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]

Thanks, that does indeed work, but it still requires that "unsafe" there 
so I'm hesitant replacing the call to threadDelay with something more 
complicated, where it isn't obviously safe.

Indeed, I think I'll go for the MVar or possibly a Chan.

Thanks for the help.

/M

-- 
Magnus Therning                        (OpenPGP: 0xAB4DFBA4)
magnus@therning.org          Jabber: magnus@therning.org
http://therning.org/magnus         identi.ca|twitter: magthe

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 197 bytes
Desc: OpenPGP digital signature
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20090504/e6f0efcf/signature.bin


More information about the Haskell-Cafe mailing list