Use of unsafePerformIO appropriate?

Is using unsafePerformIO to allow read-only IO calls to non-changing files in pure code appropriate or is it going to cause a lot of problems?

The main reason is because I'd like to store them in containers and for example, make them an instance of Ord , but I can't seem to imagine how to do that without wrapping IO calls in unsafePerformIO .


On safety

Using unsafePerformIO in the way you describe should not cause any problems.

The thumb rule is: if you are using unsafePerformIO to define a function which could be defined without it in Haskell, then you are using it safely.

In your case, you essentially use it to achieve the same effect of defining some fixed values in your code. That is, you could just include your read-only non-changing files in your source code, at the cost of keeping the whole lot of data in memory. So your use is safe.

For example, if you invented a primality test which somehow exploits a fixed 100MB data table, then it would be alright to use unsafePerformIO to access an immutable file containing it. This would trade code purity for performance (memory footprint), without compromising safety.

On appropriateness

Since unsafePerformIO is indeed unsafe (the burden of proving the program safe is on you), it should be regarded as a last resort, and definitely not as the default way for reading a file's contents.

It's hard to understand whether your case really justifies using unsafePerformIO . You should describe what you are trying to achieve in more detail.

I'd guess that, if your program is going to read the files and store their whole contents in memory, then you would get no performance advantage from unsafePerformIO , and you should use pure code instead.

链接地址: http://www.djcxy.com/p/43234.html

上一篇: 结合Free类型

下一篇: 使用unsafePerformIO合适吗?