Skip to content

Instantly share code, notes, and snippets.

@gbluma
Created June 23, 2012 04:57
Show Gist options
  • Save gbluma/2976940 to your computer and use it in GitHub Desktop.
Save gbluma/2976940 to your computer and use it in GitHub Desktop.
Finally wrote out a decent proof-of-concept for a resource pool
module GameState where
import qualified Control.Monad.State as ST
-- define our data structure w/o any special state information
data GameState = GameState {
gs_camera_x :: Float,
gs_camera_y :: Float,
gs_camera_z :: Float
}
-- define the local state monad functions
type State a = ST.StateT GameState IO a
type Selector a = (State a, a -> State ())
-- select returns the left half of the tuple. This yields the read-only portion
-- of our property.
select :: Selector a -> State a
select = fst
-- modify returns the right half of the tuple. This applies a function (mfun) to
-- the data structure inside the state monad.
modify :: Selector a -> (a -> a) -> State ()
modify (gf,uf) mfun = do
st <- gf
uf (mfun st)
-- the following are function pairs for getting/setting the gs_camera_x data
camera_x :: Selector Float
camera_x = (ST.gets gs_camera_x,
\x -> ST.modify (\vs -> vs { gs_camera_x = x }))
camera_y :: Selector Float
camera_y = (ST.gets gs_camera_y,
\y -> ST.modify (\vs -> vs { gs_camera_y = y }))
camera_z :: Selector Float
camera_z = (ST.gets gs_camera_z,
\z -> ST.modify (\vs -> vs { gs_camera_z = z }))
import qualified Control.Monad.State as ST
import qualified GameState as GameState
sample :: GameState.State ()
sample = do
GameState.modify GameState.camera_x (\x -> 4.0)
x <- GameState.select GameState.camera_x
ST.liftIO $ print x
main = do
ST.runStateT sample (GameState.GameState 0.0 0.0 0.0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment