Arrays in Elixir

Our first program will demonstrate how to work with arrays in Elixir. Here’s the full source code:

defmodule ArrayExample do
  def run do
    # Create an array (list) with 5 elements, all initialized to 0
    a = List.duplicate(0, 5)
    IO.puts("emp: #{inspect(a)}")

    # Set a value at an index
    a = List.replace_at(a, 4, 100)
    IO.puts("set: #{inspect(a)}")
    IO.puts("get: #{Enum.at(a, 4)}")

    # Get the length of the array
    IO.puts("len: #{length(a)}")

    # Declare and initialize an array in one line
    b = [1, 2, 3, 4, 5]
    IO.puts("dcl: #{inspect(b)}")

    # Create an array with specific values at specific indices
    c = [100] ++ List.duplicate(0, 2) ++ [400, 500]
    IO.puts("idx: #{inspect(c)}")

    # Create a 2D array
    two_d = [
      [0, 1, 2],
      [1, 2, 3]
    ]
    IO.puts("2d: #{inspect(two_d)}")

    # Create and initialize a 2D array
    two_d = [
      [1, 2, 3],
      [1, 2, 3]
    ]
    IO.puts("2d: #{inspect(two_d)}")
  end
end

ArrayExample.run()

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:

$ elixir array_example.exs
emp: [0, 0, 0, 0, 0]
set: [0, 0, 0, 0, 100]
get: 100
len: 5
dcl: [1, 2, 3, 4, 5]
idx: [100, 0, 0, 400, 500]
2d: [[0, 1, 2], [1, 2, 3]]
2d: [[1, 2, 3], [1, 2, 3]]

Note that lists in Elixir are printed in the form [v1, v2, v3, ...] when inspected or printed.