From 754bbf7a25a8dda49b5d08ef0d0443bbf5af0e36 Mon Sep 17 00:00:00 2001 From: Craig Jennings Date: Sun, 7 Apr 2024 13:41:34 -0500 Subject: new repository --- devdocs/elisp/setcar.html | 70 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 devdocs/elisp/setcar.html (limited to 'devdocs/elisp/setcar.html') diff --git a/devdocs/elisp/setcar.html b/devdocs/elisp/setcar.html new file mode 100644 index 00000000..67867eb1 --- /dev/null +++ b/devdocs/elisp/setcar.html @@ -0,0 +1,70 @@ +

Altering List Elements with setcar

Changing the CAR of a cons cell is done with setcar. When used on a list, setcar replaces one element of a list with a different element.

Function: setcar cons object +
+

This function stores object as the new CAR of cons, replacing its previous CAR. In other words, it changes the CAR slot of cons to refer to object. It returns the value object. For example:

(setq x (list 1 2))
+     ⇒ (1 2)
+
+
(setcar x 4)
+     ⇒ 4
+
+
x
+     ⇒ (4 2)
+
+
+

When a cons cell is part of the shared structure of several lists, storing a new CAR into the cons changes one element of each of these lists. Here is an example:

;; Create two lists that are partly shared.
+(setq x1 (list 'a 'b 'c))
+     ⇒ (a b c)
+(setq x2 (cons 'z (cdr x1)))
+     ⇒ (z b c)
+
+ +
;; Replace the CAR of a shared link.
+(setcar (cdr x1) 'foo)
+     ⇒ foo
+x1                           ; Both lists are changed.
+     ⇒ (a foo c)
+x2
+     ⇒ (z foo c)
+
+ +
;; Replace the CAR of a link that is not shared.
+(setcar x1 'baz)
+     ⇒ baz
+x1                           ; Only one list is changed.
+     ⇒ (baz foo c)
+x2
+     ⇒ (z foo c)
+
+

Here is a graphical depiction of the shared structure of the two lists in the variables x1 and x2, showing why replacing b changes them both:

        --- ---        --- ---      --- ---
+x1---> |   |   |----> |   |   |--> |   |   |--> nil
+        --- ---        --- ---      --- ---
+         |        -->   |            |
+         |       |      |            |
+          --> a  |       --> b        --> c
+                 |
+       --- ---   |
+x2--> |   |   |--
+       --- ---
+        |
+        |
+         --> z
+
+

Here is an alternative form of box diagram, showing the same relationship:

x1:
+ --------------       --------------       --------------
+| car   | cdr  |     | car   | cdr  |     | car   | cdr  |
+|   a   |   o------->|   b   |   o------->|   c   |  nil |
+|       |      |  -->|       |      |     |       |      |
+ --------------  |    --------------       --------------
+                 |
+x2:              |
+ --------------  |
+| car   | cdr  | |
+|   z   |   o----
+|       |      |
+ --------------
+
+
+

+ Copyright © 1990-1996, 1998-2022 Free Software Foundation, Inc.
Licensed under the GNU GPL license.
+ https://www.gnu.org/software/emacs/manual/html_node/elisp/Setcar.html +

+
-- cgit v1.2.3