I am creating a Haskell application that generates a random number on an infinite loop (only when requested by a client). However, I should only use pure functions for that purpose. Is it safe to wrap randomIO
with unsafeperformIO
without any drastic stability or performance risk?
Risks of using unsafeperformIO on randomIO
1.2k views Asked by Axel Advento At
2
There are 2 answers
0
On
I am creating a Haskell application that generates a random number on an infinite loop (only when requested by a client). However, I should only use pure functions for that purpose. Is it safe to wrap randomIO with unsafeperformIO without any drastic stability or performance risk?
Aside from performance (no risk) or stability (small risk), consider also the fact that you are writing non-canonical Haskell for no good reason. Your code will be difficult for anyone else to maintain if you take this approach.
Any use of
unsafePerformIO
should be justified by a proof that the resulting value is still pure. The rigour of the proof is up to you and the importance of the work. For example, this pathetic useunsafePerformIO
andrandomIO
should be safe, because you can prove that whenslowTrue
returns anything, it will returnTrue
.The following tempting definition of a global, possibly random variables is not safe:
The problem is that the same expression will now yield different values:
prints here:
(at least when compiled without optimizations – but that just stresses the fragility of inappropriate use of
unsafePerformIO
).