Tuples vs lists

Mikael Pettersson mikpe@REDACTED
Wed Feb 1 13:14:06 CET 2006


Fernando Rodriguez writes:
 > Hi,
 > 
 > I'm going through the Erlang tutorial,and I don't understand very well the
 > difference between tuples and lists. For example, form the tutorial:
 > 
 > o represent the temperature of various cities of the world we could write
 > 
 > {moscow, {c, -10}}
 > {cape_town, {f, 70}}
 > {paris, {f, 28}}
 >     
 > 
 > Why not use [moscow, [c, -10]] instead? 

Be prepared for an all-out religious flamewar. Seriously.

1. 2-tuples {X,Y} and cons-cells [X|Y] are semantically equivalent
   except for type (tuple vs "list") and syntax: both allow you to
   store two terms in a container, to pass around that container,
   and to retrieve the stored terms.

2. Lists [...] are built from cons-cells [_|_] and the empty list,
   [], so [X,Y,Z] is really [X|[Y|[Z|[]]]]. For this reason, some
   people(*) equate cons-cells with lists and strongly dislike
   cons-cells being used to build non-lists, to the point where
   they consider that to be a programming error.

3. N-tuples have constant-time indexing, while lists of N elements
   have O(N)-time indexing. Aggregates of more than two elements
   will be slower to access when stored in lists than when stored
   in tuples.

   This is assuming the list representation of a 2-element aggregate
   uses a single cons-cell: [X|Y]. Your example above, [c,-10],
   is really [c|[-10|[]]], so it uses two cons-cells and will be
   larger and slower to access than the 2-tuple {c,-10}.

4. Cons-cells have a representation in the current Erlang/OTP system
   that is slightly more compact and cheap to test for or index than
   2-tuples. This is why some people (not the (*) ones above obviously)
   like to use cons-cells instead of 2-tuples for 2-element aggregates.

/Mikael



More information about the erlang-questions mailing list