Previous: , Up: Lists   [Contents][Index]


5.5.2.6 Infinite Lists

Sometimes it is useful to be able to create ‘infinite’ lists—that is, lists which appear to have no last element—this can easily be done in Lisp by linking the cdr of the last cons cell in the list structure back to the beginning of the list.

 -----------------------------------
|                                   |
 --> +-----+-----+   +-----+-----+  |
     |  o  |  o----> |  o  |  o-----
     +--|--+-----+   +--|--+-----+
        |               |
         --> 1           --> 2

The diagram above represents the infinite list (1 2 1 2 1 2 …).

Infinite lists have a major drawback though, many of the standard list manipulation functions can not be used on them. These functions work by moving through the list until they reach the end. If the list has no end the function may never terminate and the only option is to send the interpreter an interrupt signal.

The only functions which may be used on circular lists are: the cons cell primitives (cons, car, cdr, rplaca, rplacd), nth and nthcdr.

Also note that infinite lists can’t be printed. But note the print-length and print-level variables, see Output Functions.