Modeling the ST monad in Agda
This recent SO question prompted me to write an unsafe and pure emulation of the ST monad in Haskell, a slightly modified version of which you can see below: {-# LANGUAGE DeriveFunctor, GeneralizedNewtypeDeriving, RankNTypes #-} import Control.Monad.Trans.State import GHC.Prim (Any) import Unsafe.Coerce (unsafeCoerce) import Data.List newtype ST s a = ST (State ([Any], Int) a) deriving (Functor, Applicative, Monad) newtype STRef s a = STRef Int deriving Show newSTRef :: a -> ST s (STRef s a) newSTRef a = ST $ do (env, i) <- get put (unsafeCoerce a : env, i + 1) pure (STRef i) update :: [a] ->