I'll try to explain the reasoning for runST
's type:
runST :: (forall s. ST s a) -> a
And why it isn't like this simple one:
alternativeRunST :: ST s a -> a
Note that this alternativeRunST
would had worked for your program.
alternativeRunST
would also had allowed us to leak variables out of the ST
monad:
leakyVar :: STRef s Int
leakyVar = alternativeRunST (newSTRef 0)
evilFunction :: Int -> Int
evilFunction x =
alternativeRunST $ do
val <- readSTRef leakyVar
writeSTRef leakyVar (val+1)
return (val + x)
Then you could go in ghci and do:
>>> map evilFunction [7,7,7]
[7,8,9]
evilFunction
is not referentially transparent!
Btw, to try it out yourself here's the "bad ST" framework needed to run the code above:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
import Control.Monad
import Data.IORef
import System.IO.Unsafe
newtype ST s a = ST { unST :: IO a } deriving Monad
newtype STRef s a = STRef { unSTRef :: IORef a }
alternativeRunST :: ST s a -> a
alternativeRunST = unsafePerformIO . unST
newSTRef :: a -> ST s (STRef s a)
newSTRef = ST . liftM STRef . newIORef
readSTRef :: STRef s a -> ST s a
readSTRef = ST . readIORef . unSTRef
writeSTRef :: STRef s a -> a -> ST s ()
writeSTRef ref = ST . writeIORef (unSTRef ref)
The real runST
doesn't allow us to construct such "evil" functions. How does it do it? It's kinda tricky, see below:
Trying to run:
>>> runST (newSTRef "Hi")
error:
Couldn't match type `a' with `STRef s [Char]'
...
>>> :t runST
runST :: (forall s. ST s a) -> a
>>> :t newSTRef "Hi"
newSTRef "Hi" :: ST s (STRef s [Char])
newSTRef "Hi"
doesn't fit (forall s. ST s a)
. As can be also seen using an even simpler example, where GHC gives us a pretty nice error:
dontEvenRunST :: (forall s. ST s a) -> Int
dontEvenRunST = const 0
>>> dontEvenRunST (newSTRef "Hi")
<interactive>:14:1:
Couldn't match type `a0' with `STRef s [Char]'
because type variable `s' would escape its scope
Note that we can also write
dontEvenRunST :: forall a. (forall s. ST s a) -> Int
And it is equivalent to omitting the forall a.
as we did before.
Note that the scope of a
is larger than that of s
, but in the case of newSTRef "Hi"
its value should depend on s
. The type system doesn't allow this.