List is the the most important data type in Erlang, as in every functional programming language. In this article, I will present the Erlang’s lists module and its most important functions.
Syntax
1
|
|
N is called the length of the list. So, [] is the empty list.
Decomposing & Pattern Matching
An empty list pattern matches with [].
1 2 3 4 5 6 7 8 9 10 11 12 |
|
A non-empty list pattern matches with [Head | Tail].
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Normal Representation
The format [Element1, Element2, …, ElementN] is a shorthand of [Element1 | [Element2 | … | [ElementN | []] … ] representation.
Example: the list [1, 2, 3] is a shorthand of [1 | [2 | 3 | []]], that is the normal representation of a list.
Decomposing:
1 2 3 4 5 6 7 8 9 10 |
|
Composing:
1 2 3 4 5 6 7 8 |
|
Of course, since it is more readable and easier to write, the shorthand representation is usually used:
1 2 3 4 5 6 7 8 9 10 11 |
|
List Parsing
The pattern matching you saw before can be used in a function in order to parse the list:
1 2 3 4 |
|
Concatenation
Two lists can be concatenated using ++:
1 2 3 4 5 6 7 8 9 10 |
|
Difference
You can take the difference of two lists (the left-hand side one without the element of the right-hand side) using the – operator:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Module Lists
The lists module defines some commonly used list processing functions. This module is extremely useful, so it is a good idea to “remember” what functions it provides.
all/2
Called as all(Pred, List). Returns true if Pred(Element) returns true for all lists’ elements.
1 2 3 4 5 6 7 8 9 10 |
|
append/1|2
Concatenates the lists to one.
1 2 3 4 |
|
Notice that the operator ++ and the function append/2 are the same.
delete/2
Deletes an element from the list (first occurrence, if any).
1 2 |
|
concat/1
Accepts a list of items (atom, integer, float, string) and returns the concatenation of their textual representation as a list.
1 2 |
|
filter/2
Called as filter(Pred, List). Returns a list containing only the elements that return true for the Pred.
1 2 3 4 5 6 |
|
flatten/1
Returns a flattened (no element is a list) version of the input list.
1 2 |
|
key*** functions
There are several functions which their name starts with the word “key”. They are all used to process lists of tuples.
1 2 3 4 5 6 7 8 9 10 |
|
last/1
Returns the last element of the list.
1 2 |
|
map/2
Called as map(Fun, List). Applies function Fun to every item of the list and returns the resulting list.
1 2 |
|
partition/2
Partitions a list to two according to if the elements satisfy or not a given predicate.
1 2 |
|
reverse/1|2
Returns the reverse of a list.
1 2 3 4 |
|
sort/1|2
Sorts a list to increasing order or according to a given function.
1 2 3 4 5 6 7 8 |
|
sum/1
Returns the sum of the elements of a list containing numbers.
1 2 |
|
u*** functions
There are several function which their name starts with “u” and the results they return contain no duplicates.
1 2 |
|