Nyquist / XLISP 2.0  -  Contents | Tutorials | Examples | Reference

Circular Lists



Known XLISP Problems with Circular Lists


Warning: do not try this with XLISP:

> (setq my-list (cons 'item nil))  ; create a 1-item list
(ITEM)

> (setf (cdr my-list) my-list))    ; create the circle
ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM
ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM
ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM
ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ITEM ...

If you're lucky you can break the loop. If not, then XLISP will print the ITEM forever.

  Back to top


c-nth


The 'c-nth' macro accesses a linear list as if it were circular:

(defmacro c-nth (index list)
  `(nth ,(rem index (length list)) ,list))

Note that with every call to 'c-nth', the length of the list will be computed again.

Examples:

(c-nth 0 '(1 2 3))  => 1
(c-nth 1 '(1 2 3))  => 2
(c-nth 2 '(1 2 3))  => 3
(c-nth 3 '(1 2 3))  => 1
(c-nth 4 '(1 2 3))  => 2
(c-nth 5 '(1 2 3))  => 3
(c-nth 6 '(1 2 3))  => 1
(c-nth 7 '(1 2 3))  => 2
Because 'c-nth' is a macro expanding into a regular nth form, 'c-nth' can be used with setf:
(setq lst '(1 2 3))      => (1 2 3)
lst                      => (1 2 3)
(setf (c-nth 4 lst) 'x)  => X
lst                      => (1 X 3)

  Back to top


Nyquist / XLISP 2.0  -  Contents | Tutorials | Examples | Reference