In Erlang as in many other languages, a list is a collection of elements. Lists in Erlang are surrounded by “[” and “]”. For example the list of the first ten integer numbers is expressed as follows:

List = [1,2,3,4,5,6,7,8,9].

A very useful way of looking at parts of lists, is by using “|”. For example you can divide the list into first element and others elements as follows:

1> List = [1,2,3,4,5,6,7,8,9].
2> [FirstElement | OthersElements] = List.

And now you can access the list by using FirstElement and/or OthersElements.

3> FirstElement.
4> OthersElements.

Using te above notation we can easily implement a recursive function to compute the length of the list:


listLength([]) -> 0;
listLength([FirstElement | OthersElements]) -> 1 + listLength(OthersElements).

save the above src code as mylists.erl, then open the erlang shell and compile it:

1> c(mylists).
mylists.erl:5: Warning: variable 'FirstElement' is unused

2> mylists:listLength([a,b,c,d,e]).

Lists editing:
As we have seen, with Erlang we can create a new list using a simple notation:

List = [1,2,3,4,5,6,7,8,9].

An empty list is defined like:

EmptyList = [].

Erlang provides a lot of useful stuff to edit lists.

Adding an element at the head of a list:
The operator “|” can also be used to add an element at the beginning of a list, for example.

NewList = [0 | List].

will produce:


Concatenate lists:
Imagine you have the following two lists

List = [1,2,3,4,5,6,7,8,9].
List1 = [a,b,c].

You can concatenate the two lists using the ++ operator:

10> ConcList = List ++ List1.

Populating lists:
Fill a list with the first 100 integer numbers.
To fill a list with the first 100 integer number you can use the seq function provided by the lists module:

11> List2 = lists:seq(1, 100).

If you want a list containing the first 50 even integer numbers:

16> List3 = lists:seq(0, 100, 2).

and naturally the odd numbers:

17> List4 = lists:seq(1, 100, 2).

Take a look at the lists manual page, there are a lot of useful functions:

all/2, any/2, append/1, append/2, concat/1, delete/2, droplast/1, dropwhile/2, duplicate/2, filter/2, filtermap/2, flatlength/1, flatmap/2, flatten/1, flatten/2, foldl/3, foldr/3, foreach/2, keydelete/3, keyfind/3, keymap/3, keymember/3, keymerge/3, keyreplace/4, keysearch/3,keysort/2, keystore/4, keytake/3, last/1, map/2, mapfoldl/3, mapfoldr/3, max/1, member/2, merge/1, merge/2, merge/3, merge3/3, min/1, nth/2, nthtail/2, partition/2, prefix/2, reverse/1, reverse/2, seq/2, seq/3, sort/1, sort/2, split/2, splitwith/2, sublist/2, sublist/3, subtract/2, suffix/2, sum/1, takewhile/2, ukeymerge/3, ukeysort/2, umerge/1, umerge/2, umerge/3, umerge3/3, unzip/1, unzip3/1, usort/1, usort/2, zip/2, zip3/3, zipwith/3, zipwith3/4.