[Haskell-cafe] Is it safe to use unsafePerformIO here?

Cristiano Paris cristiano.paris at gmail.com
Tue Sep 15 15:34:46 EDT 2009


On Tue, Sep 15, 2009 at 9:16 PM, Svein Ove Aas <svein.ove at aas.no> wrote:
> I have a number of suggestions, some of which conflict with each
> other, so I'll just throw them out here. Let's see..

:)

> First off, the IO monad does indeed enforce sequencing; that's its
> primary purpose.

So, unsafePerformIO can be thought as an escape to this strict rule.

> However, you can ask for it to run I/O out of order,
> specifically when the value the out-of-order action returns is
> actually forced (used); that's lazy I/O, and is implemented using
> unsafeInterleaveIO.

I imagined that. But I hate to have to use unsafePerformIO when
hGetContets is already using it.

> You would not usually use unsafeInterleaveIO directly, though.

That's the point.

> Instead, you'd use an existing wrapper, such as hGetContents. (for
> Strings, or lazy bytestrings; the strict bytestring variant reasonably
> has a strict semantics)
>
> One thing to keep in mind about lazy I/O is that the I/O in question
> can run at any arbitrary time, or not at all; not more than once,
> though. You must make sure this is safe. For file input, that
> basically means the file should not change during the program's
> lifetime.

Ok.

> hGetLine is not lazy in this way, but the hGetContents you use is. I'm
> not sure whether this means your program should work as-is, and I'm
> not going to examine it closely enough to tell - as you mentioned it's
> a mockup anyway. Besides..
>
> Strings are also *slow*. What you want for I/O is, when reasonably
> possible, bytestrings. You'd then use parsec-bytestring, or if
> possible Data.Binary, to parse said bytestring; the latter is faster
> (..probably), if more limited in function.

Yes, that was only a first attempt, kind of prototype...

> You could use the lazy bytestring hGetContents for this. However...
>
> There is also a bytestring-mmap package on hackage, which outsources
> the decision of what blocks to load into memory to the OS, and has the
> best performance overall. Use this.
>
>
> Oh. And unsafePerformIO is a trap that will kill you. See
> http://www.girlgeniusonline.com/comic.php?date=20070725 for details.

Thank you for the link.

Cristiano


More information about the Haskell-Cafe mailing list