# [erlang-questions] Irregular list

Robert Virding rvirding@REDACTED
Thu Feb 12 20:11:53 CET 2009

```2009/2/12 Mihai Balea <mihai@REDACTED>

> Maybe I'm missing something, but what is the point of even allowing
> the concept of cons cells? Wouldn't a tuple be more generic?
> Is there any practical use of "improper lists" in Erlang?

Tuples and lists have different properties and different uses. Tuples have
fixed a size and are typically used when you know how many elements there
are. Changing the size of a tuple is basically impossible so if you want to
add/remove an another element to a tuple you have to create a new tuple
which is different from the old tuple. A typical use for a tuple is when you
want to return more than one value from a function where you return a tuple
containg the values.

Lists, on the other hand, are dynamic objects. It is easy and cheap to
add/remove elements to/from the front of the list, the without having to
copy the rest of the list. It is also very easy to step over the elements of
a list. A list is built up of pairs, cons cells, where the first element,
the head, of the pair is the element of the list while second element, the
tail, points to the next pair/cons cell of the list. A pair is written in
Erlang as [a|b] and a list as [a,b,c,d] which is syntactic sugar for the
actual representation which is written as [a|[b|[c|[d|[]]]]]. Note that the
tail of the last pair is []. This makes it a what is called a proper list.
If the tail of the last pair is not a [] then it is not a proper list. [] is
therefore considered to be the empty list as it contains no elements.

Many (most) list processing functions assume that the lists they work on are
proper lists, typically by stepping down the list as long as they tail is
another list pair until they get to a []. Length/1 is like this. The test
is_list/1 is very simple and test whether its arguments is a pair or the
empty list []. It does not check the whole list.

Re: Paul Fisher and the dict module. Dict uses lists for example to keep all
the values which have the same key. There is one place in dict where a
cons-cell is used in what would normally be a 2-element tuple, it does
[Key|Listof Values] instead of {Key,ListofValues}, but that is just joke and
serves no practical purpose.

I hope this clears up some issues and doesn't add to the confusion,

Robert
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20090212/93128bbe/attachment.htm>
```