Lists
| List literals | |
| Head and tail | |
| Prepend is cheap | |
| Concatenate |
List literals
Square brackets build a list, and items can mix numbers, strings, and atoms.
An empty list is two brackets with nothing between them.
The is_list check below answers true for the numbers binding.
numbers = [1, 2, 3]
mixed = [1, "two", :three]
empty = []
is_list(numbers)
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.
list = [1, 2, 3]
hd(list)
tl(list)
[head | tail] = list
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 is the fast habit in Elixir.
list = [2, 3]
longer = [1 | list]
length(longer)
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.
[1, 2] ++ [3, 4]
[1, 2, 3] -- [2]
Next: Tuples
Article author: Arthur Isaev