2

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.

4
  • 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
    Commented Jun 6, 2019 at 11:32
  • @mihai I don't know what you are talking about. Maybe writing an answer would be more helpful than downvoting.
    – jue
    Commented Jun 19, 2019 at 19:56
  • see this answer. It has a nice picture, too. Cyclic and infinite are two different things. You ask for one in the title, but for the other one in your actual question.
    – mihai
    Commented Jun 20, 2019 at 6:11
  • @mihai thats the way learning goes, It didn't occured to me there is difference. Also I'm no native english speaker, so I rely on (maybe inaccurate) dictionarys and approximations ... Anyway, thanks for the hint.
    – jue
    Commented Sep 17, 2019 at 10:28

1 Answer 1

3

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#)
8
  • 1
    It would be better to write (setq ys (list 1 2 3 4)) since you're going to modify the list object
    – npostavs
    Commented Jun 29, 2017 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
    Commented Jun 29, 2017 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
    Commented Jun 29, 2017 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
    Commented Jun 29, 2017 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
    Commented Jun 29, 2017 at 17:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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