Arrays in Elm
Our first program will demonstrate how to work with arrays in Elm. Here’s the full source code:
In Elm, arrays are implemented as the Array
type from the Array
module. They are immutable data structures, which means that operations that seem to modify an array actually return a new array.
We start by importing the necessary modules and defining our main
function.
We then create an empty array using Array.empty
. Unlike in some languages, Elm arrays don’t have a fixed size, and they can grow or shrink as needed.
We can create and initialize an array in one line using Array.fromList
.
To set a value at a specific index, we use Array.set
. This returns a new array with the updated value.
To get a value at a specific index, we use Array.get
. This returns a Maybe
value, as the index might be out of bounds.
The Array.length
function returns the length of an array.
We can create multi-dimensional arrays by nesting Array
types. In this example, we create a 2D array.
When we run this program, it will display the results of our array operations in the browser.
Note that in Elm, arrays are typically used for random access and when you know the length of the collection in advance. For many other use cases, Elm programmers often prefer to use List
, which is optimized for prepending elements and iterating from left to right.