Alex Rivera | Logout

Functional Programming: what is an "improper list"?

Asked 2009-12-17T02:18:02.407
54

Could somebody explain what an "improper list" is?

Edit
Report

3 Answers

11

The definition of a list in Erlang is given in the manual - specifically Section 2.10

In Erlang the only thing you really need to know about improper lists is how to avoid them, and the way to do that is very simple - it is all down to the first 'thing' that you are going to build your list on. The following all create proper lists:

A = [].
B = [term()].
C = [term(), term(), term()].

In all these cases the syntax ensures that there is a hidden 'empty' tail which matches to '[]' sort of at the end....

So from them the following operations all produce a proper list:

X = [term() | A].
Y = [term() | B].
Z = [term() | C]. 

They are all operations which add a new head to a proper list.

What makes is useful is that you can feed each of X, Y or Z into a function like:

func([], Acc)      -> Acc;
func([H | T], Acc) -> NewAcc = do_something(H),
                      func(T, [NewAcc | Acc]).

And they will rip through the list and terminate on the top clause when the hidden empty list at the tail is all that is left.

The problem comes when your base list has been improperly made, like so:

D = [term1() | term2()]. % term2() is any term except a list

This list doesn't have the hidden empty list as the terminal tail, it has a term...

From here on downwards is mince as Robert Virding pointed out in the comments

So how do you write a terminal clause for it?

What makes it infuriating is that there is no way to see if a list is improper by inspecting it... print the damn thing out it looks good... So you end up creating an

answered 2009-12-17T09:33:33.103
4

I think possibly it refers to a "dotted pair" in LISP, e.g. a list whose final cons cell has an atom, rather than a reference to another cons cell or NIL, in the cdr.

EDIT

Wikipedia suggests that a circular list also counts as improper. See

http://en.wikipedia.org/wiki/Lisp_(programming_language)

and search for 'improper' and check the footnotes.

answered 2009-12-17T02:22:51.180
2

In Erlang a proper list is one where [H|T].

H is the head of the list and T is the rest of the list as another list.

An improper list does not conform to this definition.

answered 2009-12-17T03:40:16.700

Your Answer