[Haskell-beginners] Getting Stuff out of IO Handles

Jared Hance jaredhance at gmail.com
Fri Jun 24 01:46:59 CEST 2011


> If you want to know if you can do something like:
> 
> someFunction :: Int -> Int
> someFunction n = escapeIO $ someIOAction n
> 
> then the answer is you shouldn't. It is technically possible, by using a
> function that every experienced haskell developer will tell you to never
> ever ever ever ever ever ever ever (get the picture) use, which is
> unsafePerformIO, but if you use unsafePerformIO it's likely that your code
> won't do what you actually expect it to do, even if the type signatures all
> check correctly. The IO Monad serves a very important purpose and implies
> certain things about a computation, likewise the absence of the IO Monad
> implies certain guarantees, and when you break those guarantees bad things
> happen.

I'd like to clarify a bit here. The unsafePerformIO function has a use,
and should be used, but only in the right circumstances. The problem is
that often a function is referentially transparent, but haskell cannot
prove that it is because it uses the IO Monad.

The circumstance in which this crops up is usually when you use the FFI.
The function you call in C might return a pointer to something, rather
than the data itself. The pointer will usually be different every time,
so the result isn't referentially transparent. However, if you extract
the data from the pointer, that data _is_ referentially transparent and
is, as such, a good use case for unsafePerformIO.

So I would say an experienced programmer would say to never use it if
you don't know what you are doing, but if you do, use it when you need
it.



More information about the Beginners mailing list