title: Am I abusing unsafePerformIO?
body: <p>To get acquainted with <code>unsafePerformIO</code> (how to use it and when to use it), I've implemented a module for generating unique values.</p>
  
  <p>Here's what I have:</p>
  
  <pre><code>module Unique (newUnique) where
  
  import Data.IORef
  import System.IO.Unsafe (unsafePerformIO)
  
  -- Type to represent a unique thing.
  -- Show is derived just for testing purposes.
  newtype Unique = U Integer
    deriving Show
  
  -- I believe this is the Haskell'98 derived instance, but
  -- I want to be explicit, since its Eq instance is the most
  -- important part of Unique.
  instance Eq Unique where
    (U x) == (U y) = x == y
  
  counter :: IORef Integer
  counter = unsafePerformIO $ newIORef 0
  
  updateCounter :: IO ()
  updateCounter = do
    x &lt;- readIORef counter
    writeIORef counter (x+1)
  
  readCounter :: IO Integer
  readCounter = readIORef counter
  
  newUnique' :: IO Unique
  newUnique' = do { x &lt;- readIORef counter
                  ; writeIORef counter (x+1)
                  ; return $ U x }
  
  newUnique :: () -&gt; Unique
  newUnique () = unsafePerformIO newUnique'
  </code></pre>
  
  <p>To my delight, the <a href="http://hackage.haskell.org/package/base-4.3.1.0/docs/Data-Unique.html" rel="noreferrer">package</a> called <code>Data.Unique</code> chose the same datatype as I did; on the other hand, they chose the type <code>newUnique :: IO Unique</code>, but I want to stay out of <code>IO</code> if possible. </p>
  
  <p>Is this implementation dangerous? Could it possibly lead GHC to change the semantics of a program which uses it?</p>