Lists

A list is the workhorse of Erlang: a sequence of any number of terms, built from square brackets and taken apart with the bar. It is a linked list, so the front is cheap and the end is not, and the lists module holds the loops that every program writes once.

List literals

Square brackets build a list, and the items may mix numbers, strings and atoms. The empty list is two brackets with nothing between them. A string is a list of character codes, which is why it prints in quotes inside a list:

erl

1> [1, 2, 3]. [1,2,3] 2> [a, "two", 3]. [a,"two",3] 3> []. [] 4> [1, 2, 3] ++ [4, 5]. [1,2,3,4,5] 5> [1, 2, 3] -- [2]. [1,3]

++ joins two lists into a new one and copies the left list; -- removes the first copy of each item found in the right list. Both return a new list and leave the inputs alone. The double minus is not a set difference: [1, 1, 2] -- [1] is [1,2].

Head and tail

Every non-empty list splits into a head, the first item, and a tail, the list of the rest. hd/1 and tl/1 do it with a function, and the bar does it in a pattern:

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] 5> Head. 1 6> Tail. [2,3]

The bar builds as well as matches: [0 | List] is a list whose head is zero and whose tail is List. An improper list such as [1 | 2] is legal and prints as [1|2], but length/1 and the list functions refuse it: a list ends with [], not with a number.

Prepend is cheap

Adding to the front with the cons operator takes one step, however long the list is. The old list stays untouched and the new one shares its tail, so a loop that builds a result back to front is linear. Appending with ++ copies the left list on every call, which turns the same loop quadratic. This module squares each number and prepends as it returns:

squares.erl

-module(squares). -export([main/0, squares/1]). squares([]) -> []; squares([Number | Rest]) -> [Number * Number | squares(Rest)]. main() -> io:format("~p~n", [squares([1, 2, 3, 4])]).

erlc squares.erl

erl -noshell -eval 'squares:main(), halt().'

[1,4,9,16]

The result comes out in the input order because the constructor wraps the recursive result; the prepend happens on the way back out. A filter has the same shape, with a guard that keeps some items:

evens.erl

-module(evens). -export([main/0, evens/1]). evens([]) -> []; evens([Number | Rest]) when Number rem 2 =:= 0 -> [Number | evens(Rest)]; evens([_ | Rest]) -> evens(Rest). main() -> io:format("~p~n", [evens([1, 2, 3, 4, 5, 6])]).

erlc evens.erl

erl -noshell -eval 'evens:main(), halt().'

[2,4,6]

Concatenate and subtract

When the result must be in the reverse order, build it with an accumulator and the prepend becomes the whole loop. This reverse is the one the standard library uses:

reverse.erl

-module(reverse). -export([main/0, reverse/1]). reverse(List) -> reverse(List, []). reverse([], Acc) -> Acc; reverse([Head | Tail], Acc) -> reverse(Tail, [Head | Acc]). main() -> io:format("~p~n", [reverse([1, 2, 3])]).

erlc reverse.erl

erl -noshell -eval 'reverse:main(), halt().'

[3,2,1]

The accumulator holds the result built so far, and the base case returns it. This is the tail-recursive shape of the recursion lesson: each step moves one item from the input to the accumulator and nothing waits for the return.

The lists module

The lists module holds the loops above as functions: map/2, filter/2, foldl/3, reverse/1, sort/1, member/2, nth/2, seq/2, zip/2, sum/1 and last/1. A session is enough to see the shapes:

erl

1> lists:seq(1, 5). [1,2,3,4,5] 2> lists:sort([3, 1, 2]). [1,2,3] 3> lists:member(2, [1, 2, 3]). true 4> lists:nth(2, [a, b, c]). b 5> lists:sum([1, 2, 3]). 6 6> lists:zip([1, 2], [a, b]). [{1,a},{2,b}]

map/2 and filter/2 take a function, so they wait for the funs lesson and Higher-order functions; foldl/3 is the general loop behind both. The list comprehension lesson writes map and filter in one expression. This lesson is not the library documentation: the lists module itself is documented in the OTP documentation on the machine.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How do you write a list of three numbers?

    Answer

    [1, 2, 3]

    Square brackets build a list; curly braces build a tuple.

  2. 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.

  3. 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.

  4. 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.

  5. What does this module print? -module(q4). -export([main/0]). main() -> Found = lists:member(b, [a, b, c]), io:format("~p~n", [Found]).

    Answer

    true

    b is the second item of the list, so lists:member/2 answers true.

  6. 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.

  7. What does [1 | 2] build?

    Answer

    An improper list whose tail is the number 2

    The tail of a cons must be a list; here it is the number 2, so the result is improper and length/1 refuses it.

  8. What does this module print? -module(q1). -export([main/0]). main() -> io:format("~p~n", [lists:seq(2, 4)]).

    Answer

    [2,3,4]

    lists:seq/2 returns every integer from the first to the second, inclusive.

  9. What does this module print? -module(q2). -export([main/0, squares/1]). squares([]) -> []; squares([N | Rest]) -> [N * N | squares(Rest)]. main() -> io:format("~p~n", [squares([2, 3])]).

    Answer

    [4,9]

    The constructor keeps the input order, so the squares are [4,9].

  10. What does this module print? -module(q3). -export([main/0]). reverse(List) -> reverse(List, []). reverse([], Acc) -> Acc; reverse([H | T], Acc) -> reverse(T, [H | Acc]). main() -> io:format("~p~n", [reverse([a, b, c])]).

    Answer

    [c,b,a]

    Each head is prepended to the accumulator, so the last item becomes the first.

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