MonadState instance for IO (not sound!)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment