[Haskell-cafe] unsafePerformIO: are we safe?

Paul Johnson paul at cogito.org.uk
Wed Sep 26 16:16:36 EDT 2007

Jorge Marques Pelizzoni wrote:
> Hi, all!
> This is a newbie question: I sort of understand what unsafePerformIO does
> but I don't quite get its consequences. In short: how safe can one be in
> face of it? I mean, conceptually, it allows any Haskell function to have
> side effects just as in any imperative language, doesn't it? Doesn't it
> blow up referential transparency for good? Is there anything intrinsic to
> it that still keeps Haskell "sound" no matter what unsafePerformIO users
> do (unlikely) or else what are the guidelines we should follow when using
> it
unsafePerformIO does indeed lose referential transparency, or to be more 
precise, it fails to guarantee it.  If you call a computation with 
unsafePerformIO twice it may give different answers, depending on the IO 
value it wraps.  Therefore its up to the programmer to make sure that it 
doesn't matter how many times the computation is executed.  The Haskell 
compiler may (or may not) optimise multiple calls into one call.  If the 
result is not required then a lazy computation may mean that the 
computation is never used.  If you have two calls to unsafePerformIO 
then you can't rely on the ordering, and the strictness analyser may 
change the order as part of optimisation.  You get the picture.

So in summary, its up to you to make sure that the computation wrapped 
by unsafePerformIO has no side effects.  For instance if you wanted to 
read a configuration file and make the result look like a pure value 
then that would be a reasonable use for unsafePerformIO: reading the 
file is almost free of side effects (apart from updating the 
last-accessed time in some file systems), and the file isn't likely to 
change while you are reading it.


More information about the Haskell-Cafe mailing list