public
Last active

MonadState instance for IO (not sound!)

  • Download Gist
IoState.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ExtendedDefaultRules #-}
 
module IoState where
 
import Control.Monad.State.Class
 
import Data.IORef
import System.IO.Unsafe
 
type IoState s = IO
 
stRef :: IORef a
stRef = unsafePerformIO (newIORef undefined)
{-# NOINLINE stRef #-}
 
instance MonadState s (IoState s) where
get = readIORef stRef
put st = writeIORef stRef st
 
runIoState :: s -> IoState s a -> IO a
runIoState st action = do
writeIORef stRef st
action
 
test1 :: IO ()
test1 = runIoState (2 :: Int) (get >>= print)
-- prints "()"
 
test2 :: IO ()
test2 = runIoState (2 :: Int) (get >>= print . (+ (1::Int)))
-- prints "3"
 
test3 :: IO ()
test3 = runIoState (2 :: Int) (get >>= print . (+ (1 :: Double)))
-- prints "1.0"

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.