Lists
List literals
Square brackets build a list, and items can mix numbers, strings, and atoms. The empty list is two brackets with nothing between them.
erl
1> [1, 2, 3].
[1,2,3]
2> [a, "two", 3].
[a,"two",3]
3> [].
[]
Head and tail
Every non empty list splits into a head, the first item, and a tail, the rest. The hd function returns the head and the tl function returns the tail.
The pattern on the last line binds both parts in a single match.
erl
1> List = [1, 2, 3].
[1,2,3]
2> hd(List).
1
3> tl(List).
[2,3]
4> [Head | Tail] = List.
[1,2,3]
Prepend is cheap
Adding to the front with the cons operator takes one step, no matter how long the list is. The old list stays untouched, and the new list shares its tail with the old one.
Building results back to front and reversing at the end is the fast habit in Erlang.
erl
1> List = [2, 3].
[2,3]
2> Longer = [1 | List].
[1,2,3]
3> length(Longer).
3
Concatenate
The double plus operator joins two lists into one new list. The double minus operator removes the first copy of each item found on the right.
Both return fresh lists and leave the inputs alone, in line with the single-assignment rule of lesson 5.
erl
1> [1, 2] ++ [3, 4].
[1,2,3,4]
2> [1, 2, 3] -- [2].
[1,3]
Next: Tuples
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
How do you write a list of three numbers?
Answer
[1, 2, 3]Square brackets build a list; curly braces build a tuple.
-
What is the head of
[1, 2, 3]?Answer
1The head is the first item, and the tail is the rest of the list.
-
What is the tail of
[1, 2, 3]?Answer
[2,3]The tail is the list without its first item, so it holds 2 and 3.
-
What does
hd([1, 2, 3]).return?Answer
1hd/1returns the first item of a non-empty list. -
What does
tl([1, 2, 3]).return?Answer
[2,3]tl/1returns the list without its first item. -
Which expression adds
1to the front of[2, 3]?Answer
[1 | [2, 3]]The cons operator
|puts the new head in front of the existing list. -
How expensive is prepending one item to a list?
Answer
It takes one step whatever the length
The new list shares the old tail, so only a new head cell is created.
-
What does
[1, 2] ++ [3, 4].return?Answer
[1,2,3,4]The double plus joins the two lists in order into one new list.
-
What does
[1, 2, 3] -- [2].return?Answer
[1,3]The double minus removes the first copy of each item found on the right.
-
Why build a result back to front and reverse it at the end?
Answer
Prepending is cheap while appending to the end is not
Each prepend takes one step, so the loop stays linear; appending to the end would copy the list every time.
The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev