Arrays in Erlang

In Erlang, arrays are typically represented using tuples or lists. Tuples are fixed-size containers, while lists are variable-length. For this example, we’ll use tuples to represent fixed-size arrays and lists for dynamic-sized arrays.

-module(arrays).
-export([main/0]).

main() ->
    % Here we create a tuple 'A' that will hold exactly 5 integers.
    % By default, elements are initialized to the atom 'undefined'.
    A = {undefined, undefined, undefined, undefined, undefined},
    io:format("emp: ~p~n", [A]),

    % We can set a value at an index using the setelement/3 function,
    % and get a value with element/2.
    A2 = setelement(5, A, 100),
    io:format("set: ~p~n", [A2]),
    io:format("get: ~p~n", [element(5, A2)]),

    % The tuple_size/1 function returns the size of a tuple.
    io:format("len: ~p~n", [tuple_size(A2)]),

    % Use this syntax to declare and initialize a tuple in one line.
    B = {1, 2, 3, 4, 5},
    io:format("dcl: ~p~n", [B]),

    % For dynamic-sized arrays, we can use lists.
    C = [1, 2, 3, 4, 5],
    io:format("list: ~p~n", [C]),

    % To create a list with specific indices, we can use a list comprehension.
    D = [100 | [0 || _ <- lists:seq(1, 2)]] ++ [400, 500],
    io:format("idx: ~p~n", [D]),

    % For multi-dimensional data structures, we can use nested tuples or lists.
    TwoD = {{0,1,2}, {1,2,3}},
    io:format("2d: ~p~n", [TwoD]),

    % You can also create and initialize multi-dimensional structures at once.
    TwoD2 = {{1,2,3}, {1,2,3}},
    io:format("2d: ~p~n", [TwoD2]).

To run the program, save it as arrays.erl and use the Erlang shell:

$ erl
1> c(arrays).
{ok,arrays}
2> arrays:main().
emp: {undefined,undefined,undefined,undefined,undefined}
set: {undefined,undefined,undefined,undefined,100}
get: 100
len: 5
dcl: {1,2,3,4,5}
list: [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}}
ok

Note that Erlang uses different syntax for printing and representing data structures. Tuples are enclosed in curly braces {}, while lists use square brackets [].

Erlang doesn’t have mutable arrays like some other languages. Instead, when you “modify” a tuple or list, you’re actually creating a new one with the changes. This immutability is a key feature of Erlang’s design.