Mutable Arrays
Mutable states are typically found in imperative programming languages like C or Java, but they are not commonly used in purely functional languages such as Haskell. However, many algorithms are described using pseudocode that includes mutable states. To make it easier to implement such algorithms in Keelung, we have included mutable arrays in the language.
Type of Mutable Arrays
The general form of the type of a mutable array is ArrM t
, where t
represents the type of elements that the mutable array can store. Currently, t
can only be one of the following types:
Field
: Field elementsBoolean
: BooleansUInt
: Unsigned integers with bit widthw
ArrM a
: mutable arrays of any kind
Here are some examples of types of mutable arrays:
type | meaning |
---|---|
| An array of Field elements |
| An array of Booleans |
| An array of arrays of Field elements |
| An array of arrays of Booleans |
Construction / Conversion
From Haskell lists to mutable arrays
thaw takes a list of Values and process it into an Array.
Note that because toArrayM
is a statement. The resulting array of type ArrM t
is wrapped in Comp
. We can extract the array by using do-notation like this:
This way, array
would have type ArrM Number
in the scope.
From Haskell lists
Here are some helper functions of higher-dimension:
To Haskell lists
freeze
works as the inverse of toArrayM
. It takes a Keelung mutable array and converts it into a list.
Here are some helper functions of higher-dimension:
Functions
Access
Values within an array are indexed by an integer, starting from 0.
accessM
takes an array and an Int
as the index and returns the corresponding value.
Update
updateM
is very much like accessM
, but it takes an extra value to replace the corresponding entry in the array. update
only works on mutable arrays.
Length
lengthOf
returns the length of an array.
Last updated