Skip to content

Instantly share code, notes, and snippets.

@JohnLato
Created September 4, 2012 05:02
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save JohnLato/3616775 to your computer and use it in GitHub Desktop.
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