Skip to content

Instantly share code, notes, and snippets.

@chessai
Created February 26, 2019 15:54
Show Gist options
  • Save chessai/e170fc8271a867d413136f7207552408 to your computer and use it in GitHub Desktop.
Save chessai/e170fc8271a867d413136f7207552408 to your computer and use it in GitHub Desktop.
module Example (main) where
import Data.IORef
import Data.Primitive
import Data.Primitive.PrimArray
import GHC.Prim (RealWorld)
main :: IO ()
main = do
let len = 30
arr <- newInitialise len
modifyArray (+1) arr
x <- readPrimArray arr (len `div` 2)
print x
newInitialise :: Int -> IO (MutablePrimArray RealWorld Int)
newInitialise sz = do
arr <- newPrimArray sz
let go :: Int -> IO ()
go ix = if ix < sz
then writePrimArray arr ix 0 >> go (ix + 1)
else pure ()
go 0
pure arr
modifyArray :: (Int -> Int) -> MutablePrimArray RealWorld Int -> IO ()
modifyArray f arr = do
let sz = sizeofMutablePrimArray arr
let go :: Int -> IO ()
go ix = if ix < sz
then do
atIx <- readPrimArray arr ix
writePrimArray arr ix (f atIx)
go (ix + 1)
else pure ()
go 0
{-
x <- newIORef 0
add1 x
v <- readIORef x
print v
add1 :: IORef Int -> IO ()
add1 x = modifyIORef' x (+1)
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment