The nthcdr function can be used in conjunction with the rplaca
function to modify an arbitrary element in a list. For example,
(rplaca (nthcdr 2 '(0 1 2 3 4 5)) 'foo)
=> foo
sets the third element of the list (0 1 2 3 4 5) to the symbol
called foo.
There are also functions which modify the structure of a whole list. These are called destructive operations because they modify the actual structure of a list -- no copy is made. This can lead to unpleasant side effects if care is not taken.
append,
it modifies its arguments so that it can return a list which is the
concatenation of the elements in its arguments lists.
Like all the destructive functions this means that the lists given as
arguments are modified (specifically, the cdr of their last cons cell
is made to point to the next list). This can be seen with the
following example (similar to the example in the append documentation).
(setq foo '(1 2))
=> (1 2)
(setq bar '(3 4))
=> (3 4)
(setq baz (nconc foo bar))
=> (1 2 3 4)
foo
=> (1 2 3 4) ;`foo' has been altered!
(eq (nthcdr 2 baz) bar)
=> t
The following diagram shows the final state of the three variables more clearly,
foo--> bar-->
baz--> +-----+-----+ +-----+-----+ +-----+-----+ +-----+-----+
| o | o----> | o | o----> | o | o----> | o | |
+--|--+-----+ +--|--+-----+ +--|--+-----+ +--|--+-----+
| | | |
--> 1 --> 2 --> 3 --> 4
(setq foo '(1 2 3))
=> (1 2 3)
(nreverse foo)
=> (3 2 1)
foo
=> (1) ;`foo' wasn't updated when the list
; was altered.
equal to object then returns the modified list.
(delete t '(nil t nil t nil))
=> (nil nil nil)
When this function is used to remove an element from a list which is stored
in a variable that variable must be set to the return value of the
delete function. Otherwise, if the first element of the list
has to be deleted (because it is equal to object) the value
of the variable will not change.
(setq foo '(1 2 3))
=> (1 2 3)
(delete 1 foo)
=> (2 3)
foo
=> (1 2 3)
(setq foo (delete 1 foo))
=> (2 3)
delete function, the only difference
is that the eq function is used to compare object with each
of the elements in list, instead of the equal function which
is used by delete.
Go to the first, previous, next, last section, table of contents.