3

I'm reading An Introduction to Programming in Emacs Lisp by Robert J. Chassell.
When the book is introducing setcar, it points out that when we use this function to a list, the list should be initialized in this way:

(setq list1 (list 'a 'b 'c))

instead of

(setq list2 '(a b c))

And then

(setcar list1 'A)

But if I evaluate list1 and list2, Emacs gives me the same list (a b c).
I don't see any difference here. As a matter of fact, (setcar list2 'A) is also evaluated successfully.

Page 76
...Because we intend to use setcar to change the list, this setq should not use the quoted form '(antolope giraffe lion tiger), as that would yield a list that is part of the program and bad things could happen if we tried to change part of the program while running it.
Generally speaking an Emacs Lisp program's components should be constant (or unchanged) while the program is running. So we instead construct an animal list by using the list function, as follows: setq animals (list 'antelope 'giraffe 'lion 'tiger))

Drew
  • 75,699
  • 9
  • 109
  • 225
Lluvio Liu
  • 73
  • 6
  • 3
    See [`(info "(elisp) Mutability")`](https://www.gnu.org/software/emacs/manual/html_node/elisp/Mutability.html). – Basil Jan 21 '21 at 12:21
  • 1
    I think [Modifying Existing List Structure](https://www.gnu.org/software/emacs/manual/html_node/elisp/Modifying-Lists.html) might be even better entry point to Elisp documentation as it clearly states _"Destructive operations should be applied only to mutable lists, that is, lists constructed via cons, list or similar operations. Lists created by quoting are part of the program and should not be changed by destructive operations."_ and then refers to [Mutability](https://www.gnu.org/software/emacs/manual/html_node/elisp/Mutability.html). – user272735 Jan 21 '21 at 17:32
  • https://emacs.stackexchange.com/tags/elisp/info – Drew Jan 21 '21 at 18:53
  • 2
    Does this answer your question? [Why does a constant in \`let\` change with repeated calls?](https://emacs.stackexchange.com/questions/20535/why-does-a-constant-in-let-change-with-repeated-calls) – phils Jan 21 '21 at 23:22
  • 1
    Does this answer your question? [Evaluating symbol in function arguments affected by destructive operations?](https://emacs.stackexchange.com/questions/45814/evaluating-symbol-in-function-arguments-affected-by-destructive-operations) – Drew Jan 22 '21 at 16:51

1 Answers1

1

Internally, in function definitions, Emacs stores the list if it is written as '(a b c). If you modify it using destructing operations like setcar you actually change the function definition.

Lindydancer
  • 6,095
  • 1
  • 13
  • 25