Skip to content

@JohnLato /IoState.hs
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
MonadState instance for IO (not sound!)
{-# 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
Something went wrong with that request. Please try again.