Skip to content

Instantly share code, notes, and snippets.

@RTS2013
Last active June 6, 2019 08:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RTS2013/6bb4112777850effadb3 to your computer and use it in GitHub Desktop.
Save RTS2013/6bb4112777850effadb3 to your computer and use it in GitHub Desktop.
import Control.Applicative
import Control.Monad.ST.Safe
import qualified Data.Vector.Unboxed as IU
import qualified Data.Vector.Unboxed.Mutable as U
-- Mutable world
data World s = World
{ _souls :: !(U.STVector s Int)
, _positions :: !(U.STVector s (Float,Float))
}
-- Immutable world
data IWorld = IWorld
{ _iSouls :: !(IU.Vector Int)
, _iPositions :: !(IU.Vector (Float,Float))
} deriving (Show)
-- Thaw immutable world, apply update, freeze again.
worldST :: IWorld -> (World s -> ST s (World s)) -> ST s IWorld
worldST world f = do
stWorld <- World
<$> IU.thaw (_iSouls world)
<*> IU.thaw (_iPositions world)
newWorld <- f stWorld
IWorld
<$> IU.unsafeFreeze (_souls newWorld)
<*> IU.unsafeFreeze (_positions newWorld)
main :: IO ()
main = do
let w = IWorld (IU.replicate 100 0) (IU.replicate 100 (0,0))
print $ runST (worldST w return)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment