Preface: Here is what happens with LIST-LENGTH in Common Lisp:
Code: Select all
(list-length (cons 'a (cons 'chicken 'cat)))
=> error: undefined function LIST-LENGTH
Question: Is this Scheme (other Lisp dialect than Common Lisp) what your are talking about?
Sorry: The text above is wrong! - see Ramarren's comment below. The rest is still true:
But in Scheme as well as in Common Lisp, the problem is in principle the same.
The main underlying data structure in Lisp is not the list, but the cons cell. Lisp lists are build of cons cells. Lisp differs between two forms of lists, "proper" lists and "dotted" lists, where the main difference is that in a "proper" list the CDR of the LAST cons cell must be NIL.
With your CONS code from above you create a "dotted" list, because the last element is 'cat and not NIL:
Code: Select all
(cons 'a (cons 'chicken 'cat)) => (a chicken . cat) ; with a dot
+---+---+ +---+---+
-->| * | * -->| * | * --> cat
+-|-+---+ +-|-+---+
v v
a chicken
Here the same example as a proper list, created by the LIST function:
Code: Select all
(list 'a 'chicken 'cat) => (a chicken cat) ; with no dot
+---+---+ +---+---+ +---+---+
-->| * | * -->| * | * -->| * | * -->nil
+-|-+---+ +-|-+---+ +-|-+---+
v v v
a chicken cat
To create a "proper" list with CONS you must write:
Code: Select all
(cons 'a (cons 'chicken (cons 'cat nil))) => (a chicken cat) ; with no dot
To test if a list is a "proper" list you must write:
The reason why this is not a built-in function is that the test must follow all cons-cell pointers until it finds the LAST cell, to test if the CDR of the LAST cell is NIL. This test is very slow with long lists.
David Touretzky's book:
includes a program to print the CONS cells on the screen.