Want to learn?

Lists

Representation

Documentation

The list is a collection of values which can be represented by any type. Furthermore, these values don't have to be unique. You can define a list by putting zero or more values between brackets:

iex> []
[]
iex> [1, :hello, nil, "hello"]
[1, :hello, nil, "hello"]
iex> [1, 1, 1]
[1, 1, 1]

In every list, there is a specific order of values. For example, when we're dealing with:

[1, :hello, nil, "hello"]

we can precisely specify that 1 is the first element, :hello is the second one, and so on. It is very important since the most common operation on the list is an iteration.

Linked list

A list is implemented as linked list data structure. In short, it means that every element of collection points to the next one in order. Because of that, when we iterate over such a collection, we have to start from the first element and go one by one. This is why it's faster to add a new element to the beginning of a list, rather than the end.

Head and Tail

A list consist of two elements:

  1. The head which contains a value.

  2. The tail which is itself a list.

There is a special operator that make use of these two elements: pipe operator. You can use it to represent the split between the head and the tail:

iex> [ "first element" | [2, :three] ]
["first element", 2, :three]

In this example we define a list that has:

  • head element represented by "first element" string value,

  • tail element which is itself a list of two elements: 2 and :three.

Pipe operator appends value of head to the beginning of tail's list. This operation is based on recursion. You can nest pipe operator inside of another list:

iex> [ "first element" | [ 2 | [ :three | [] ] ] ]
["first element", 2, :three]

List concatenation

You can merge two lists into one:

iex> [1, :two, "three"] ++ ["4", 5, :six]
[1, :two, "three", "4", 5, :six]

List on the right side of the ++ operator, in this case ["4", 5, :six], becomes tail of a new list. These two operations are equal regarding the returned result:

iex> [1, :two, "three"] ++ ["4", 5, :six]
[1, :two, "three", "4", 5, :six]
iex> [1, :two, "three" | ["4", 5, :six] ]
[1, :two, "three", "4", 5, :six]

Deleting elements

You can delete one or more elements from list at once:

iex> [1, 2, 2, 2, 3, 3] -- [1, 2, 3]
[2, 2, 3]

This operation is searching for values in the list on the left side which are also specified in the list on the right side. It starts searching from the left side of the list and deletes first matching value.

Start a project with your dedicated software house

Top

Contact us

* Required fields

Elo Mordo!Elo Mordo!