# Using unsafePerformIO safely?

**URL:** <https://discourse.haskell.org/t/using-unsafeperformio-safely/4146>\
**Category:** Uncategorized\
**Created:** [February 28, 2022, 2:41pm UTC](https://discourse.haskell.org/t/using-unsafeperformio-safely/4146 "2022-02-28T14:41:23Z")\
**Posts on this page:** 1\
**Showing post:** 9

<div class="post-metadata">

**Author:** ![jaror](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/jaror/32/3271_2.png) [@jaror](https://discourse.haskell.org/u/jaror)\
**Post date:** [February 28, 2022, 8:58pm UTC](https://discourse.haskell.org/t/using-unsafeperformio-safely/4146/9 "2022-02-28T20:58:50Z")

</div>

> [@VictorCMiraldo](#):
>
> never forget `{-# NOINLINE ... #-}`

As long as the IO action is actually really pure (e.g. running another Haskell program that only uses `interact` in its main function), then no special measures are necessary. Things like `NOINLINE`, `-fno-cse`, and `-fno-full-laziness` are only required if you still want the side-effects of each `unsafePerformIO` call to be performed exactly once.

> [@VictorCMiraldo](#):
>
> Are there some other contexts that work particularly well to illustrate other situations?

I’m imagining a context like

```haskell
E[x] = do evaluate x; readFile "test"

```

This shows that `writeFile "test" "something"` is not pure, because `do evaluate (unsafePerformIO (writeFile "test" "something")); readFile "test"` is clearly different than `do evaluate (); readFile "test"`. However, this does require some kind of equality on the IO type.

How else would we prove that `writeFile "test" "something"` is not pure?

> [@VictorCMiraldo](#):
>
> How do exceptions get handled?

Exceptions can only be caught from inside IO. In the pure subset of Haskell throwing an exception is like entering an infinite loop. Exceptions thrown from within the unsafely performed IO are no different. Catching exceptions inside the `unsafePerformIO` actually seems kind of strange to me, is the following function pure?

```haskell
f x = unsafePerformIO (evaluate (x `seq` True) `catch` (\e -> (e :: SomeException) `seq` pure False))

```

That’s a good question.

---

_[View the full topic](https://discourse.haskell.org/t/using-unsafeperformio-safely/4146)._
