ArrayRef-0.1: Examples/Array/Dynamic.hs
-- This example demonstrates using of `DynamicIOArray`,
-- i.e. arrays whose bounds can be changed dynamically,
-- including automatic growth as `writeArray` requires.
--
-- Other types of dynamic arrays - DynamicIOUArray, DynamicSTArray,
-- DynamicSTUArray and manually constructed dynamic array types
-- can be used in the same fashion.
import Data.ArrayBZ.Dynamic
main = do
-- This array will grow at least two times each time when index is out of bounds,
-- because it is created using `newDynamicArray growTwoTimes`
arr <- newDynamicArray growTwoTimes (0,-1) 99 :: IO (DynamicIOArray Int Int)
-- At this moment the array is empty
printArray arr
-- During this cycle the array extended 3 times
for [0..5] $ \i ->
writeArray arr i i
printArray arr
-- During this cycle the array extended one more time
for [-5 .. -1] $ \i ->
writeArray arr i i
printArray arr
-- Operation that explicitly resizes the array
resizeDynamicArray arr (3,15)
printArray arr
-- This array will not grow automatically because it is created using `newArray`,
-- but it can be resized explicitly using `resizeDynamicArray`
arr <- newArray (0,-1) 99 :: IO (DynamicIOArray Int Int)
resizeDynamicArray arr (0,0)
printArray arr
writeArray arr 1 1 -- this operation raises error
-- Print dynamic array bounds and contents
printArray arr = do
bounds <- getBounds arr
contents <- getElems arr
putStrLn (show bounds++" : "++show contents)
for list action = mapM_ action list