How to specify a list, which's last element is referring to the first element?

By specify I mean, for example, how to write a setq statement with this list.
I have seen this in the documentation, but I can't find it anymore. Here some pointers:

  • You could loop over the elements of the list forever, but it uses only about as much memory as it has real elements.
  • Its cdr points to its car.
  • You could call it a ring list, but I do not mean stuff from the ring package.
  • It is something basic.

I do not have a use in mind, it's just for learning and experimenting.

  • So you want an infinite list or you want a circular list? (-1 since this appears in search results for the title, but the contents are different) – mihai Jun 6 at 11:32

See the Elisp manual, node Circular Objects.

A circular list is one way to implement an infinite list.

For example (from the doc), this creates a list in which the first element recurs as the third element:

(setq x  '(#1=(a) b #1#))

In your case:

(setq ys  '(1 2 3 4))
(setq ll  (last ys))
(setcdr ll ys) 

C-h v ys:

#1=(1 2 3 4 . #1#)
  • It would be better to write (setq ys (list 1 2 3 4)) since you're going to modify the list object – npostavs Jun 29 '17 at 14:25
  • This is exactly the documentation I was searching for. This #1=(a #1#) was what I meant. Thank you for the nice setq example. – jue Jun 29 '17 at 14:25
  • @npostavs Thanks for the hint, I thought ' and list are just different notations. I better have an extra look into the manual. :) – jue Jun 29 '17 at 14:29
  • list vs ' doesn't matter for this simple illustration. What matters is that you must not expect ' to always create new list structure (it doesn't). list always creates a new cons. – Drew Jun 29 '17 at 14:51
  • 2
    @npostavs: Agreed. For its purpose here it is OK. Plugged into a different context, the behavior might surprise someone unaware of how ' is handled. – Drew Jun 29 '17 at 17:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.