Skip to content

Instantly share code, notes, and snippets.

@hasufell hasufell/HMonad.hs
Last active Apr 19, 2016

Embed
What would you like to do?
-- |The GUI state.
data GUIState = GUIState { mygui :: MyGUI
, myview :: MyView
}
-- |Our own monad-ish type used to pass around our GUI state
-- and allow IO actions.
newtype HMonad a = HMonad { runHMonad :: GUIState -> IO (GUIState, a) }
instance Functor HMonad where
fmap f hex = HMonad $ \st -> do
(st', a) <- runHMonad hex st
return (st', f a)
instance Applicative HMonad where
pure a = HMonad $ \st -> return (st, a)
(<*>) f hex = HMonad $ \st -> do
(st', af) <- runHMonad f st
runHMonad (fmap af hex) st'
instance Monad HMonad where
return a = HMonad $ \st -> return (st, a)
(>>=) hm f = HMonad $ \st -> do
(st', a) <- runHMonad hm st
runHMonad (f a) st'
instance MonadIO HMonad where
liftIO ioa = HMonad $ \st -> do
a <- ioa
return (st, a)
hget :: HMonad (MyGUI, MyView)
hget = getState $ \st -> (mygui st, myview st)
hgetGUI :: HMonad MyGUI
hgetGUI = getState mygui
hgetView :: HMonad MyView
hgetView = getState myview
getState :: (GUIState -> a) -> HMonad a
getState f = HMonad $ \st -> return (st, f st)
putState :: (GUIState -> GUIState) -> HMonad ()
putState f = HMonad $ \st -> return (f st, ())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.