Lists
A list is the linked list of Elixir: an ordered sequence of values, written between square brackets. It is the collection a function returns when the number of items is not known in advance, and the collection most of the standard library is written for. Its one rule of cost is simple: adding at the front is one step, adding at the end walks the whole list.
List literals
Square brackets hold the items, separated by commas, and the items may have different types. An empty list is two brackets with nothing between them. is_list/1 answers whether a value is one:
literal.exs
numbers = [1, 2, 3] mixed = [1, "two", :three] empty = [] IO.inspect(numbers) IO.inspect(mixed) IO.inspect(empty) IO.puts(is_list(numbers)) IO.puts(is_list("abc"))
elixir literal.exs
[1, 2, 3]
[1, "two", :three]
[]
true
false
A string is not a list: "abc" is a binary, and the charlists of the Erlang library are the list form, which has its own lesson later in the course. A list whose items are all printable code points is what IO.inspect/1 shows as a charlist, ~c"abc", so IO.inspect([97, 98, 99]) prints the characters rather than the numbers. Inside the VM a list is a chain of cells: each cell holds one item and a pointer to the rest. That shape is what makes the next two sections cheap and the end of the list dear.
Head and tail
Every non-empty list has a head, its first item, and a tail, a list of the rest. hd/1 and tl/1 return them, and the pattern [head | tail] binds both in one match, which is the form a function clause uses:
head.exs
list = [1, 2, 3] IO.inspect(hd(list)) IO.inspect(tl(list)) [head | tail] = list IO.inspect(head) IO.inspect(tail)
elixir head.exs
1
[2, 3]
1
[2, 3]
The vertical bar is the cons operator, and it is also how a list is built: a list of one item has the item as its head and the empty list as its tail. A function that walks a list therefore has two clauses, one for [head | tail] and one for [], as recursion shows.
Prepend, concatenate and subtract
The cons operator adds one item at the front, and the new list shares the old one as its tail. The double plus joins two lists into one new list, and the double minus removes the first copy of each item of the right list:
build.exs
list = [2, 3] longer = [1 | list] IO.inspect(longer) IO.inspect([1, 2] ++ [3, 4]) IO.inspect([1, 2, 3] -- [2]) IO.puts(length(longer))
elixir build.exs
[1, 2, 3]
[1, 2, 3, 4]
[1, 3]
3
++ is right-associative, so [1] ++ [2] ++ [3] groups as [1] ++ ([2] ++ [3]) and copies the short left list once. -- removes one copy per item on the right, so [1, 1] -- [1] still holds one 1.
What each operation costs
[item | list] is one step whatever the length of the list: the VM makes one new cell and points it at the list. left ++ right walks the whole of left and copies it, so its cost grows with the left list, and length/1 walks the whole list too. The program below builds the same list in two directions, once with a prepend and once with an append, and the two results differ only in order:
cost.exs
front = Enum.reduce(1..5, [], fn n, acc -> [n | acc] end) back = Enum.reduce(1..5, [], fn n, acc -> acc ++ [n] end) IO.inspect(front) IO.inspect(back) IO.inspect(Enum.reverse(front))
elixir cost.exs
[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
The first reduce is linear; the second is quadratic, because each ++ copies everything built so far. With a few items the difference is invisible, and with a few hundred thousand it is the difference between a program that finishes and one that seems to hang. The habit is to build a result back to front and reverse it once at the end, which is what Enum does internally for the functions that keep the order.
The mistake: the head of an empty list
A pattern that asks for a head takes for granted that the list has one. Called with the empty list, it matches nothing and the program stops with a MatchError:
mistake.exs
[head | tail] = [] IO.inspect(head) IO.inspect(tail)
elixir mistake.exs
** (MatchError) no match of right hand side value:
[]
mistake.exs:1: (file)
(elixir 1.19.7) lib/code.ex:1613: Code.require_file/2
The fix is a clause or a branch for the empty list, or a function that answers for it: List.first([]) returns nil, and hd([]) raises an ArgumentError instead. A function that walks a list and has no clause for [] accepts an argument it cannot answer, and the crash names the call rather than the data.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which operation is one step, whatever the length of the list?
Answer
[item | list]
A prepend makes one new cell and points it at the old list, so its cost does not grow.
-
What does the pattern
[head | tail]bind tail to for the list[1, 2, 3]?Answer
[2, 3]
head takes the first item and tail takes a list of all the others.
-
Why is a loop that appends with
acc ++ [n]slow on a long list?Answer
Each ++ copies the whole of acc
The cost of left ++ right grows with left, so the loop becomes quadratic.
-
What does this program print?
IO.inspect([1, 2] ++ [3])Answer
[1, 2, 3]
The double plus joins the two lists in order into one new list.
-
What does this program print?
IO.inspect([1, 2, 3] -- [2])Answer
[1, 3]
The double minus removes the first copy of each item of the right list.
-
What does this program print?
IO.inspect(tl([10, 20, 30]))Answer
[20, 30]
tl/1 returns the list without its first item.
-
What does this program print?
IO.puts(is_list("abc"))Answer
false
A double-quoted string is a binary; a charlist is the list form of text.
-
What does this program print?
IO.inspect(List.first([]))Answer
nil
List.first/1 answers nil for an empty list, where hd/1 raises.
-
What does this program do?
[head | tail] = [] IO.inspect(head)Answer
A MatchError, because the empty list has no head
The pattern asks for a head and the empty list has none, so the match fails.
-
What does this program print?
IO.inspect(Enum.reverse([1, 2, 3]))Answer
[3, 2, 1]
Enum.reverse/1 returns the same items in the opposite order.
Автор статьи: Arthur Isaev