[newbie] refactor function?

Håkan Huss <>
Wed Feb 2 13:36:59 CET 2005


Since you want a general rule:

* If E is an element (of any type) and L is a list, [E | L] returns a
list beginning with E and continuing with the elements of L.

However, [...|...] is more general. The truth is that:

* If E1 and E2 are Erlang terms (of any type), [E1 | E2] creats a pair
(usually referred to as a cons or a cons cell) containing E1 and E2.

For example, creating a cons cell with the terms 1 and 2 is done using
[1 | 2] (try it in the shell!). Since cons cells normally are used to
create lists (next paragraph), this is sometimes called an improper
list.

Regarding lists, they can be recursively defined by noting that a list is:
* Either the empty list, denoted [], or
* A pair [E | L], where E is any Erlang term and L is a list.

Thus, the following are all lists:
[]
[3 | []]
[2 | [3 | []]]
[1 | [2 | [3 | []]]]

Since lists are common, there is a special, more convenient notation
for them. The above lists can instead be written:
[]
[3]
[2, 3]
[1, 2, 3]

However, this is just so called syntactic sugar for the above
notations. Knowing this makes a number of "strange" special cases
disappear. E.g., [H | T] = [1, 2, 3] yielding H==1 and T==[2,3]. Why?
Simple, rewrite the list into its "true form":
[H | T] = [1 | [2 | [3 | []]]]  => H==1, T==[2 | [3 | []]] (== [2,3])
No magic...

The ++ operator is intended to operate on two lists and returns a new
list containing all elements from the left operand followed by all the
elements of the right operand.

(Also, adding items to the end of a list often leads to
inefficiencies, but "first make it work then make it fast" :-)

/Håkan

On Wed, 02 Feb 2005 12:49:03 +0100, Bengt Kleberg
<> wrote:
> Gaspar Chilingarov wrote:
> ...deleted
> > in case of joining single element to list
> >
> >
> > [ Element | List ] is equal to [ Element ] ++ List
> > but [ List | Element ] creates nested list instead of
> > List ++ [ Element ]
> 
> [ List | Element ] does not create a ''proper'' list.
> 
> you can not add an item to the end of a list.
> ++ appends 2 lists. you can not use it on items.
> 
> 
> bengt
>



More information about the erlang-questions mailing list