]> code.delx.au - gnu-emacs/blob - lispref/lists.texi
Initial revision
[gnu-emacs] / lispref / lists.texi
1 @c -*-texinfo-*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
4 @c See the file elisp.texi for copying conditions.
5 @setfilename ../info/lists
6 @node Lists, Sequences Arrays Vectors, Strings and Characters, Top
7 @chapter Lists
8 @cindex list
9 @cindex element (of list)
10
11 A @dfn{list} represents a sequence of zero or more elements (which may
12 be any Lisp objects). The important difference between lists and
13 vectors is that two or more lists can share part of their structure; in
14 addition, you can insert or delete elements in a list without copying
15 the whole list.
16
17 @menu
18 * Cons Cells:: How lists are made out of cons cells.
19 * Lists as Boxes:: Graphical notation to explain lists.
20 * List-related Predicates:: Is this object a list? Comparing two lists.
21 * List Elements:: Extracting the pieces of a list.
22 * Building Lists:: Creating list structure.
23 * Modifying Lists:: Storing new pieces into an existing list.
24 * Sets And Lists:: A list can represent a finite mathematical set.
25 * Association Lists:: A list can represent a finite relation or mapping.
26 @end menu
27
28 @node Cons Cells
29 @section Lists and Cons Cells
30 @cindex lists and cons cells
31 @cindex @code{nil} and lists
32
33 Lists in Lisp are not a primitive data type; they are built up from
34 @dfn{cons cells}. A cons cell is a data object which represents an ordered
35 pair. It records two Lisp objects, one labeled as the @sc{car}, and the
36 other labeled as the @sc{cdr}. These names are traditional; @sc{cdr} is
37 pronounced ``could-er.''
38
39 A list is a series of cons cells chained together, one cons cell per
40 element of the list. By convention, the @sc{car}s of the cons cells are
41 the elements of the list, and the @sc{cdr}s are used to chain the list:
42 the @sc{cdr} of each cons cell is the following cons cell. The @sc{cdr}
43 of the last cons cell is @code{nil}. This asymmetry between the
44 @sc{car} and the @sc{cdr} is entirely a matter of convention; at the
45 level of cons cells, the @sc{car} and @sc{cdr} slots have the same
46 characteristics.
47
48 The symbol @code{nil} is considered a list as well as a symbol; it is
49 the list with no elements. For convenience, the symbol @code{nil} is
50 considered to have @code{nil} as its @sc{cdr} (and also as its
51 @sc{car}).
52
53 The @sc{cdr} of any nonempty list @var{l} is a list containing all the
54 elements of @var{l} except the first.
55
56 @node Lists as Boxes
57 @comment node-name, next, previous, up
58 @section Lists as Linked Pairs of Boxes
59 @cindex box representation for lists
60 @cindex lists represented as boxes
61 @cindex cons cell as box
62
63 A cons cell can be illustrated as a pair of boxes. The first box
64 represents the @sc{car} and the second box represents the @sc{cdr}.
65 Here is an illustration of the two-element list, @code{(tulip lily)},
66 made from two cons cells:
67
68 @example
69 @group
70 --------------- ---------------
71 | car | cdr | | car | cdr |
72 | tulip | o---------->| lily | nil |
73 | | | | | |
74 --------------- ---------------
75 @end group
76 @end example
77
78 Each pair of boxes represents a cons cell. Each box ``refers to'',
79 ``points to'' or ``contains'' a Lisp object. (These terms are
80 synonymous.) The first box, which is the @sc{car} of the first cons
81 cell, contains the symbol @code{tulip}. The arrow from the @sc{cdr} of
82 the first cons cell to the second cons cell indicates that the @sc{cdr}
83 of the first cons cell points to the second cons cell.
84
85 The same list can be illustrated in a different sort of box notation
86 like this:
87
88 @example
89 @group
90 ___ ___ ___ ___
91 |___|___|--> |___|___|--> nil
92 | |
93 | |
94 --> tulip --> lily
95 @end group
96 @end example
97
98 Here is a more complex illustration, showing the three-element list,
99 @code{((pine needles) oak maple)}, the first element of which is a
100 two-element list:
101
102 @example
103 @group
104 ___ ___ ___ ___ ___ ___
105 |___|___|--> |___|___|--> |___|___|--> nil
106 | | |
107 | | |
108 | --> oak --> maple
109 |
110 | ___ ___ ___ ___
111 --> |___|___|--> |___|___|--> nil
112 | |
113 | |
114 --> pine --> needles
115 @end group
116 @end example
117
118 The same list represented in the first box notation looks like this:
119
120 @example
121 @group
122 -------------- -------------- --------------
123 | car | cdr | | car | cdr | | car | cdr |
124 | o | o------->| oak | o------->| maple | nil |
125 | | | | | | | | | |
126 -- | --------- -------------- --------------
127 |
128 |
129 | -------------- ----------------
130 | | car | cdr | | car | cdr |
131 ------>| pine | o------->| needles | nil |
132 | | | | | |
133 -------------- ----------------
134 @end group
135 @end example
136
137 @xref{List Type}, for the read and print syntax of lists, and for more
138 ``box and arrow'' illustrations of lists.
139
140 @node List-related Predicates
141 @section Predicates on Lists
142
143 The following predicates test whether a Lisp object is an atom, is a
144 cons cell or is a list, or whether it is the distinguished object
145 @code{nil}. (Many of these predicates can be defined in terms of the
146 others, but they are used so often that it is worth having all of them.)
147
148 @defun consp object
149 This function returns @code{t} if @var{object} is a cons cell, @code{nil}
150 otherwise. @code{nil} is not a cons cell, although it @emph{is} a list.
151 @end defun
152
153 @defun atom object
154 @cindex atoms
155 This function returns @code{t} if @var{object} is an atom, @code{nil}
156 otherwise. All objects except cons cells are atoms. The symbol
157 @code{nil} is an atom and is also a list; it is the only Lisp object
158 which is both.
159
160 @example
161 (atom @var{object}) @equiv{} (not (consp @var{object}))
162 @end example
163 @end defun
164
165 @defun listp object
166 This function returns @code{t} if @var{object} is a cons cell or
167 @code{nil}. Otherwise, it returns @code{nil}.
168
169 @example
170 @group
171 (listp '(1))
172 @result{} t
173 @end group
174 @group
175 (listp '())
176 @result{} t
177 @end group
178 @end example
179 @end defun
180
181 @defun nlistp object
182 This function is the opposite of @code{listp}: it returns @code{t} if
183 @var{object} is not a list. Otherwise, it returns @code{nil}.
184
185 @example
186 (listp @var{object}) @equiv{} (not (nlistp @var{object}))
187 @end example
188 @end defun
189
190 @defun null object
191 This function returns @code{t} if @var{object} is @code{nil}, and
192 returns @code{nil} otherwise. This function is identical to @code{not},
193 but as a matter of clarity we use @code{null} when @var{object} is
194 considered a list and @code{not} when it is considered a truth value
195 (see @code{not} in @ref{Combining Conditions}).
196
197 @example
198 @group
199 (null '(1))
200 @result{} nil
201 @end group
202 @group
203 (null '())
204 @result{} t
205 @end group
206 @end example
207 @end defun
208
209 @need 1000
210
211 @node List Elements
212 @section Accessing Elements of Lists
213 @cindex list elements
214
215 @defun car cons-cell
216 This function returns the value pointed to by the first pointer of the
217 cons cell @var{cons-cell}. Expressed another way, this function
218 returns the @sc{car} of @var{cons-cell}.
219
220 As a special case, if @var{cons-cell} is @code{nil}, then @code{car}
221 is defined to return @code{nil}; therefore, any list is a valid argument
222 for @code{car}. An error is signaled if the argument is not a cons cell
223 or @code{nil}.
224
225 @example
226 @group
227 (car '(a b c))
228 @result{} a
229 @end group
230 @group
231 (car '())
232 @result{} nil
233 @end group
234 @end example
235 @end defun
236
237 @defun cdr cons-cell
238 This function returns the value pointed to by the second pointer of
239 the cons cell @var{cons-cell}. Expressed another way, this function
240 returns the @sc{cdr} of @var{cons-cell}.
241
242 As a special case, if @var{cons-cell} is @code{nil}, then @code{cdr}
243 is defined to return @code{nil}; therefore, any list is a valid argument
244 for @code{cdr}. An error is signaled if the argument is not a cons cell
245 or @code{nil}.
246
247 @example
248 @group
249 (cdr '(a b c))
250 @result{} (b c)
251 @end group
252 @group
253 (cdr '())
254 @result{} nil
255 @end group
256 @end example
257 @end defun
258
259 @defun car-safe object
260 This function lets you take the @sc{car} of a cons cell while avoiding
261 errors for other data types. It returns the @sc{car} of @var{object} if
262 @var{object} is a cons cell, @code{nil} otherwise. This is in contrast
263 to @code{car}, which signals an error if @var{object} is not a list.
264
265 @example
266 @group
267 (car-safe @var{object})
268 @equiv{}
269 (let ((x @var{object}))
270 (if (consp x)
271 (car x)
272 nil))
273 @end group
274 @end example
275 @end defun
276
277 @defun cdr-safe object
278 This function lets you take the @sc{cdr} of a cons cell while
279 avoiding errors for other data types. It returns the @sc{cdr} of
280 @var{object} if @var{object} is a cons cell, @code{nil} otherwise.
281 This is in contrast to @code{cdr}, which signals an error if
282 @var{object} is not a list.
283
284 @example
285 @group
286 (cdr-safe @var{object})
287 @equiv{}
288 (let ((x @var{object}))
289 (if (consp x)
290 (cdr x)
291 nil))
292 @end group
293 @end example
294 @end defun
295
296 @defun nth n list
297 This function returns the @var{n}th element of @var{list}. Elements
298 are numbered starting with zero, so the @sc{car} of @var{list} is
299 element number zero. If the length of @var{list} is @var{n} or less,
300 the value is @code{nil}.
301
302 If @var{n} is negative, @code{nth} returns the first element of
303 @var{list}.
304
305 @example
306 @group
307 (nth 2 '(1 2 3 4))
308 @result{} 3
309 @end group
310 @group
311 (nth 10 '(1 2 3 4))
312 @result{} nil
313 @end group
314 @group
315 (nth -3 '(1 2 3 4))
316 @result{} 1
317
318 (nth n x) @equiv{} (car (nthcdr n x))
319 @end group
320 @end example
321 @end defun
322
323 @defun nthcdr n list
324 This function returns the @var{n}th @sc{cdr} of @var{list}. In other
325 words, it removes the first @var{n} links of @var{list} and returns
326 what follows.
327
328 If @var{n} is zero or negative, @code{nthcdr} returns all of
329 @var{list}. If the length of @var{list} is @var{n} or less,
330 @code{nthcdr} returns @code{nil}.
331
332 @example
333 @group
334 (nthcdr 1 '(1 2 3 4))
335 @result{} (2 3 4)
336 @end group
337 @group
338 (nthcdr 10 '(1 2 3 4))
339 @result{} nil
340 @end group
341 @group
342 (nthcdr -3 '(1 2 3 4))
343 @result{} (1 2 3 4)
344 @end group
345 @end example
346 @end defun
347
348 @node Building Lists
349 @comment node-name, next, previous, up
350 @section Building Cons Cells and Lists
351 @cindex cons cells
352 @cindex building lists
353
354 Many functions build lists, as lists reside at the very heart of Lisp.
355 @code{cons} is the fundamental list-building function; however, it is
356 interesting to note that @code{list} is used more times in the source
357 code for Emacs than @code{cons}.
358
359 @defun cons object1 object2
360 This function is the fundamental function used to build new list
361 structure. It creates a new cons cell, making @var{object1} the
362 @sc{car}, and @var{object2} the @sc{cdr}. It then returns the new cons
363 cell. The arguments @var{object1} and @var{object2} may be any Lisp
364 objects, but most often @var{object2} is a list.
365
366 @example
367 @group
368 (cons 1 '(2))
369 @result{} (1 2)
370 @end group
371 @group
372 (cons 1 '())
373 @result{} (1)
374 @end group
375 @group
376 (cons 1 2)
377 @result{} (1 . 2)
378 @end group
379 @end example
380
381 @cindex consing
382 @code{cons} is often used to add a single element to the front of a
383 list. This is called @dfn{consing the element onto the list}. For
384 example:
385
386 @example
387 (setq list (cons newelt list))
388 @end example
389
390 Note that there is no conflict between the variable named @code{list}
391 used in this example and the function named @code{list} described below;
392 any symbol can serve both purposes.
393 @end defun
394
395 @defun list &rest objects
396 This function creates a list with @var{objects} as its elements. The
397 resulting list is always @code{nil}-terminated. If no @var{objects}
398 are given, the empty list is returned.
399
400 @example
401 @group
402 (list 1 2 3 4 5)
403 @result{} (1 2 3 4 5)
404 @end group
405 @group
406 (list 1 2 '(3 4 5) 'foo)
407 @result{} (1 2 (3 4 5) foo)
408 @end group
409 @group
410 (list)
411 @result{} nil
412 @end group
413 @end example
414 @end defun
415
416 @defun make-list length object
417 This function creates a list of length @var{length}, in which all the
418 elements have the identical value @var{object}. Compare
419 @code{make-list} with @code{make-string} (@pxref{Creating Strings}).
420
421 @example
422 @group
423 (make-list 3 'pigs)
424 @result{} (pigs pigs pigs)
425 @end group
426 @group
427 (make-list 0 'pigs)
428 @result{} nil
429 @end group
430 @end example
431 @end defun
432
433 @defun append &rest sequences
434 @cindex copying lists
435 This function returns a list containing all the elements of
436 @var{sequences}. The @var{sequences} may be lists, vectors, or strings.
437 All arguments except the last one are copied, so none of them are
438 altered.
439
440 The final argument to @code{append} may be any object but it is
441 typically a list. The final argument is not copied or converted; it
442 becomes part of the structure of the new list.
443
444 Here is an example:
445
446 @example
447 @group
448 (setq trees '(pine oak))
449 @result{} (pine oak)
450 (setq more-trees (append '(maple birch) trees))
451 @result{} (maple birch pine oak)
452 @end group
453
454 @group
455 trees
456 @result{} (pine oak)
457 more-trees
458 @result{} (maple birch pine oak)
459 @end group
460 @group
461 (eq trees (cdr (cdr more-trees)))
462 @result{} t
463 @end group
464 @end example
465
466 You can see what happens by looking at a box diagram. The variable
467 @code{trees} is set to the list @code{(pine oak)} and then the variable
468 @code{more-trees} is set to the list @code{(maple birch pine oak)}.
469 However, the variable @code{trees} continues to refer to the original
470 list:
471
472 @smallexample
473 @group
474 more-trees trees
475 | |
476 | ___ ___ ___ ___ -> ___ ___ ___ ___
477 --> |___|___|--> |___|___|--> |___|___|--> |___|___|--> nil
478 | | | |
479 | | | |
480 --> maple -->birch --> pine --> oak
481 @end group
482 @end smallexample
483
484 An empty sequence contributes nothing to the value returned by
485 @code{append}. As a consequence of this, a final @code{nil} argument
486 forces a copy of the previous argument.
487
488 @example
489 @group
490 trees
491 @result{} (pine oak)
492 @end group
493 @group
494 (setq wood (append trees ()))
495 @result{} (pine oak)
496 @end group
497 @group
498 wood
499 @result{} (pine oak)
500 @end group
501 @group
502 (eq wood trees)
503 @result{} nil
504 @end group
505 @end example
506
507 @noindent
508 This once was the usual way to copy a list, before the function
509 @code{copy-sequence} was invented. @xref{Sequences Arrays Vectors}.
510
511 With the help of @code{apply}, we can append all the lists in a list of
512 lists:
513
514 @example
515 @group
516 (apply 'append '((a b c) nil (x y z) nil))
517 @result{} (a b c x y z)
518 @end group
519 @end example
520
521 If no @var{sequences} are given, @code{nil} is returned:
522
523 @example
524 @group
525 (append)
526 @result{} nil
527 @end group
528 @end example
529
530 See @code{nconc} in @ref{Rearrangement}, for a way to join lists with no
531 copying.
532
533 Integers are also allowed as arguments to @code{append}. They are
534 converted to strings of digits making up the decimal print
535 representation of the integer, and these strings are then appended.
536 Here's what happens:
537
538 @example
539 @group
540 (setq trees '(pine oak))
541 @result{} (pine oak)
542 @end group
543 @group
544 (char-to-string 54)
545 @result{} "6"
546 @end group
547 @group
548 (setq longer-list (append trees 6 '(spruce)))
549 @result{} (pine oak 54 spruce)
550 @end group
551 @group
552 (setq x-list (append trees 6 6))
553 @result{} (pine oak 54 . 6)
554 @end group
555 @end example
556
557 This special case exists for compatibility with Mocklisp, and we don't
558 recommend you take advantage of it. If you want to convert an integer
559 in this way, use @code{format} (@pxref{Formatting Strings}) or
560 @code{number-to-string} (@pxref{String Conversion}).
561 @end defun
562
563 @defun reverse list
564 This function creates a new list whose elements are the elements of
565 @var{list}, but in reverse order. The original argument @var{list} is
566 @emph{not} altered.
567
568 @example
569 @group
570 (setq x '(1 2 3 4))
571 @result{} (1 2 3 4)
572 @end group
573 @group
574 (reverse x)
575 @result{} (4 3 2 1)
576 x
577 @result{} (1 2 3 4)
578 @end group
579 @end example
580 @end defun
581
582 @node Modifying Lists
583 @section Modifying Existing List Structure
584
585 You can modify the @sc{car} and @sc{cdr} contents of a cons cell with the
586 primitives @code{setcar} and @code{setcdr}.
587
588 @cindex CL note---@code{rplaca} vrs @code{setcar}
589 @quotation
590 @findex rplaca
591 @findex rplacd
592 @b{Common Lisp note:} Common Lisp uses functions @code{rplaca} and
593 @code{rplacd} to alter list structure; they change structure the same
594 way as @code{setcar} and @code{setcdr}, but the Common Lisp functions
595 return the cons cell while @code{setcar} and @code{setcdr} return the
596 new @sc{car} or @sc{cdr}.
597 @end quotation
598
599 @menu
600 * Setcar:: Replacing an element in a list.
601 * Setcdr:: Replacing part of the list backbone.
602 This can be used to remove or add elements.
603 * Rearrangement:: Reordering the elements in a list; combining lists.
604 @end menu
605
606 @node Setcar
607 @subsection Altering List Elements with @code{setcar}
608
609 Changing the @sc{car} of a cons cell is done with @code{setcar}, which
610 replaces one element of a list with a different element.
611
612 @defun setcar cons object
613 This function stores @var{object} as the new @sc{car} of @var{cons},
614 replacing its previous @sc{car}. It returns the value @var{object}.
615 For example:
616
617 @example
618 @group
619 (setq x '(1 2))
620 @result{} (1 2)
621 @end group
622 @group
623 (setcar x 4)
624 @result{} 4
625 @end group
626 @group
627 x
628 @result{} (4 2)
629 @end group
630 @end example
631 @end defun
632
633 When a cons cell is part of the shared structure of several lists,
634 storing a new @sc{car} into the cons changes one element of each of
635 these lists. Here is an example:
636
637 @example
638 @group
639 ;; @r{Create two lists that are partly shared.}
640 (setq x1 '(a b c))
641 @result{} (a b c)
642 (setq x2 (cons 'z (cdr x1)))
643 @result{} (z b c)
644 @end group
645
646 @group
647 ;; @r{Replace the @sc{car} of a shared link.}
648 (setcar (cdr x1) 'foo)
649 @result{} foo
650 x1 ; @r{Both lists are changed.}
651 @result{} (a foo c)
652 x2
653 @result{} (z foo c)
654 @end group
655
656 @group
657 ;; @r{Replace the @sc{car} of a link that is not shared.}
658 (setcar x1 'baz)
659 @result{} baz
660 x1 ; @r{Only one list is changed.}
661 @result{} (baz foo c)
662 x2
663 @result{} (z foo c)
664 @end group
665 @end example
666
667 Here is a graphical depiction of the shared structure of the two lists
668 in the variables @code{x1} and @code{x2}, showing why replacing @code{b}
669 changes them both:
670
671 @example
672 @group
673 ___ ___ ___ ___ ___ ___
674 x1---> |___|___|----> |___|___|--> |___|___|--> nil
675 | --> | |
676 | | | |
677 --> a | --> b --> c
678 |
679 ___ ___ |
680 x2--> |___|___|--
681 |
682 |
683 --> z
684 @end group
685 @end example
686
687 Here is an alternative form of box diagram, showing the same relationship:
688
689 @example
690 @group
691 x1:
692 -------------- -------------- --------------
693 | car | cdr | | car | cdr | | car | cdr |
694 | a | o------->| b | o------->| c | nil |
695 | | | -->| | | | | |
696 -------------- | -------------- --------------
697 |
698 x2: |
699 -------------- |
700 | car | cdr | |
701 | z | o----
702 | | |
703 --------------
704 @end group
705 @end example
706
707 @node Setcdr
708 @subsection Altering the CDR of a List
709
710 The lowest-level primitive for modifying a @sc{cdr} is @code{setcdr}:
711
712 @defun setcdr cons object
713 This function stores @var{object} into the @sc{cdr} of @var{cons}. The
714 value returned is @var{object}, not @var{cons}.
715 @end defun
716
717 Here is an example of replacing the @sc{cdr} of a list with a
718 different list. All but the first element of the list are removed in
719 favor of a different sequence of elements. The first element is
720 unchanged, because it resides in the @sc{car} of the list, and is not
721 reached via the @sc{cdr}.
722
723 @example
724 @group
725 (setq x '(1 2 3))
726 @result{} (1 2 3)
727 @end group
728 @group
729 (setcdr x '(4))
730 @result{} (4)
731 @end group
732 @group
733 x
734 @result{} (1 4)
735 @end group
736 @end example
737
738 You can delete elements from the middle of a list by altering the
739 @sc{cdr}s of the cons cells in the list. For example, here we delete
740 the second element, @code{b}, from the list @code{(a b c)}, by changing
741 the @sc{cdr} of the first cell:
742
743 @example
744 @group
745 (setq x1 '(a b c))
746 @result{} (a b c)
747 (setcdr x1 (cdr (cdr x1)))
748 @result{} (c)
749 x1
750 @result{} (a c)
751 @end group
752 @end example
753
754 Here is the result in box notation:
755
756 @example
757 @group
758 --------------------
759 | |
760 -------------- | -------------- | --------------
761 | car | cdr | | | car | cdr | -->| car | cdr |
762 | a | o----- | b | o-------->| c | nil |
763 | | | | | | | | |
764 -------------- -------------- --------------
765 @end group
766 @end example
767
768 @noindent
769 The second cons cell, which previously held the element @code{b}, still
770 exists and its @sc{car} is still @code{b}, but it no longer forms part
771 of this list.
772
773 It is equally easy to insert a new element by changing @sc{cdr}s:
774
775 @example
776 @group
777 (setq x1 '(a b c))
778 @result{} (a b c)
779 (setcdr x1 (cons 'd (cdr x1)))
780 @result{} (d b c)
781 x1
782 @result{} (a d b c)
783 @end group
784 @end example
785
786 Here is this result in box notation:
787
788 @smallexample
789 @group
790 -------------- ------------- -------------
791 | car | cdr | | car | cdr | | car | cdr |
792 | a | o | -->| b | o------->| c | nil |
793 | | | | | | | | | | |
794 --------- | -- | ------------- -------------
795 | |
796 ----- --------
797 | |
798 | --------------- |
799 | | car | cdr | |
800 -->| d | o------
801 | | |
802 ---------------
803 @end group
804 @end smallexample
805
806 @node Rearrangement
807 @subsection Functions that Rearrange Lists
808 @cindex rearrangement of lists
809 @cindex modification of lists
810
811 Here are some functions that rearrange lists ``destructively'' by
812 modifying the @sc{cdr}s of their component cons cells. We call these
813 functions ``destructive'' because they chew up the original lists passed
814 to them as arguments, to produce a new list that is the returned value.
815
816 @defun nconc &rest lists
817 @cindex concatenating lists
818 @cindex joining lists
819 This function returns a list containing all the elements of @var{lists}.
820 Unlike @code{append} (@pxref{Building Lists}), the @var{lists} are
821 @emph{not} copied. Instead, the last @sc{cdr} of each of the
822 @var{lists} is changed to refer to the following list. The last of the
823 @var{lists} is not altered. For example:
824
825 @example
826 @group
827 (setq x '(1 2 3))
828 @result{} (1 2 3)
829 @end group
830 @group
831 (nconc x '(4 5))
832 @result{} (1 2 3 4 5)
833 @end group
834 @group
835 x
836 @result{} (1 2 3 4 5)
837 @end group
838 @end example
839
840 Since the last argument of @code{nconc} is not itself modified, it is
841 reasonable to use a constant list, such as @code{'(4 5)}, as in the
842 above example. For the same reason, the last argument need not be a
843 list:
844
845 @example
846 @group
847 (setq x '(1 2 3))
848 @result{} (1 2 3)
849 @end group
850 @group
851 (nconc x 'z)
852 @result{} (1 2 3 . z)
853 @end group
854 @group
855 x
856 @result{} (1 2 3 . z)
857 @end group
858 @end example
859
860 A common pitfall is to use a quoted constant list as a non-last
861 argument to @code{nconc}. If you do this, your program will change
862 each time you run it! Here is what happens:
863
864 @smallexample
865 @group
866 (defun add-foo (x) ; @r{We want this function to add}
867 (nconc '(foo) x)) ; @r{@code{foo} to the front of its arg.}
868 @end group
869
870 @group
871 (symbol-function 'add-foo)
872 @result{} (lambda (x) (nconc (quote (foo)) x))
873 @end group
874
875 @group
876 (setq xx (add-foo '(1 2))) ; @r{It seems to work.}
877 @result{} (foo 1 2)
878 @end group
879 @group
880 (setq xy (add-foo '(3 4))) ; @r{What happened?}
881 @result{} (foo 1 2 3 4)
882 @end group
883 @group
884 (eq xx xy)
885 @result{} t
886 @end group
887
888 @group
889 (symbol-function 'add-foo)
890 @result{} (lambda (x) (nconc (quote (foo 1 2 3 4) x)))
891 @end group
892 @end smallexample
893 @end defun
894
895 @defun nreverse list
896 @cindex reversing a list
897 This function reverses the order of the elements of @var{list}.
898 Unlike @code{reverse}, @code{nreverse} alters its argument destructively
899 by reversing the @sc{cdr}s in the cons cells forming the list. The cons
900 cell which used to be the last one in @var{list} becomes the first cell
901 of the value.
902
903 For example:
904
905 @example
906 @group
907 (setq x '(1 2 3 4))
908 @result{} (1 2 3 4)
909 @end group
910 @group
911 x
912 @result{} (1 2 3 4)
913 (nreverse x)
914 @result{} (4 3 2 1)
915 @end group
916 @group
917 ;; @r{The cell that was first is now last.}
918 x
919 @result{} (1)
920 @end group
921 @end example
922
923 To avoid confusion, we usually store the result of @code{nreverse}
924 back in the same variable which held the original list:
925
926 @example
927 (setq x (nreverse x))
928 @end example
929
930 Here is the @code{nreverse} of our favorite example, @code{(a b c)},
931 presented graphically:
932
933 @smallexample
934 @group
935 @r{Original list head:} @r{Reversed list:}
936 ------------- ------------- ------------
937 | car | cdr | | car | cdr | | car | cdr |
938 | a | nil |<-- | b | o |<-- | c | o |
939 | | | | | | | | | | | | |
940 ------------- | --------- | - | -------- | -
941 | | | |
942 ------------- ------------
943 @end group
944 @end smallexample
945 @end defun
946
947 @defun sort list predicate
948 @cindex stable sort
949 @cindex sorting lists
950 This function sorts @var{list} stably, though destructively, and
951 returns the sorted list. It compares elements using @var{predicate}. A
952 stable sort is one in which elements with equal sort keys maintain their
953 relative order before and after the sort. Stability is important when
954 successive sorts are used to order elements according to different
955 criteria.
956
957 The argument @var{predicate} must be a function that accepts two
958 arguments. It is called with two elements of @var{list}. To get an
959 increasing order sort, the @var{predicate} should return @code{t} if the
960 first element is ``less than'' the second, or @code{nil} if not.
961
962 The destructive aspect of @code{sort} is that it rearranges the cons
963 cells forming @var{list} by changing @sc{cdr}s. A nondestructive sort
964 function would create new cons cells to store the elements in their
965 sorted order. If you wish to make a sorted copy without destroying the
966 original, copy it first with @code{copy-sequence} and then sort.
967
968 Sorting does not change the @sc{car}s of the cons cells in @var{list};
969 the cons cell that originally contained the element @code{a} in
970 @var{list} still has @code{a} in its @sc{car} after sorting, but it now
971 appears in a different position in the list due to the change of
972 @sc{cdr}s. For example:
973
974 @example
975 @group
976 (setq nums '(1 3 2 6 5 4 0))
977 @result{} (1 3 2 6 5 4 0)
978 @end group
979 @group
980 (sort nums '<)
981 @result{} (0 1 2 3 4 5 6)
982 @end group
983 @group
984 nums
985 @result{} (1 2 3 4 5 6)
986 @end group
987 @end example
988
989 @noindent
990 Note that the list in @code{nums} no longer contains 0; this is the same
991 cons cell that it was before, but it is no longer the first one in the
992 list. Don't assume a variable that formerly held the argument now holds
993 the entire sorted list! Instead, save the result of @code{sort} and use
994 that. Most often we store the result back into the variable that held
995 the original list:
996
997 @example
998 (setq nums (sort nums '<))
999 @end example
1000
1001 @xref{Sorting}, for more functions that perform sorting.
1002 See @code{documentation} in @ref{Accessing Documentation}, for a
1003 useful example of @code{sort}.
1004 @end defun
1005
1006 @ifinfo
1007 See @code{delq}, in @ref{Sets And Lists}, for another function
1008 that modifies cons cells.
1009 @end ifinfo
1010 @iftex
1011 The function @code{delq} in the following section is another example
1012 of destructive list manipulation.
1013 @end iftex
1014
1015 @node Sets And Lists
1016 @section Using Lists as Sets
1017 @cindex lists as sets
1018 @cindex sets
1019
1020 A list can represent an unordered mathematical set---simply consider a
1021 value an element of a set if it appears in the list, and ignore the
1022 order of the list. To form the union of two sets, use @code{append} (as
1023 long as you don't mind having duplicate elements). Other useful
1024 functions for sets include @code{memq} and @code{delq}, and their
1025 @code{equal} versions, @code{member} and @code{delete}.
1026
1027 @cindex CL note---lack @code{union}, @code{set}
1028 @quotation
1029 @b{Common Lisp note:} Common Lisp has functions @code{union} (which
1030 avoids duplicate elements) and @code{intersection} for set operations,
1031 but GNU Emacs Lisp does not have them. You can write them in Lisp if
1032 you wish.
1033 @end quotation
1034
1035 @defun memq object list
1036 @cindex membership in a list
1037 This function tests to see whether @var{object} is a member of
1038 @var{list}. If it is, @code{memq} returns a list starting with the
1039 first occurrence of @var{object}. Otherwise, it returns @code{nil}.
1040 The letter @samp{q} in @code{memq} says that it uses @code{eq} to
1041 compare @var{object} against the elements of the list. For example:
1042
1043 @example
1044 @group
1045 (memq 2 '(1 2 3 2 1))
1046 @result{} (2 3 2 1)
1047 @end group
1048 @group
1049 (memq '(2) '((1) (2))) ; @r{@code{(2)} and @code{(2)} are not @code{eq}.}
1050 @result{} nil
1051 @end group
1052 @end example
1053 @end defun
1054
1055 @defun delq object list
1056 @cindex deletion of elements
1057 This function destructively removes all elements @code{eq} to
1058 @var{object} from @var{list}. The letter @samp{q} in @code{delq} says
1059 that it uses @code{eq} to compare @var{object} against the elements of
1060 the list, like @code{memq}.
1061 @end defun
1062
1063 When @code{delq} deletes elements from the front of the list, it does so
1064 simply by advancing down the list and returning a sublist that starts
1065 after those elements:
1066
1067 @example
1068 @group
1069 (delq 'a '(a b c)) @equiv{} (cdr '(a b c))
1070 @end group
1071 @end example
1072
1073 When an element to be deleted appears in the middle of the list,
1074 removing it involves changing the @sc{cdr}s (@pxref{Setcdr}).
1075
1076 @example
1077 @group
1078 (setq sample-list '(1 2 3 (4)))
1079 @result{} (1 2 3 (4))
1080 @end group
1081 @group
1082 (delq 1 sample-list)
1083 @result{} (2 3 (4))
1084 @end group
1085 @group
1086 sample-list
1087 @result{} (1 2 3 (4))
1088 @end group
1089 @group
1090 (delq 2 sample-list)
1091 @result{} (1 3 (4))
1092 @end group
1093 @group
1094 sample-list
1095 @result{} (1 3 (4))
1096 @end group
1097 @end example
1098
1099 Note that @code{(delq 2 sample-list)} modifies @code{sample-list} to
1100 splice out the second element, but @code{(delq 1 sample-list)} does not
1101 splice anything---it just returns a shorter list. Don't assume that a
1102 variable which formerly held the argument @var{list} now has fewer
1103 elements, or that it still holds the original list! Instead, save the
1104 result of @code{delq} and use that. Most often we store the result back
1105 into the variable that held the original list:
1106
1107 @example
1108 (setq flowers (delq 'rose flowers))
1109 @end example
1110
1111 In the following example, the @code{(4)} that @code{delq} attempts to match
1112 and the @code{(4)} in the @code{sample-list} are not @code{eq}:
1113
1114 @example
1115 @group
1116 (delq '(4) sample-list)
1117 @result{} (1 3 (4))
1118 @end group
1119 @end example
1120
1121 The following two functions are like @code{memq} and @code{delq} but use
1122 @code{equal} rather than @code{eq} to compare elements. They are new in
1123 Emacs 19.
1124
1125 @defun member object list
1126 The function @code{member} tests to see whether @var{object} is a member
1127 of @var{list}, comparing members with @var{object} using @code{equal}.
1128 If @var{object} is a member, @code{member} returns a list starting with
1129 its first occurrence in @var{list}. Otherwise, it returns @code{nil}.
1130
1131 Compare this with @code{memq}:
1132
1133 @example
1134 @group
1135 (member '(2) '((1) (2))) ; @r{@code{(2)} and @code{(2)} are @code{equal}.}
1136 @result{} ((2))
1137 @end group
1138 @group
1139 (memq '(2) '((1) (2))) ; @r{@code{(2)} and @code{(2)} are not @code{eq}.}
1140 @result{} nil
1141 @end group
1142 @group
1143 ;; @r{Two strings with the same contents are @code{equal}.}
1144 (member "foo" '("foo" "bar"))
1145 @result{} ("foo" "bar")
1146 @end group
1147 @end example
1148 @end defun
1149
1150 @defun delete object list
1151 This function destructively removes all elements @code{equal} to
1152 @var{object} from @var{list}. It is to @code{delq} as @code{member} is
1153 to @code{memq}: it uses @code{equal} to compare elements with
1154 @var{object}, like @code{member}; when it finds an element that matches,
1155 it removes the element just as @code{delq} would. For example:
1156
1157 @example
1158 @group
1159 (delete '(2) '((2) (1) (2)))
1160 @result{} '((1))
1161 @end group
1162 @end example
1163 @end defun
1164
1165 @quotation
1166 @b{Common Lisp note:} The functions @code{member} and @code{delete} in
1167 GNU Emacs Lisp are derived from Maclisp, not Common Lisp. The Common
1168 Lisp versions do not use @code{equal} to compare elements.
1169 @end quotation
1170
1171 @node Association Lists
1172 @section Association Lists
1173 @cindex association list
1174 @cindex alist
1175
1176 An @dfn{association list}, or @dfn{alist} for short, records a mapping
1177 from keys to values. It is a list of cons cells called
1178 @dfn{associations}: the @sc{car} of each cell is the @dfn{key}, and the
1179 @sc{cdr} is the @dfn{associated value}.@footnote{This usage of ``key''
1180 is not related to the term ``key sequence''; it means a value used to
1181 look up an item in a table. In this case, the table is the alist, and
1182 the alist associations are the items.}
1183
1184 Here is an example of an alist. The key @code{pine} is associated with
1185 the value @code{cones}; the key @code{oak} is associated with
1186 @code{acorns}; and the key @code{maple} is associated with @code{seeds}.
1187
1188 @example
1189 @group
1190 '((pine . cones)
1191 (oak . acorns)
1192 (maple . seeds))
1193 @end group
1194 @end example
1195
1196 The associated values in an alist may be any Lisp objects; so may the
1197 keys. For example, in the following alist, the symbol @code{a} is
1198 associated with the number @code{1}, and the string @code{"b"} is
1199 associated with the @emph{list} @code{(2 3)}, which is the @sc{cdr} of
1200 the alist element:
1201
1202 @example
1203 ((a . 1) ("b" 2 3))
1204 @end example
1205
1206 Sometimes it is better to design an alist to store the associated
1207 value in the @sc{car} of the @sc{cdr} of the element. Here is an
1208 example:
1209
1210 @example
1211 '((rose red) (lily white) (buttercup yellow))
1212 @end example
1213
1214 @noindent
1215 Here we regard @code{red} as the value associated with @code{rose}. One
1216 advantage of this method is that you can store other related
1217 information---even a list of other items---in the @sc{cdr} of the
1218 @sc{cdr}. One disadvantage is that you cannot use @code{rassq} (see
1219 below) to find the element containing a given value. When neither of
1220 these considerations is important, the choice is a matter of taste, as
1221 long as you are consistent about it for any given alist.
1222
1223 Note that the same alist shown above could be regarded as having the
1224 associated value in the @sc{cdr} of the element; the value associated
1225 with @code{rose} would be the list @code{(red)}.
1226
1227 Association lists are often used to record information that you might
1228 otherwise keep on a stack, since new associations may be added easily to
1229 the front of the list. When searching an association list for an
1230 association with a given key, the first one found is returned, if there
1231 is more than one.
1232
1233 In Emacs Lisp, it is @emph{not} an error if an element of an
1234 association list is not a cons cell. The alist search functions simply
1235 ignore such elements. Many other versions of Lisp signal errors in such
1236 cases.
1237
1238 Note that property lists are similar to association lists in several
1239 respects. A property list behaves like an association list in which
1240 each key can occur only once. @xref{Property Lists}, for a comparison
1241 of property lists and association lists.
1242
1243 @defun assoc key alist
1244 This function returns the first association for @var{key} in
1245 @var{alist}. It compares @var{key} against the alist elements using
1246 @code{equal} (@pxref{Equality Predicates}). It returns @code{nil} if no
1247 association in @var{alist} has a @sc{car} @code{equal} to @var{key}.
1248 For example:
1249
1250 @smallexample
1251 (setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
1252 @result{} ((pine . cones) (oak . acorns) (maple . seeds))
1253 (assoc 'oak trees)
1254 @result{} (oak . acorns)
1255 (cdr (assoc 'oak trees))
1256 @result{} acorns
1257 (assoc 'birch trees)
1258 @result{} nil
1259 @end smallexample
1260
1261 Here is another example in which the keys and values are not symbols:
1262
1263 @smallexample
1264 (setq needles-per-cluster
1265 '((2 "Austrian Pine" "Red Pine")
1266 (3 "Pitch Pine")
1267 (5 "White Pine")))
1268
1269 (cdr (assoc 3 needles-per-cluster))
1270 @result{} ("Pitch Pine")
1271 (cdr (assoc 2 needles-per-cluster))
1272 @result{} ("Austrian Pine" "Red Pine")
1273 @end smallexample
1274 @end defun
1275
1276 @defun assq key alist
1277 This function is like @code{assoc} in that it returns the first
1278 association for @var{key} in @var{alist}, but it makes the comparison
1279 using @code{eq} instead of @code{equal}. @code{assq} returns @code{nil}
1280 if no association in @var{alist} has a @sc{car} @code{eq} to @var{key}.
1281 This function is used more often than @code{assoc}, since @code{eq} is
1282 faster than @code{equal} and most alists use symbols as keys.
1283 @xref{Equality Predicates}.
1284
1285 @smallexample
1286 (setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
1287 @result{} ((pine . cones) (oak . acorns) (maple . seeds))
1288 (assq 'pine trees)
1289 @result{} (pine . cones)
1290 @end smallexample
1291
1292 On the other hand, @code{assq} is not usually useful in alists where the
1293 keys may not be symbols:
1294
1295 @smallexample
1296 (setq leaves
1297 '(("simple leaves" . oak)
1298 ("compound leaves" . horsechestnut)))
1299
1300 (assq "simple leaves" leaves)
1301 @result{} nil
1302 (assoc "simple leaves" leaves)
1303 @result{} ("simple leaves" . oak)
1304 @end smallexample
1305 @end defun
1306
1307 @defun rassq value alist
1308 This function returns the first association with value @var{value} in
1309 @var{alist}. It returns @code{nil} if no association in @var{alist} has
1310 a @sc{cdr} @code{eq} to @var{value}.
1311
1312 @code{rassq} is like @code{assq} except that it compares the @sc{cdr} of
1313 each @var{alist} association instead of the @sc{car}. You can think of
1314 this as ``reverse @code{assq}'', finding the key for a given value.
1315
1316 For example:
1317
1318 @smallexample
1319 (setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
1320
1321 (rassq 'acorns trees)
1322 @result{} (oak . acorns)
1323 (rassq 'spores trees)
1324 @result{} nil
1325 @end smallexample
1326
1327 Note that @code{rassq} cannot search for a value stored in the @sc{car}
1328 of the @sc{cdr} of an element:
1329
1330 @smallexample
1331 (setq colors '((rose red) (lily white) (buttercup yellow)))
1332
1333 (rassq 'white colors)
1334 @result{} nil
1335 @end smallexample
1336
1337 In this case, the @sc{cdr} of the association @code{(lily white)} is not
1338 the symbol @code{white}, but rather the list @code{(white)}. This
1339 becomes clearer if the association is written in dotted pair notation:
1340
1341 @smallexample
1342 (lily white) @equiv{} (lily . (white))
1343 @end smallexample
1344 @end defun
1345
1346 @defun copy-alist alist
1347 @cindex copying alists
1348 This function returns a two-level deep copy of @var{alist}: it creates a
1349 new copy of each association, so that you can alter the associations of
1350 the new alist without changing the old one.
1351
1352 @smallexample
1353 @group
1354 (setq needles-per-cluster
1355 '((2 . ("Austrian Pine" "Red Pine"))
1356 (3 . "Pitch Pine")
1357 (5 . "White Pine")))
1358 @result{}
1359 ((2 "Austrian Pine" "Red Pine")
1360 (3 . "Pitch Pine")
1361 (5 . "White Pine"))
1362
1363 (setq copy (copy-alist needles-per-cluster))
1364 @result{}
1365 ((2 "Austrian Pine" "Red Pine")
1366 (3 . "Pitch Pine")
1367 (5 . "White Pine"))
1368
1369 (eq needles-per-cluster copy)
1370 @result{} nil
1371 (equal needles-per-cluster copy)
1372 @result{} t
1373 (eq (car needles-per-cluster) (car copy))
1374 @result{} nil
1375 (cdr (car (cdr needles-per-cluster)))
1376 @result{} "Pitch Pine"
1377 (eq (cdr (car (cdr needles-per-cluster)))
1378 (cdr (car (cdr copy))))
1379 @result{} t
1380 @end group
1381 @end smallexample
1382 @end defun
1383
1384