5. List Handling

5 List Handling

5.1 Creating a List

Lists can only be built starting from the end and attaching list elements at the beginning. If you use the "++" operator as follows, a new list is created that is a copy of the elements in List1, followed by List2:

List1 ++ List2

Looking at how lists:append/1 or ++ would be implemented in plain Erlang, clearly the first list is copied:

append([H|T], Tail) ->
    [H|append(T, Tail)];
append([], Tail) ->
    Tail.

When recursing and building a list, it is important to ensure that you attach the new elements to the beginning of the list. In this way, you will build one list, not hundreds or thousands of copies of the growing result list.

Let us first see how it is n