2 | import Data.IOArray.Prims
7 | record IOArray elem where
8 | constructor MkIOArray
10 | content : ArrayData (Maybe elem)
13 | max : IOArray elem -> Int
17 | newArray : HasIO io => Int -> io (IOArray elem)
19 | = pure (MkIOArray size !(primIO (prim__newArray size Nothing)))
22 | writeArray : HasIO io => IOArray elem -> Int -> elem -> io Bool
23 | writeArray arr pos el
24 | = if pos < 0 || pos >= max arr
26 | else do primIO (prim__arraySet (content arr) pos (Just el))
30 | readArray : HasIO io => IOArray elem -> Int -> io (Maybe elem)
32 | = if pos < 0 || pos >= max arr
34 | else primIO (prim__arrayGet (content arr) pos)
39 | newArrayCopy : HasIO io =>
40 | (newsize : Int) -> IOArray elem -> io (IOArray elem)
41 | newArrayCopy newsize arr
42 | = do let newsize' = if newsize < max arr then max arr else newsize
43 | arr' <- newArray newsize'
44 | copyFrom (content arr) (content arr') (max arr - 1)
47 | copyFrom : ArrayData (Maybe elem) ->
48 | ArrayData (Maybe elem) ->
50 | copyFrom old new pos
53 | else do el <- primIO $
prim__arrayGet old pos
54 | primIO $
prim__arraySet new pos el
55 | copyFrom old new $
assert_smaller pos (pos - 1)
58 | toList : HasIO io => IOArray elem -> io (List (Maybe elem))
59 | toList arr = iter 0 (max arr) []
61 | iter : Int -> Int -> List (Maybe elem) -> io (List (Maybe elem))
64 | then pure (reverse acc)
65 | else do el <- readArray arr pos
66 | assert_total (iter (pos + 1) end (el :: acc))
69 | fromList : HasIO io => List (Maybe elem) -> io (IOArray elem)
71 | = do arr <- newArray (cast (length ns))
75 | addToArray : Int -> List (Maybe elem) -> IOArray elem -> io ()
76 | addToArray loc [] arr = pure ()
77 | addToArray loc (Nothing :: ns) arr = addToArray (loc + 1) ns arr
78 | addToArray loc (Just el :: ns) arr
79 | = do primIO $
prim__arraySet (content arr) loc (Just el)
80 | addToArray (loc + 1) ns arr