Unsafe hGetContents

Isaac Dupree ml at isaac.cedarswampstudios.org
Sun Oct 11 13:48:36 EDT 2009

Hmm, Don't you think forkIO deserves some of the same complaints as 
unsafeInterleaveIO?  Things happen in a nondeterministic order!

I think what irritates us about unsafeInterleaveIO is that it's IO that 
tinkers with the internals of the Haskell evaluation system.  The OS 
can't do it: in a C program it might, because there's libc and debuggers 
and all kinds of things that understand compiled C to some extent.  But 
the Haskell runtime system is pretty much obfuscated to anyone except 
ourselves.  This obfuscation maintains its conceptual purity to a 
greater extent than is really guaranteed by the standards.  This 
obfuscation is supported in our minds by the fact that functions (->) 
cannot be compared for equality or deconstructed or serialized in any 
way, only applied.

forkIO causes IO to happen in a nondeterministic order.  So does 
unsafeInterleaveIO.  But for unsafeInterleaveIO, the nondeterminism 
depends in part on how pure functions are written: partly because there 
is a compiler that makes arbitrary choices, and also partly affected by 
the strictness properties of the functions.  This feels disconcerting to 
us.  And worse: I am not sure if forkIO has a formal guarantee that its 
IO will complete, but we tend to assume that it will, sooner or later; 
unsafeInterleaveIO might not happen at all, and frequently does not, due 
to the observations of how pure functions are written.

It's disconcerting.  It can affect how we choose to write our pure code, 
the same way that efficiency and memory concerns can.  But if 'catch' 
can catch a different exception depending even, conceptually, on the 
phase of the moon, it is a similarly strange stretch to imagine 
unsafeInterleaveIO doing so.  It plays with chronology (like forkIO 
does) and with the ways Haskell functions are written (like 'catch' 
does) at the same time.

A result is that it makes a lot of people confused when they do 
something they didn't intend with it.  Also, it's a powerful enough tool 
that when you want to replace its formal nondeterminism with something 
more precise, you may have quite a bit of work cut out for you, 
restructuring your code (like Darcs did, IIRC).


More information about the Haskell-prime mailing list