Arrays in Elm
Our first program will demonstrate how to work with arrays in Elm. Here’s the full source code:
module Main exposing (main)
import Html exposing (Html, div, text)
import Array exposing (Array)
main : Html msg
main =
div []
[ demonstrateArrays
]
demonstrateArrays : Html msg
demonstrateArrays =
let
-- Create an empty array of integers
emptyArray : Array Int
emptyArray =
Array.empty
-- Create and initialize an array in one line
initializedArray : Array Int
initializedArray =
Array.fromList [1, 2, 3, 4, 5]
-- Set a value at an index
updatedArray : Array Int
updatedArray =
Array.set 4 100 initializedArray
-- Get a value at an index
fifthElement : Maybe Int
fifthElement =
Array.get 4 updatedArray
-- Create a 2D array
twoDArray : Array (Array Int)
twoDArray =
Array.fromList
[ Array.fromList [1, 2, 3]
, Array.fromList [4, 5, 6]
]
in
div []
[ text ("Empty array: " ++ Debug.toString emptyArray)
, Html.br [] []
, text ("Initialized array: " ++ Debug.toString initializedArray)
, Html.br [] []
, text ("Updated array: " ++ Debug.toString updatedArray)
, Html.br [] []
, text ("Fifth element: " ++ Maybe.withDefault "Not found" (Maybe.map String.fromInt fifthElement))
, Html.br [] []
, text ("Length of array: " ++ String.fromInt (Array.length initializedArray))
, Html.br [] []
, text ("2D array: " ++ Debug.toString twoDArray)
]
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.