This module introduces the StaticArray
. A static array is a non empty array fix a fixed size.
We can check the size in compile-time and ensure that the array is about as fast as a usual (dynamic) array in run time.
Internal.StaticArray n a
A static array is an array with a fixed length.
singleElement : StaticArray One Int
singleElement =
singleton 42
twoElements : StaticArray Two Int
twoElements =
singleElement
|> push 7
singleton : a -> StaticArray Index.One a
Constructs an array with a single item.
fromList : Length n -> ( a, List a ) -> StaticArray n a
Constructs an array from a list
import StaticArray.Length as Length
fromList Length.five (0,[])
|> toList
--> [0,0,0,0,0]
fromList Length.five (0,[1,2,3,4])
|> toList
--> [0,1,2,3,4]
initialize : Length n -> (Basics.Int -> a) -> StaticArray n a
Initiate an array and fill it.
import StaticArray.Length as Length
initialize Length.five (\i -> i*i)
--> fromList Length.five (0,[1,4,9,16])
push : a -> StaticArray n a -> StaticArray (Index.OnePlus n) a
Adds an element to the end of the array.
get : Internal.Index n -> StaticArray n a -> a
Gets an element of the array. Note that it only possible if the index is in bound. Therefore eliminating Off-by-one errors.
set : Internal.Index n -> a -> StaticArray n a -> StaticArray n a
Sets an element of the array.
resize : Length m -> StaticArray n a -> StaticArray m a
Changes the size of the array. If the array gets bigger, then the first element of the array gets used as default value.
import StaticArray.Length as Length
import Array
singleton 42
|> push 7
|> resize (Length.one |> Length.plus4)
|> toArray
|> Array.toList --> [42,7,42,42,42]
length : StaticArray n a -> Length n
Returns the length of an array.
map : (a -> b) -> StaticArray n a -> StaticArray n b
Updates all elements of an array.
indexedMap : (Internal.Index n -> a -> b) -> StaticArray n a -> StaticArray n b
Same as map but with an index.
toArray : StaticArray n a -> Array a
Transforms the static array into a dynamic array.
toList : StaticArray n a -> List a
Transforms the static array into a list.
toRecord : StaticArray n a -> { length : Length n, head : a, tail : Array a }
Exposes the underlying record of the array
import StaticArray.Length as Length
import StaticArray.Index exposing (Five,OnePlus)
array : StaticArray (OnePlus Five) Int
array =
fromList (Length.five |> Length.plus1) (0,[1,2,3,4,5])
array
|> toRecord
|> fromRecord
--> array
fromRecord : { length : Length n, head : a, tail : Array a } -> StaticArray n a
Constructs a static array from its components. If the Length is bigger then the number of elements provided, the additional element will be filled with duplicates of head.
import StaticArray.Length as Length
import Array
fromRecord
{ length = (Length.five |> Length.plus1)
, head = 0
, tail = Array.fromList [1,2,3,4,5]
}
--> fromList (Length.five |> Length.plus1) (0,[1,2,3,4,5])