Orasund/elm-static-array/1.0.0

NOTE: the latest version is 3.0.0

StaticArray

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.

type alias StaticArray n a =
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 One a

Constructs an array with a single item.

fromList : Length n -> a -> List a -> StaticArray n a

Constructs an array from a list

push : a -> StaticArray n a -> StaticArray (OnePlus n) a

Adds a element to the end of the array.

get : 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 : Index n -> a -> StaticArray n a -> StaticArray n a

Sets an element of the array.

length : StaticArray n a -> Length n

Returns the length of an 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.

singleton 42
|> push 7
|> resize (Length.one |> Length.plus4)
|> toArray
|> Array.toList --> [42,7,42,42,42]
toArray : StaticArray n a -> Array a

Transforms the static array into a dynamic array.

map : (a -> a) -> StaticArray n a -> StaticArray n a

Updates all elements of an array.

indexedMap : (Index n -> a -> a) -> StaticArray n a -> StaticArray n a

Same as map but with an index.

StaticArray n a
-> { length : Length n
, head : a
, tail : Array a
}

Exposes the underlying record of the array

array =
    [0,1,2,3,4,5]
        |> fromList (Length.five |> Length.plus1 )

array |> toRecord |> fromRecord --> array
{ 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.

fromRecord
    { length = (Length.five |> Length.plus1 )
    , head = 0
    , tail = [1,2,3,4,5]
    }
    --> fromList (Length.five |> Length.plus1 ) [0,1,2,3,4,5]