Arrays in Elixir
Our first program will demonstrate how to work with arrays in Elixir. Here’s the full source code:
In Elixir, we don’t have traditional arrays like in some other languages. Instead, we use lists, which are implemented as linked lists. However, we can use them in a similar way to arrays in other languages.
Here we create a list a
that will hold exactly 5 integers. By default, we initialize it with zeros using List.duplicate/2
.
We can set a value at an index using the List.replace_at/3
function, and get a value with Enum.at/2
.
The built-in length/1
function returns the length of a list.
We can declare and initialize a list in one line using the [1, 2, 3, 4, 5]
syntax.
To create a list with specific values at specific indices, we can concatenate lists using the ++
operator.
List types are one-dimensional, but you can compose types to build multi-dimensional data structures. In this case, we create a list of lists to represent a 2D array.
You can create and initialize multi-dimensional lists at once too.
To run the program, save it as array_example.exs
and use elixir
:
Note that lists in Elixir are printed in the form [v1, v2, v3, ...]
when inspected or printed.