* doc/lispref/tips.texi (Coding Conventions): Recommend cl-lib over cl.
[bpt/emacs.git] / doc / lispref / lists.texi
CommitLineData
b8d4c8d0
GM
1@c -*-texinfo-*-
2@c This is part of the GNU Emacs Lisp Reference Manual.
1e103a7c 3@c Copyright (C) 1990-1995, 1998-1999, 2001-2012 Free Software Foundation, Inc.
b8d4c8d0 4@c See the file elisp.texi for copying conditions.
ecc6530d 5@node Lists
b8d4c8d0
GM
6@chapter Lists
7@cindex lists
8@cindex element (of list)
9
10 A @dfn{list} represents a sequence of zero or more elements (which may
11be any Lisp objects). The important difference between lists and
12vectors is that two or more lists can share part of their structure; in
13addition, you can insert or delete elements in a list without copying
14the whole list.
15
16@menu
17* Cons Cells:: How lists are made out of cons cells.
18* List-related Predicates:: Is this object a list? Comparing two lists.
19* List Elements:: Extracting the pieces of a list.
20* Building Lists:: Creating list structure.
21* List Variables:: Modifying lists stored in variables.
22* Modifying Lists:: Storing new pieces into an existing list.
23* Sets And Lists:: A list can represent a finite mathematical set.
24* Association Lists:: A list can represent a finite relation or mapping.
b8d4c8d0
GM
25@end menu
26
27@node Cons Cells
28@section Lists and Cons Cells
29@cindex lists and cons cells
30
31 Lists in Lisp are not a primitive data type; they are built up from
31cbea1d
CY
32@dfn{cons cells} (@pxref{Cons Cell Type}). A cons cell is a data
33object that represents an ordered pair. That is, it has two slots,
34and each slot @dfn{holds}, or @dfn{refers to}, some Lisp object. One
35slot is known as the @sc{car}, and the other is known as the @sc{cdr}.
36(These names are traditional; see @ref{Cons Cell Type}.) @sc{cdr} is
16152b76 37pronounced ``could-er''.
b8d4c8d0
GM
38
39 We say that ``the @sc{car} of this cons cell is'' whatever object
40its @sc{car} slot currently holds, and likewise for the @sc{cdr}.
41
16152b76 42 A list is a series of cons cells ``chained together'', so that each
31cbea1d
CY
43cell refers to the next one. There is one cons cell for each element
44of the list. By convention, the @sc{car}s of the cons cells hold the
45elements of the list, and the @sc{cdr}s are used to chain the list
46(this asymmetry between @sc{car} and @sc{cdr} is entirely a matter of
47convention; at the level of cons cells, the @sc{car} and @sc{cdr}
48slots have similar properties). Hence, the @sc{cdr} slot of each cons
49cell in a list refers to the following cons cell.
b8d4c8d0
GM
50
51@cindex true list
31cbea1d
CY
52 Also by convention, the @sc{cdr} of the last cons cell in a list is
53@code{nil}. We call such a @code{nil}-terminated structure a
54@dfn{true list}. In Emacs Lisp, the symbol @code{nil} is both a
55symbol and a list with no elements. For convenience, the symbol
b8d4c8d0 56@code{nil} is considered to have @code{nil} as its @sc{cdr} (and also
31cbea1d
CY
57as its @sc{car}).
58
59 Hence, the @sc{cdr} of a true list is always a true list. The
60@sc{cdr} of a nonempty true list is a true list containing all the
61elements except the first.
b8d4c8d0
GM
62
63@cindex dotted list
64@cindex circular list
31cbea1d
CY
65 If the @sc{cdr} of a list's last cons cell is some value other than
66@code{nil}, we call the structure a @dfn{dotted list}, since its
67printed representation would use dotted pair notation (@pxref{Dotted
68Pair Notation}). There is one other possibility: some cons cell's
69@sc{cdr} could point to one of the previous cons cells in the list.
70We call that structure a @dfn{circular list}.
b8d4c8d0
GM
71
72 For some purposes, it does not matter whether a list is true,
31cbea1d 73circular or dotted. If a program doesn't look far enough down the
b8d4c8d0
GM
74list to see the @sc{cdr} of the final cons cell, it won't care.
75However, some functions that operate on lists demand true lists and
76signal errors if given a dotted list. Most functions that try to find
77the end of a list enter infinite loops if given a circular list.
78
79@cindex list structure
31cbea1d
CY
80 Because most cons cells are used as part of lists, we refer to any
81structure made out of cons cells as a @dfn{list structure}.
b8d4c8d0
GM
82
83@node List-related Predicates
84@section Predicates on Lists
85
86 The following predicates test whether a Lisp object is an atom,
87whether it is a cons cell or is a list, or whether it is the
88distinguished object @code{nil}. (Many of these predicates can be
89defined in terms of the others, but they are used so often that it is
eceeb5fc 90worth having them.)
b8d4c8d0
GM
91
92@defun consp object
93This function returns @code{t} if @var{object} is a cons cell, @code{nil}
94otherwise. @code{nil} is not a cons cell, although it @emph{is} a list.
95@end defun
96
97@defun atom object
98This function returns @code{t} if @var{object} is an atom, @code{nil}
99otherwise. All objects except cons cells are atoms. The symbol
100@code{nil} is an atom and is also a list; it is the only Lisp object
101that is both.
102
103@example
104(atom @var{object}) @equiv{} (not (consp @var{object}))
105@end example
106@end defun
107
108@defun listp object
109This function returns @code{t} if @var{object} is a cons cell or
110@code{nil}. Otherwise, it returns @code{nil}.
111
112@example
113@group
114(listp '(1))
115 @result{} t
116@end group
117@group
118(listp '())
119 @result{} t
120@end group
121@end example
122@end defun
123
124@defun nlistp object
125This function is the opposite of @code{listp}: it returns @code{t} if
126@var{object} is not a list. Otherwise, it returns @code{nil}.
127
128@example
129(listp @var{object}) @equiv{} (not (nlistp @var{object}))
130@end example
131@end defun
132
133@defun null object
134This function returns @code{t} if @var{object} is @code{nil}, and
135returns @code{nil} otherwise. This function is identical to @code{not},
136but as a matter of clarity we use @code{null} when @var{object} is
137considered a list and @code{not} when it is considered a truth value
138(see @code{not} in @ref{Combining Conditions}).
139
140@example
141@group
142(null '(1))
143 @result{} nil
144@end group
145@group
146(null '())
147 @result{} t
148@end group
149@end example
150@end defun
151
152
153@node List Elements
154@section Accessing Elements of Lists
155@cindex list elements
156
157@defun car cons-cell
158This function returns the value referred to by the first slot of the
b6a5263f
CY
159cons cell @var{cons-cell}. In other words, it returns the @sc{car} of
160@var{cons-cell}.
b8d4c8d0 161
b6a5263f
CY
162As a special case, if @var{cons-cell} is @code{nil}, this function
163returns @code{nil}. Therefore, any list is a valid argument. An
164error is signaled if the argument is not a cons cell or @code{nil}.
b8d4c8d0
GM
165
166@example
167@group
168(car '(a b c))
169 @result{} a
170@end group
171@group
172(car '())
173 @result{} nil
174@end group
175@end example
176@end defun
177
178@defun cdr cons-cell
b6a5263f
CY
179This function returns the value referred to by the second slot of the
180cons cell @var{cons-cell}. In other words, it returns the @sc{cdr} of
181@var{cons-cell}.
182
183As a special case, if @var{cons-cell} is @code{nil}, this function
184returns @code{nil}; therefore, any list is a valid argument. An error
185is signaled if the argument is not a cons cell or @code{nil}.
b8d4c8d0
GM
186
187@example
188@group
189(cdr '(a b c))
190 @result{} (b c)
191@end group
192@group
193(cdr '())
194 @result{} nil
195@end group
196@end example
197@end defun
198
199@defun car-safe object
200This function lets you take the @sc{car} of a cons cell while avoiding
201errors for other data types. It returns the @sc{car} of @var{object} if
202@var{object} is a cons cell, @code{nil} otherwise. This is in contrast
203to @code{car}, which signals an error if @var{object} is not a list.
204
205@example
206@group
207(car-safe @var{object})
208@equiv{}
209(let ((x @var{object}))
210 (if (consp x)
211 (car x)
212 nil))
213@end group
214@end example
215@end defun
216
217@defun cdr-safe object
218This function lets you take the @sc{cdr} of a cons cell while
219avoiding errors for other data types. It returns the @sc{cdr} of
220@var{object} if @var{object} is a cons cell, @code{nil} otherwise.
221This is in contrast to @code{cdr}, which signals an error if
222@var{object} is not a list.
223
224@example
225@group
226(cdr-safe @var{object})
227@equiv{}
228(let ((x @var{object}))
229 (if (consp x)
230 (cdr x)
231 nil))
232@end group
233@end example
234@end defun
235
236@defmac pop listname
237This macro is a way of examining the @sc{car} of a list,
238and taking it off the list, all at once.
239
240It operates on the list which is stored in the symbol @var{listname}.
241It removes this element from the list by setting @var{listname}
242to the @sc{cdr} of its old value---but it also returns the @sc{car}
243of that list, which is the element being removed.
244
245@example
246x
247 @result{} (a b c)
248(pop x)
249 @result{} a
250x
251 @result{} (b c)
252@end example
31cbea1d
CY
253
254@noindent
255For the @code{pop} macro, which removes an element from a list,
256@xref{List Variables}.
b8d4c8d0
GM
257@end defmac
258
259@defun nth n list
260@anchor{Definition of nth}
261This function returns the @var{n}th element of @var{list}. Elements
262are numbered starting with zero, so the @sc{car} of @var{list} is
263element number zero. If the length of @var{list} is @var{n} or less,
264the value is @code{nil}.
265
266If @var{n} is negative, @code{nth} returns the first element of
267@var{list}.
268
269@example
270@group
271(nth 2 '(1 2 3 4))
272 @result{} 3
273@end group
274@group
275(nth 10 '(1 2 3 4))
276 @result{} nil
277@end group
278@group
279(nth -3 '(1 2 3 4))
280 @result{} 1
281
282(nth n x) @equiv{} (car (nthcdr n x))
283@end group
284@end example
285
286The function @code{elt} is similar, but applies to any kind of sequence.
287For historical reasons, it takes its arguments in the opposite order.
288@xref{Sequence Functions}.
289@end defun
290
291@defun nthcdr n list
292This function returns the @var{n}th @sc{cdr} of @var{list}. In other
293words, it skips past the first @var{n} links of @var{list} and returns
294what follows.
295
296If @var{n} is zero or negative, @code{nthcdr} returns all of
297@var{list}. If the length of @var{list} is @var{n} or less,
298@code{nthcdr} returns @code{nil}.
299
300@example
301@group
302(nthcdr 1 '(1 2 3 4))
303 @result{} (2 3 4)
304@end group
305@group
306(nthcdr 10 '(1 2 3 4))
307 @result{} nil
308@end group
309@group
310(nthcdr -3 '(1 2 3 4))
311 @result{} (1 2 3 4)
312@end group
313@end example
314@end defun
315
316@defun last list &optional n
317This function returns the last link of @var{list}. The @code{car} of
318this link is the list's last element. If @var{list} is null,
319@code{nil} is returned. If @var{n} is non-@code{nil}, the
320@var{n}th-to-last link is returned instead, or the whole of @var{list}
321if @var{n} is bigger than @var{list}'s length.
322@end defun
323
324@defun safe-length list
325@anchor{Definition of safe-length}
326This function returns the length of @var{list}, with no risk of either
327an error or an infinite loop. It generally returns the number of
328distinct cons cells in the list. However, for circular lists,
329the value is just an upper bound; it is often too large.
330
331If @var{list} is not @code{nil} or a cons cell, @code{safe-length}
332returns 0.
333@end defun
334
335 The most common way to compute the length of a list, when you are not
336worried that it may be circular, is with @code{length}. @xref{Sequence
337Functions}.
338
339@defun caar cons-cell
340This is the same as @code{(car (car @var{cons-cell}))}.
341@end defun
342
343@defun cadr cons-cell
344This is the same as @code{(car (cdr @var{cons-cell}))}
345or @code{(nth 1 @var{cons-cell})}.
346@end defun
347
348@defun cdar cons-cell
349This is the same as @code{(cdr (car @var{cons-cell}))}.
350@end defun
351
352@defun cddr cons-cell
353This is the same as @code{(cdr (cdr @var{cons-cell}))}
354or @code{(nthcdr 2 @var{cons-cell})}.
355@end defun
356
357@defun butlast x &optional n
358This function returns the list @var{x} with the last element,
359or the last @var{n} elements, removed. If @var{n} is greater
360than zero it makes a copy of the list so as not to damage the
361original list. In general, @code{(append (butlast @var{x} @var{n})
362(last @var{x} @var{n}))} will return a list equal to @var{x}.
363@end defun
364
365@defun nbutlast x &optional n
366This is a version of @code{butlast} that works by destructively
367modifying the @code{cdr} of the appropriate element, rather than
368making a copy of the list.
369@end defun
370
371@node Building Lists
b8d4c8d0
GM
372@section Building Cons Cells and Lists
373@cindex cons cells
374@cindex building lists
375
376 Many functions build lists, as lists reside at the very heart of Lisp.
377@code{cons} is the fundamental list-building function; however, it is
378interesting to note that @code{list} is used more times in the source
379code for Emacs than @code{cons}.
380
381@defun cons object1 object2
382This function is the most basic function for building new list
383structure. It creates a new cons cell, making @var{object1} the
384@sc{car}, and @var{object2} the @sc{cdr}. It then returns the new
385cons cell. The arguments @var{object1} and @var{object2} may be any
386Lisp objects, but most often @var{object2} is a list.
387
388@example
389@group
390(cons 1 '(2))
391 @result{} (1 2)
392@end group
393@group
394(cons 1 '())
395 @result{} (1)
396@end group
397@group
398(cons 1 2)
399 @result{} (1 . 2)
400@end group
401@end example
402
403@cindex consing
404@code{cons} is often used to add a single element to the front of a
405list. This is called @dfn{consing the element onto the list}.
406@footnote{There is no strictly equivalent way to add an element to
407the end of a list. You can use @code{(append @var{listname} (list
408@var{newelt}))}, which creates a whole new list by copying @var{listname}
409and adding @var{newelt} to its end. Or you can use @code{(nconc
410@var{listname} (list @var{newelt}))}, which modifies @var{listname}
411by following all the @sc{cdr}s and then replacing the terminating
412@code{nil}. Compare this to adding an element to the beginning of a
413list with @code{cons}, which neither copies nor modifies the list.}
414For example:
415
416@example
417(setq list (cons newelt list))
418@end example
419
420Note that there is no conflict between the variable named @code{list}
421used in this example and the function named @code{list} described below;
422any symbol can serve both purposes.
423@end defun
424
425@defun list &rest objects
426This function creates a list with @var{objects} as its elements. The
427resulting list is always @code{nil}-terminated. If no @var{objects}
428are given, the empty list is returned.
429
430@example
431@group
432(list 1 2 3 4 5)
433 @result{} (1 2 3 4 5)
434@end group
435@group
436(list 1 2 '(3 4 5) 'foo)
437 @result{} (1 2 (3 4 5) foo)
438@end group
439@group
440(list)
441 @result{} nil
442@end group
443@end example
444@end defun
445
446@defun make-list length object
447This function creates a list of @var{length} elements, in which each
448element is @var{object}. Compare @code{make-list} with
449@code{make-string} (@pxref{Creating Strings}).
450
451@example
452@group
453(make-list 3 'pigs)
454 @result{} (pigs pigs pigs)
455@end group
456@group
457(make-list 0 'pigs)
458 @result{} nil
459@end group
460@group
1f403cb9 461(setq l (make-list 3 '(a b)))
b8d4c8d0
GM
462 @result{} ((a b) (a b) (a b))
463(eq (car l) (cadr l))
464 @result{} t
465@end group
466@end example
467@end defun
468
469@defun append &rest sequences
470@cindex copying lists
471This function returns a list containing all the elements of
472@var{sequences}. The @var{sequences} may be lists, vectors,
473bool-vectors, or strings, but the last one should usually be a list.
474All arguments except the last one are copied, so none of the arguments
475is altered. (See @code{nconc} in @ref{Rearrangement}, for a way to join
476lists with no copying.)
477
478More generally, the final argument to @code{append} may be any Lisp
479object. The final argument is not copied or converted; it becomes the
480@sc{cdr} of the last cons cell in the new list. If the final argument
481is itself a list, then its elements become in effect elements of the
482result list. If the final element is not a list, the result is a
483dotted list since its final @sc{cdr} is not @code{nil} as required
484in a true list.
b8d4c8d0
GM
485@end defun
486
487 Here is an example of using @code{append}:
488
489@example
490@group
491(setq trees '(pine oak))
492 @result{} (pine oak)
493(setq more-trees (append '(maple birch) trees))
494 @result{} (maple birch pine oak)
495@end group
496
497@group
498trees
499 @result{} (pine oak)
500more-trees
501 @result{} (maple birch pine oak)
502@end group
503@group
504(eq trees (cdr (cdr more-trees)))
505 @result{} t
506@end group
507@end example
508
509 You can see how @code{append} works by looking at a box diagram. The
510variable @code{trees} is set to the list @code{(pine oak)} and then the
511variable @code{more-trees} is set to the list @code{(maple birch pine
512oak)}. However, the variable @code{trees} continues to refer to the
513original list:
514
515@smallexample
516@group
517more-trees trees
518| |
519| --- --- --- --- -> --- --- --- ---
520 --> | | |--> | | |--> | | |--> | | |--> nil
521 --- --- --- --- --- --- --- ---
522 | | | |
523 | | | |
524 --> maple -->birch --> pine --> oak
525@end group
526@end smallexample
527
528 An empty sequence contributes nothing to the value returned by
529@code{append}. As a consequence of this, a final @code{nil} argument
530forces a copy of the previous argument:
531
532@example
533@group
534trees
535 @result{} (pine oak)
536@end group
537@group
538(setq wood (append trees nil))
539 @result{} (pine oak)
540@end group
541@group
542wood
543 @result{} (pine oak)
544@end group
545@group
546(eq wood trees)
547 @result{} nil
548@end group
549@end example
550
551@noindent
552This once was the usual way to copy a list, before the function
553@code{copy-sequence} was invented. @xref{Sequences Arrays Vectors}.
554
555 Here we show the use of vectors and strings as arguments to @code{append}:
556
557@example
558@group
559(append [a b] "cd" nil)
560 @result{} (a b 99 100)
561@end group
562@end example
563
564 With the help of @code{apply} (@pxref{Calling Functions}), we can append
565all the lists in a list of lists:
566
567@example
568@group
569(apply 'append '((a b c) nil (x y z) nil))
570 @result{} (a b c x y z)
571@end group
572@end example
573
574 If no @var{sequences} are given, @code{nil} is returned:
575
576@example
577@group
578(append)
579 @result{} nil
580@end group
581@end example
582
583 Here are some examples where the final argument is not a list:
584
585@example
586(append '(x y) 'z)
587 @result{} (x y . z)
588(append '(x y) [z])
589 @result{} (x y . [z])
590@end example
591
592@noindent
593The second example shows that when the final argument is a sequence but
594not a list, the sequence's elements do not become elements of the
595resulting list. Instead, the sequence becomes the final @sc{cdr}, like
596any other non-list final argument.
597
598@defun reverse list
599This function creates a new list whose elements are the elements of
600@var{list}, but in reverse order. The original argument @var{list} is
601@emph{not} altered.
602
603@example
604@group
605(setq x '(1 2 3 4))
606 @result{} (1 2 3 4)
607@end group
608@group
609(reverse x)
610 @result{} (4 3 2 1)
611x
612 @result{} (1 2 3 4)
613@end group
614@end example
615@end defun
616
617@defun copy-tree tree &optional vecp
618This function returns a copy of the tree @code{tree}. If @var{tree} is a
619cons cell, this makes a new cons cell with the same @sc{car} and
620@sc{cdr}, then recursively copies the @sc{car} and @sc{cdr} in the
621same way.
622
623Normally, when @var{tree} is anything other than a cons cell,
624@code{copy-tree} simply returns @var{tree}. However, if @var{vecp} is
625non-@code{nil}, it copies vectors too (and operates recursively on
626their elements).
627@end defun
628
629@defun number-sequence from &optional to separation
630This returns a list of numbers starting with @var{from} and
631incrementing by @var{separation}, and ending at or just before
632@var{to}. @var{separation} can be positive or negative and defaults
633to 1. If @var{to} is @code{nil} or numerically equal to @var{from},
634the value is the one-element list @code{(@var{from})}. If @var{to} is
635less than @var{from} with a positive @var{separation}, or greater than
636@var{from} with a negative @var{separation}, the value is @code{nil}
637because those arguments specify an empty sequence.
638
639If @var{separation} is 0 and @var{to} is neither @code{nil} nor
640numerically equal to @var{from}, @code{number-sequence} signals an
641error, since those arguments specify an infinite sequence.
642
643All arguments can be integers or floating point numbers. However,
644floating point arguments can be tricky, because floating point
645arithmetic is inexact. For instance, depending on the machine, it may
646quite well happen that @code{(number-sequence 0.4 0.6 0.2)} returns
647the one element list @code{(0.4)}, whereas
648@code{(number-sequence 0.4 0.8 0.2)} returns a list with three
649elements. The @var{n}th element of the list is computed by the exact
650formula @code{(+ @var{from} (* @var{n} @var{separation}))}. Thus, if
651one wants to make sure that @var{to} is included in the list, one can
652pass an expression of this exact type for @var{to}. Alternatively,
653one can replace @var{to} with a slightly larger value (or a slightly
654more negative value if @var{separation} is negative).
655
656Some examples:
657
658@example
659(number-sequence 4 9)
660 @result{} (4 5 6 7 8 9)
661(number-sequence 9 4 -1)
662 @result{} (9 8 7 6 5 4)
663(number-sequence 9 4 -2)
664 @result{} (9 7 5)
665(number-sequence 8)
666 @result{} (8)
667(number-sequence 8 5)
668 @result{} nil
669(number-sequence 5 8 -1)
670 @result{} nil
671(number-sequence 1.5 6 2)
672 @result{} (1.5 3.5 5.5)
673@end example
674@end defun
675
676@node List Variables
677@section Modifying List Variables
678
679 These functions, and one macro, provide convenient ways
680to modify a list which is stored in a variable.
681
682@defmac push newelt listname
683This macro provides an alternative way to write
684@code{(setq @var{listname} (cons @var{newelt} @var{listname}))}.
685
686@example
687(setq l '(a b))
688 @result{} (a b)
689(push 'c l)
690 @result{} (c a b)
691l
692 @result{} (c a b)
693@end example
31cbea1d
CY
694
695@noindent
696For the @code{pop} macro, which removes the first element from a list,
697@xref{List Elements}.
b8d4c8d0
GM
698@end defmac
699
700 Two functions modify lists that are the values of variables.
701
702@defun add-to-list symbol element &optional append compare-fn
703This function sets the variable @var{symbol} by consing @var{element}
704onto the old value, if @var{element} is not already a member of that
705value. It returns the resulting list, whether updated or not. The
706value of @var{symbol} had better be a list already before the call.
707@code{add-to-list} uses @var{compare-fn} to compare @var{element}
708against existing list members; if @var{compare-fn} is @code{nil}, it
709uses @code{equal}.
710
711Normally, if @var{element} is added, it is added to the front of
712@var{symbol}, but if the optional argument @var{append} is
713non-@code{nil}, it is added at the end.
714
715The argument @var{symbol} is not implicitly quoted; @code{add-to-list}
716is an ordinary function, like @code{set} and unlike @code{setq}. Quote
717the argument yourself if that is what you want.
718@end defun
719
720Here's a scenario showing how to use @code{add-to-list}:
721
722@example
723(setq foo '(a b))
724 @result{} (a b)
725
726(add-to-list 'foo 'c) ;; @r{Add @code{c}.}
727 @result{} (c a b)
728
729(add-to-list 'foo 'b) ;; @r{No effect.}
730 @result{} (c a b)
731
732foo ;; @r{@code{foo} was changed.}
733 @result{} (c a b)
734@end example
735
736 An equivalent expression for @code{(add-to-list '@var{var}
737@var{value})} is this:
738
739@example
740(or (member @var{value} @var{var})
741 (setq @var{var} (cons @var{value} @var{var})))
742@end example
743
744@defun add-to-ordered-list symbol element &optional order
745This function sets the variable @var{symbol} by inserting
746@var{element} into the old value, which must be a list, at the
747position specified by @var{order}. If @var{element} is already a
748member of the list, its position in the list is adjusted according
749to @var{order}. Membership is tested using @code{eq}.
750This function returns the resulting list, whether updated or not.
751
752The @var{order} is typically a number (integer or float), and the
753elements of the list are sorted in non-decreasing numerical order.
754
755@var{order} may also be omitted or @code{nil}. Then the numeric order
756of @var{element} stays unchanged if it already has one; otherwise,
757@var{element} has no numeric order. Elements without a numeric list
758order are placed at the end of the list, in no particular order.
759
760Any other value for @var{order} removes the numeric order of @var{element}
761if it already has one; otherwise, it is equivalent to @code{nil}.
762
763The argument @var{symbol} is not implicitly quoted;
764@code{add-to-ordered-list} is an ordinary function, like @code{set}
eceeb5fc 765and unlike @code{setq}. Quote the argument yourself if necessary.
b8d4c8d0
GM
766
767The ordering information is stored in a hash table on @var{symbol}'s
768@code{list-order} property.
769@end defun
770
771Here's a scenario showing how to use @code{add-to-ordered-list}:
772
773@example
774(setq foo '())
775 @result{} nil
776
777(add-to-ordered-list 'foo 'a 1) ;; @r{Add @code{a}.}
778 @result{} (a)
779
780(add-to-ordered-list 'foo 'c 3) ;; @r{Add @code{c}.}
781 @result{} (a c)
782
783(add-to-ordered-list 'foo 'b 2) ;; @r{Add @code{b}.}
784 @result{} (a b c)
785
786(add-to-ordered-list 'foo 'b 4) ;; @r{Move @code{b}.}
787 @result{} (a c b)
788
789(add-to-ordered-list 'foo 'd) ;; @r{Append @code{d}.}
790 @result{} (a c b d)
791
792(add-to-ordered-list 'foo 'e) ;; @r{Add @code{e}}.
793 @result{} (a c b e d)
794
795foo ;; @r{@code{foo} was changed.}
796 @result{} (a c b e d)
797@end example
798
799@node Modifying Lists
800@section Modifying Existing List Structure
801@cindex destructive list operations
802
803 You can modify the @sc{car} and @sc{cdr} contents of a cons cell with the
804primitives @code{setcar} and @code{setcdr}. We call these ``destructive''
805operations because they change existing list structure.
806
807@cindex CL note---@code{rplaca} vs @code{setcar}
808@quotation
809@findex rplaca
810@findex rplacd
811@b{Common Lisp note:} Common Lisp uses functions @code{rplaca} and
812@code{rplacd} to alter list structure; they change structure the same
813way as @code{setcar} and @code{setcdr}, but the Common Lisp functions
814return the cons cell while @code{setcar} and @code{setcdr} return the
815new @sc{car} or @sc{cdr}.
816@end quotation
817
818@menu
819* Setcar:: Replacing an element in a list.
820* Setcdr:: Replacing part of the list backbone.
821 This can be used to remove or add elements.
822* Rearrangement:: Reordering the elements in a list; combining lists.
823@end menu
824
825@node Setcar
826@subsection Altering List Elements with @code{setcar}
827
828 Changing the @sc{car} of a cons cell is done with @code{setcar}. When
829used on a list, @code{setcar} replaces one element of a list with a
830different element.
831
832@defun setcar cons object
833This function stores @var{object} as the new @sc{car} of @var{cons},
834replacing its previous @sc{car}. In other words, it changes the
835@sc{car} slot of @var{cons} to refer to @var{object}. It returns the
836value @var{object}. For example:
837
838@example
839@group
840(setq x '(1 2))
841 @result{} (1 2)
842@end group
843@group
844(setcar x 4)
845 @result{} 4
846@end group
847@group
848x
849 @result{} (4 2)
850@end group
851@end example
852@end defun
853
854 When a cons cell is part of the shared structure of several lists,
855storing a new @sc{car} into the cons changes one element of each of
856these lists. Here is an example:
857
858@example
859@group
860;; @r{Create two lists that are partly shared.}
861(setq x1 '(a b c))
862 @result{} (a b c)
863(setq x2 (cons 'z (cdr x1)))
864 @result{} (z b c)
865@end group
866
867@group
868;; @r{Replace the @sc{car} of a shared link.}
869(setcar (cdr x1) 'foo)
870 @result{} foo
871x1 ; @r{Both lists are changed.}
872 @result{} (a foo c)
873x2
874 @result{} (z foo c)
875@end group
876
877@group
878;; @r{Replace the @sc{car} of a link that is not shared.}
879(setcar x1 'baz)
880 @result{} baz
881x1 ; @r{Only one list is changed.}
882 @result{} (baz foo c)
883x2
884 @result{} (z foo c)
885@end group
886@end example
887
888 Here is a graphical depiction of the shared structure of the two lists
889in the variables @code{x1} and @code{x2}, showing why replacing @code{b}
890changes them both:
891
892@example
893@group
894 --- --- --- --- --- ---
895x1---> | | |----> | | |--> | | |--> nil
896 --- --- --- --- --- ---
897 | --> | |
898 | | | |
899 --> a | --> b --> c
900 |
901 --- --- |
902x2--> | | |--
903 --- ---
904 |
905 |
906 --> z
907@end group
908@end example
909
910 Here is an alternative form of box diagram, showing the same relationship:
911
912@example
913@group
914x1:
915 -------------- -------------- --------------
916| car | cdr | | car | cdr | | car | cdr |
917| a | o------->| b | o------->| c | nil |
918| | | -->| | | | | |
919 -------------- | -------------- --------------
920 |
921x2: |
922 -------------- |
923| car | cdr | |
924| z | o----
925| | |
926 --------------
927@end group
928@end example
929
930@node Setcdr
931@subsection Altering the CDR of a List
932
933 The lowest-level primitive for modifying a @sc{cdr} is @code{setcdr}:
934
935@defun setcdr cons object
936This function stores @var{object} as the new @sc{cdr} of @var{cons},
937replacing its previous @sc{cdr}. In other words, it changes the
938@sc{cdr} slot of @var{cons} to refer to @var{object}. It returns the
939value @var{object}.
940@end defun
941
942 Here is an example of replacing the @sc{cdr} of a list with a
943different list. All but the first element of the list are removed in
944favor of a different sequence of elements. The first element is
945unchanged, because it resides in the @sc{car} of the list, and is not
946reached via the @sc{cdr}.
947
948@example
949@group
950(setq x '(1 2 3))
951 @result{} (1 2 3)
952@end group
953@group
954(setcdr x '(4))
955 @result{} (4)
956@end group
957@group
958x
959 @result{} (1 4)
960@end group
961@end example
962
963 You can delete elements from the middle of a list by altering the
964@sc{cdr}s of the cons cells in the list. For example, here we delete
965the second element, @code{b}, from the list @code{(a b c)}, by changing
966the @sc{cdr} of the first cons cell:
967
968@example
969@group
970(setq x1 '(a b c))
971 @result{} (a b c)
972(setcdr x1 (cdr (cdr x1)))
973 @result{} (c)
974x1
975 @result{} (a c)
976@end group
977@end example
978
979 Here is the result in box notation:
980
981@smallexample
982@group
983 --------------------
984 | |
985 -------------- | -------------- | --------------
986| car | cdr | | | car | cdr | -->| car | cdr |
987| a | o----- | b | o-------->| c | nil |
988| | | | | | | | |
989 -------------- -------------- --------------
990@end group
991@end smallexample
992
993@noindent
994The second cons cell, which previously held the element @code{b}, still
995exists and its @sc{car} is still @code{b}, but it no longer forms part
996of this list.
997
998 It is equally easy to insert a new element by changing @sc{cdr}s:
999
1000@example
1001@group
1002(setq x1 '(a b c))
1003 @result{} (a b c)
1004(setcdr x1 (cons 'd (cdr x1)))
1005 @result{} (d b c)
1006x1
1007 @result{} (a d b c)
1008@end group
1009@end example
1010
1011 Here is this result in box notation:
1012
1013@smallexample
1014@group
1015 -------------- ------------- -------------
1016| car | cdr | | car | cdr | | car | cdr |
1017| a | o | -->| b | o------->| c | nil |
1018| | | | | | | | | | |
1019 --------- | -- | ------------- -------------
1020 | |
1021 ----- --------
1022 | |
1023 | --------------- |
1024 | | car | cdr | |
1025 -->| d | o------
1026 | | |
1027 ---------------
1028@end group
1029@end smallexample
1030
1031@node Rearrangement
1032@subsection Functions that Rearrange Lists
1033@cindex rearrangement of lists
1034@cindex modification of lists
1035
1036 Here are some functions that rearrange lists ``destructively'' by
1037modifying the @sc{cdr}s of their component cons cells. We call these
1038functions ``destructive'' because they chew up the original lists passed
1039to them as arguments, relinking their cons cells to form a new list that
1040is the returned value.
1041
1042@ifnottex
1043 See @code{delq}, in @ref{Sets And Lists}, for another function
1044that modifies cons cells.
1045@end ifnottex
1046@iftex
1047 The function @code{delq} in the following section is another example
1048of destructive list manipulation.
1049@end iftex
1050
1051@defun nconc &rest lists
1052@cindex concatenating lists
1053@cindex joining lists
1054This function returns a list containing all the elements of @var{lists}.
1055Unlike @code{append} (@pxref{Building Lists}), the @var{lists} are
1056@emph{not} copied. Instead, the last @sc{cdr} of each of the
1057@var{lists} is changed to refer to the following list. The last of the
1058@var{lists} is not altered. For example:
1059
1060@example
1061@group
1062(setq x '(1 2 3))
1063 @result{} (1 2 3)
1064@end group
1065@group
1066(nconc x '(4 5))
1067 @result{} (1 2 3 4 5)
1068@end group
1069@group
1070x
1071 @result{} (1 2 3 4 5)
1072@end group
1073@end example
1074
1075 Since the last argument of @code{nconc} is not itself modified, it is
1076reasonable to use a constant list, such as @code{'(4 5)}, as in the
1077above example. For the same reason, the last argument need not be a
1078list:
1079
1080@example
1081@group
1082(setq x '(1 2 3))
1083 @result{} (1 2 3)
1084@end group
1085@group
1086(nconc x 'z)
1087 @result{} (1 2 3 . z)
1088@end group
1089@group
1090x
1091 @result{} (1 2 3 . z)
1092@end group
1093@end example
1094
1095However, the other arguments (all but the last) must be lists.
1096
1097A common pitfall is to use a quoted constant list as a non-last
1098argument to @code{nconc}. If you do this, your program will change
1099each time you run it! Here is what happens:
1100
1101@smallexample
1102@group
1103(defun add-foo (x) ; @r{We want this function to add}
1104 (nconc '(foo) x)) ; @r{@code{foo} to the front of its arg.}
1105@end group
1106
1107@group
1108(symbol-function 'add-foo)
1109 @result{} (lambda (x) (nconc (quote (foo)) x))
1110@end group
1111
1112@group
1113(setq xx (add-foo '(1 2))) ; @r{It seems to work.}
1114 @result{} (foo 1 2)
1115@end group
1116@group
1117(setq xy (add-foo '(3 4))) ; @r{What happened?}
1118 @result{} (foo 1 2 3 4)
1119@end group
1120@group
1121(eq xx xy)
1122 @result{} t
1123@end group
1124
1125@group
1126(symbol-function 'add-foo)
1127 @result{} (lambda (x) (nconc (quote (foo 1 2 3 4) x)))
1128@end group
1129@end smallexample
1130@end defun
1131
1132@defun nreverse list
1133@cindex reversing a list
1134 This function reverses the order of the elements of @var{list}.
1135Unlike @code{reverse}, @code{nreverse} alters its argument by reversing
1136the @sc{cdr}s in the cons cells forming the list. The cons cell that
1137used to be the last one in @var{list} becomes the first cons cell of the
1138value.
1139
1140 For example:
1141
1142@example
1143@group
1144(setq x '(a b c))
1145 @result{} (a b c)
1146@end group
1147@group
1148x
1149 @result{} (a b c)
1150(nreverse x)
1151 @result{} (c b a)
1152@end group
1153@group
1154;; @r{The cons cell that was first is now last.}
1155x
1156 @result{} (a)
1157@end group
1158@end example
1159
1160 To avoid confusion, we usually store the result of @code{nreverse}
1161back in the same variable which held the original list:
1162
1163@example
1164(setq x (nreverse x))
1165@end example
1166
1167 Here is the @code{nreverse} of our favorite example, @code{(a b c)},
1168presented graphically:
1169
1170@smallexample
1171@group
1172@r{Original list head:} @r{Reversed list:}
1173 ------------- ------------- ------------
1174| car | cdr | | car | cdr | | car | cdr |
1175| a | nil |<-- | b | o |<-- | c | o |
1176| | | | | | | | | | | | |
1177 ------------- | --------- | - | -------- | -
1178 | | | |
1179 ------------- ------------
1180@end group
1181@end smallexample
1182@end defun
1183
1184@defun sort list predicate
1185@cindex stable sort
1186@cindex sorting lists
1187This function sorts @var{list} stably, though destructively, and
1188returns the sorted list. It compares elements using @var{predicate}. A
1189stable sort is one in which elements with equal sort keys maintain their
1190relative order before and after the sort. Stability is important when
1191successive sorts are used to order elements according to different
1192criteria.
1193
1194The argument @var{predicate} must be a function that accepts two
1195arguments. It is called with two elements of @var{list}. To get an
1196increasing order sort, the @var{predicate} should return non-@code{nil} if the
1197first element is ``less than'' the second, or @code{nil} if not.
1198
1199The comparison function @var{predicate} must give reliable results for
1200any given pair of arguments, at least within a single call to
1201@code{sort}. It must be @dfn{antisymmetric}; that is, if @var{a} is
1202less than @var{b}, @var{b} must not be less than @var{a}. It must be
1203@dfn{transitive}---that is, if @var{a} is less than @var{b}, and @var{b}
1204is less than @var{c}, then @var{a} must be less than @var{c}. If you
1205use a comparison function which does not meet these requirements, the
1206result of @code{sort} is unpredictable.
1207
1208The destructive aspect of @code{sort} is that it rearranges the cons
1209cells forming @var{list} by changing @sc{cdr}s. A nondestructive sort
1210function would create new cons cells to store the elements in their
1211sorted order. If you wish to make a sorted copy without destroying the
1212original, copy it first with @code{copy-sequence} and then sort.
1213
1214Sorting does not change the @sc{car}s of the cons cells in @var{list};
1215the cons cell that originally contained the element @code{a} in
1216@var{list} still has @code{a} in its @sc{car} after sorting, but it now
1217appears in a different position in the list due to the change of
1218@sc{cdr}s. For example:
1219
1220@example
1221@group
1222(setq nums '(1 3 2 6 5 4 0))
1223 @result{} (1 3 2 6 5 4 0)
1224@end group
1225@group
1226(sort nums '<)
1227 @result{} (0 1 2 3 4 5 6)
1228@end group
1229@group
1230nums
1231 @result{} (1 2 3 4 5 6)
1232@end group
1233@end example
1234
1235@noindent
1236@strong{Warning}: Note that the list in @code{nums} no longer contains
12370; this is the same cons cell that it was before, but it is no longer
1238the first one in the list. Don't assume a variable that formerly held
1239the argument now holds the entire sorted list! Instead, save the result
1240of @code{sort} and use that. Most often we store the result back into
1241the variable that held the original list:
1242
1243@example
1244(setq nums (sort nums '<))
1245@end example
1246
1247@xref{Sorting}, for more functions that perform sorting.
1248See @code{documentation} in @ref{Accessing Documentation}, for a
1249useful example of @code{sort}.
1250@end defun
1251
1252@node Sets And Lists
1253@section Using Lists as Sets
1254@cindex lists as sets
1255@cindex sets
1256
1257 A list can represent an unordered mathematical set---simply consider a
1258value an element of a set if it appears in the list, and ignore the
1259order of the list. To form the union of two sets, use @code{append} (as
1260long as you don't mind having duplicate elements). You can remove
1261@code{equal} duplicates using @code{delete-dups}. Other useful
1262functions for sets include @code{memq} and @code{delq}, and their
1263@code{equal} versions, @code{member} and @code{delete}.
1264
1265@cindex CL note---lack @code{union}, @code{intersection}
1266@quotation
1267@b{Common Lisp note:} Common Lisp has functions @code{union} (which
bc8410af 1268avoids duplicate elements) and @code{intersection} for set operations.
b28c06e8 1269Although standard GNU Emacs Lisp does not have them, the @file{cl}
eceeb5fc 1270library provides versions. @xref{Top,, Overview, cl, Common Lisp Extensions}.
b8d4c8d0
GM
1271@end quotation
1272
1273@defun memq object list
1274@cindex membership in a list
1275This function tests to see whether @var{object} is a member of
1276@var{list}. If it is, @code{memq} returns a list starting with the
1277first occurrence of @var{object}. Otherwise, it returns @code{nil}.
1278The letter @samp{q} in @code{memq} says that it uses @code{eq} to
1279compare @var{object} against the elements of the list. For example:
1280
1281@example
1282@group
1283(memq 'b '(a b c b a))
1284 @result{} (b c b a)
1285@end group
1286@group
1287(memq '(2) '((1) (2))) ; @r{@code{(2)} and @code{(2)} are not @code{eq}.}
1288 @result{} nil
1289@end group
1290@end example
1291@end defun
1292
1293@defun delq object list
1294@cindex deleting list elements
1295This function destructively removes all elements @code{eq} to
bb6b0efc
CY
1296@var{object} from @var{list}, and returns the resulting list. The
1297letter @samp{q} in @code{delq} says that it uses @code{eq} to compare
1298@var{object} against the elements of the list, like @code{memq} and
1299@code{remq}.
1300
1301Typically, when you invoke @code{delq}, you should use the return
1302value by assigning it to the variable which held the original list.
1303The reason for this is explained below.
b8d4c8d0
GM
1304@end defun
1305
bb6b0efc
CY
1306The @code{delq} function deletes elements from the front of the list
1307by simply advancing down the list, and returning a sublist that starts
1308after those elements. For example:
b8d4c8d0
GM
1309
1310@example
1311@group
1312(delq 'a '(a b c)) @equiv{} (cdr '(a b c))
1313@end group
1314@end example
1315
bb6b0efc 1316@noindent
b8d4c8d0
GM
1317When an element to be deleted appears in the middle of the list,
1318removing it involves changing the @sc{cdr}s (@pxref{Setcdr}).
1319
1320@example
1321@group
1322(setq sample-list '(a b c (4)))
1323 @result{} (a b c (4))
1324@end group
1325@group
1326(delq 'a sample-list)
1327 @result{} (b c (4))
1328@end group
1329@group
1330sample-list
1331 @result{} (a b c (4))
1332@end group
1333@group
1334(delq 'c sample-list)
1335 @result{} (a b (4))
1336@end group
1337@group
1338sample-list
1339 @result{} (a b (4))
1340@end group
1341@end example
1342
1343Note that @code{(delq 'c sample-list)} modifies @code{sample-list} to
1344splice out the third element, but @code{(delq 'a sample-list)} does not
1345splice anything---it just returns a shorter list. Don't assume that a
1346variable which formerly held the argument @var{list} now has fewer
1347elements, or that it still holds the original list! Instead, save the
1348result of @code{delq} and use that. Most often we store the result back
1349into the variable that held the original list:
1350
1351@example
1352(setq flowers (delq 'rose flowers))
1353@end example
1354
1355In the following example, the @code{(4)} that @code{delq} attempts to match
1356and the @code{(4)} in the @code{sample-list} are not @code{eq}:
1357
1358@example
1359@group
1360(delq '(4) sample-list)
1361 @result{} (a c (4))
1362@end group
049bcbcb 1363@end example
b8d4c8d0
GM
1364
1365If you want to delete elements that are @code{equal} to a given value,
1366use @code{delete} (see below).
b8d4c8d0
GM
1367
1368@defun remq object list
1369This function returns a copy of @var{list}, with all elements removed
1370which are @code{eq} to @var{object}. The letter @samp{q} in @code{remq}
1371says that it uses @code{eq} to compare @var{object} against the elements
1372of @code{list}.
1373
1374@example
1375@group
1376(setq sample-list '(a b c a b c))
1377 @result{} (a b c a b c)
1378@end group
1379@group
1380(remq 'a sample-list)
1381 @result{} (b c b c)
1382@end group
1383@group
1384sample-list
1385 @result{} (a b c a b c)
1386@end group
1387@end example
1388@end defun
1389
1390@defun memql object list
1391The function @code{memql} tests to see whether @var{object} is a member
1392of @var{list}, comparing members with @var{object} using @code{eql},
1393so floating point elements are compared by value.
1394If @var{object} is a member, @code{memql} returns a list starting with
1395its first occurrence in @var{list}. Otherwise, it returns @code{nil}.
1396
1397Compare this with @code{memq}:
1398
1399@example
1400@group
1401(memql 1.2 '(1.1 1.2 1.3)) ; @r{@code{1.2} and @code{1.2} are @code{eql}.}
1402 @result{} (1.2 1.3)
1403@end group
1404@group
1405(memq 1.2 '(1.1 1.2 1.3)) ; @r{@code{1.2} and @code{1.2} are not @code{eq}.}
1406 @result{} nil
1407@end group
1408@end example
1409@end defun
1410
1411The following three functions are like @code{memq}, @code{delq} and
1412@code{remq}, but use @code{equal} rather than @code{eq} to compare
1413elements. @xref{Equality Predicates}.
1414
1415@defun member object list
1416The function @code{member} tests to see whether @var{object} is a member
1417of @var{list}, comparing members with @var{object} using @code{equal}.
1418If @var{object} is a member, @code{member} returns a list starting with
1419its first occurrence in @var{list}. Otherwise, it returns @code{nil}.
1420
1421Compare this with @code{memq}:
1422
1423@example
1424@group
1425(member '(2) '((1) (2))) ; @r{@code{(2)} and @code{(2)} are @code{equal}.}
1426 @result{} ((2))
1427@end group
1428@group
1429(memq '(2) '((1) (2))) ; @r{@code{(2)} and @code{(2)} are not @code{eq}.}
1430 @result{} nil
1431@end group
1432@group
1433;; @r{Two strings with the same contents are @code{equal}.}
1434(member "foo" '("foo" "bar"))
1435 @result{} ("foo" "bar")
1436@end group
1437@end example
1438@end defun
1439
1440@defun delete object sequence
bb6b0efc
CY
1441This function removes all elements @code{equal} to @var{object} from
1442@var{sequence}, and returns the resulting sequence.
1443
1444If @var{sequence} is a list, @code{delete} is to @code{delq} as
1445@code{member} is to @code{memq}: it uses @code{equal} to compare
1446elements with @var{object}, like @code{member}; when it finds an
1447element that matches, it cuts the element out just as @code{delq}
1448would. As with @code{delq}, you should typically use the return value
1449by assigning it to the variable which held the original list.
b8d4c8d0
GM
1450
1451If @code{sequence} is a vector or string, @code{delete} returns a copy
1452of @code{sequence} with all elements @code{equal} to @code{object}
1453removed.
1454
1455For example:
1456
1457@example
1458@group
1459(setq l '((2) (1) (2)))
1460(delete '(2) l)
1461 @result{} ((1))
1462l
1463 @result{} ((2) (1))
1464;; @r{If you want to change @code{l} reliably,}
bf1af6c7 1465;; @r{write @code{(setq l (delete '(2) l))}.}
b8d4c8d0
GM
1466@end group
1467@group
1468(setq l '((2) (1) (2)))
1469(delete '(1) l)
1470 @result{} ((2) (2))
1471l
1472 @result{} ((2) (2))
1473;; @r{In this case, it makes no difference whether you set @code{l},}
1474;; @r{but you should do so for the sake of the other case.}
1475@end group
1476@group
1477(delete '(2) [(2) (1) (2)])
1478 @result{} [(1)]
1479@end group
1480@end example
1481@end defun
1482
1483@defun remove object sequence
1484This function is the non-destructive counterpart of @code{delete}. It
1485returns a copy of @code{sequence}, a list, vector, or string, with
1486elements @code{equal} to @code{object} removed. For example:
1487
1488@example
1489@group
1490(remove '(2) '((2) (1) (2)))
1491 @result{} ((1))
1492@end group
1493@group
1494(remove '(2) [(2) (1) (2)])
1495 @result{} [(1)]
1496@end group
1497@end example
1498@end defun
1499
1500@quotation
1501@b{Common Lisp note:} The functions @code{member}, @code{delete} and
1502@code{remove} in GNU Emacs Lisp are derived from Maclisp, not Common
1503Lisp. The Common Lisp versions do not use @code{equal} to compare
1504elements.
1505@end quotation
1506
1507@defun member-ignore-case object list
1508This function is like @code{member}, except that @var{object} should
1509be a string and that it ignores differences in letter-case and text
1510representation: upper-case and lower-case letters are treated as
1511equal, and unibyte strings are converted to multibyte prior to
1512comparison.
1513@end defun
1514
1515@defun delete-dups list
1516This function destructively removes all @code{equal} duplicates from
1517@var{list}, stores the result in @var{list} and returns it. Of
1518several @code{equal} occurrences of an element in @var{list},
1519@code{delete-dups} keeps the first one.
1520@end defun
1521
1522 See also the function @code{add-to-list}, in @ref{List Variables},
1523for a way to add an element to a list stored in a variable and used as a
1524set.
1525
1526@node Association Lists
1527@section Association Lists
1528@cindex association list
1529@cindex alist
1530
1531 An @dfn{association list}, or @dfn{alist} for short, records a mapping
1532from keys to values. It is a list of cons cells called
1533@dfn{associations}: the @sc{car} of each cons cell is the @dfn{key}, and the
1534@sc{cdr} is the @dfn{associated value}.@footnote{This usage of ``key''
1535is not related to the term ``key sequence''; it means a value used to
1536look up an item in a table. In this case, the table is the alist, and
1537the alist associations are the items.}
1538
1539 Here is an example of an alist. The key @code{pine} is associated with
1540the value @code{cones}; the key @code{oak} is associated with
1541@code{acorns}; and the key @code{maple} is associated with @code{seeds}.
1542
1543@example
1544@group
1545((pine . cones)
1546 (oak . acorns)
1547 (maple . seeds))
1548@end group
1549@end example
1550
1551 Both the values and the keys in an alist may be any Lisp objects.
1552For example, in the following alist, the symbol @code{a} is
1553associated with the number @code{1}, and the string @code{"b"} is
1554associated with the @emph{list} @code{(2 3)}, which is the @sc{cdr} of
1555the alist element:
1556
1557@example
1558((a . 1) ("b" 2 3))
1559@end example
1560
1561 Sometimes it is better to design an alist to store the associated
1562value in the @sc{car} of the @sc{cdr} of the element. Here is an
1563example of such an alist:
1564
1565@example
1566((rose red) (lily white) (buttercup yellow))
1567@end example
1568
1569@noindent
1570Here we regard @code{red} as the value associated with @code{rose}. One
1571advantage of this kind of alist is that you can store other related
1572information---even a list of other items---in the @sc{cdr} of the
1573@sc{cdr}. One disadvantage is that you cannot use @code{rassq} (see
1574below) to find the element containing a given value. When neither of
1575these considerations is important, the choice is a matter of taste, as
1576long as you are consistent about it for any given alist.
1577
1578 The same alist shown above could be regarded as having the
1579associated value in the @sc{cdr} of the element; the value associated
1580with @code{rose} would be the list @code{(red)}.
1581
1582 Association lists are often used to record information that you might
1583otherwise keep on a stack, since new associations may be added easily to
1584the front of the list. When searching an association list for an
1585association with a given key, the first one found is returned, if there
1586is more than one.
1587
1588 In Emacs Lisp, it is @emph{not} an error if an element of an
1589association list is not a cons cell. The alist search functions simply
1590ignore such elements. Many other versions of Lisp signal errors in such
1591cases.
1592
1593 Note that property lists are similar to association lists in several
1594respects. A property list behaves like an association list in which
1595each key can occur only once. @xref{Property Lists}, for a comparison
1596of property lists and association lists.
1597
1598@defun assoc key alist
1599This function returns the first association for @var{key} in
1600@var{alist}, comparing @var{key} against the alist elements using
1601@code{equal} (@pxref{Equality Predicates}). It returns @code{nil} if no
1602association in @var{alist} has a @sc{car} @code{equal} to @var{key}.
1603For example:
1604
1605@smallexample
1606(setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
1607 @result{} ((pine . cones) (oak . acorns) (maple . seeds))
1608(assoc 'oak trees)
1609 @result{} (oak . acorns)
1610(cdr (assoc 'oak trees))
1611 @result{} acorns
1612(assoc 'birch trees)
1613 @result{} nil
1614@end smallexample
1615
1616Here is another example, in which the keys and values are not symbols:
1617
1618@smallexample
1619(setq needles-per-cluster
1620 '((2 "Austrian Pine" "Red Pine")
1621 (3 "Pitch Pine")
1622 (5 "White Pine")))
1623
1624(cdr (assoc 3 needles-per-cluster))
1625 @result{} ("Pitch Pine")
1626(cdr (assoc 2 needles-per-cluster))
1627 @result{} ("Austrian Pine" "Red Pine")
1628@end smallexample
1629@end defun
1630
1631 The function @code{assoc-string} is much like @code{assoc} except
1632that it ignores certain differences between strings. @xref{Text
1633Comparison}.
1634
1635@defun rassoc value alist
1636This function returns the first association with value @var{value} in
1637@var{alist}. It returns @code{nil} if no association in @var{alist} has
1638a @sc{cdr} @code{equal} to @var{value}.
1639
1640@code{rassoc} is like @code{assoc} except that it compares the @sc{cdr} of
1641each @var{alist} association instead of the @sc{car}. You can think of
16152b76 1642this as ``reverse @code{assoc}'', finding the key for a given value.
b8d4c8d0
GM
1643@end defun
1644
1645@defun assq key alist
1646This function is like @code{assoc} in that it returns the first
1647association for @var{key} in @var{alist}, but it makes the comparison
1648using @code{eq} instead of @code{equal}. @code{assq} returns @code{nil}
1649if no association in @var{alist} has a @sc{car} @code{eq} to @var{key}.
1650This function is used more often than @code{assoc}, since @code{eq} is
1651faster than @code{equal} and most alists use symbols as keys.
1652@xref{Equality Predicates}.
1653
1654@smallexample
1655(setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
1656 @result{} ((pine . cones) (oak . acorns) (maple . seeds))
1657(assq 'pine trees)
1658 @result{} (pine . cones)
1659@end smallexample
1660
1661On the other hand, @code{assq} is not usually useful in alists where the
1662keys may not be symbols:
1663
1664@smallexample
1665(setq leaves
1666 '(("simple leaves" . oak)
1667 ("compound leaves" . horsechestnut)))
1668
1669(assq "simple leaves" leaves)
1670 @result{} nil
1671(assoc "simple leaves" leaves)
1672 @result{} ("simple leaves" . oak)
1673@end smallexample
1674@end defun
1675
1676@defun rassq value alist
1677This function returns the first association with value @var{value} in
1678@var{alist}. It returns @code{nil} if no association in @var{alist} has
1679a @sc{cdr} @code{eq} to @var{value}.
1680
1681@code{rassq} is like @code{assq} except that it compares the @sc{cdr} of
1682each @var{alist} association instead of the @sc{car}. You can think of
16152b76 1683this as ``reverse @code{assq}'', finding the key for a given value.
b8d4c8d0
GM
1684
1685For example:
1686
1687@smallexample
1688(setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
1689
1690(rassq 'acorns trees)
1691 @result{} (oak . acorns)
1692(rassq 'spores trees)
1693 @result{} nil
1694@end smallexample
1695
1696@code{rassq} cannot search for a value stored in the @sc{car}
1697of the @sc{cdr} of an element:
1698
1699@smallexample
1700(setq colors '((rose red) (lily white) (buttercup yellow)))
1701
1702(rassq 'white colors)
1703 @result{} nil
1704@end smallexample
1705
1706In this case, the @sc{cdr} of the association @code{(lily white)} is not
1707the symbol @code{white}, but rather the list @code{(white)}. This
1708becomes clearer if the association is written in dotted pair notation:
1709
1710@smallexample
1711(lily white) @equiv{} (lily . (white))
1712@end smallexample
1713@end defun
1714
1715@defun assoc-default key alist &optional test default
1716This function searches @var{alist} for a match for @var{key}. For each
1717element of @var{alist}, it compares the element (if it is an atom) or
1718the element's @sc{car} (if it is a cons) against @var{key}, by calling
1719@var{test} with two arguments: the element or its @sc{car}, and
1720@var{key}. The arguments are passed in that order so that you can get
1721useful results using @code{string-match} with an alist that contains
1722regular expressions (@pxref{Regexp Search}). If @var{test} is omitted
1723or @code{nil}, @code{equal} is used for comparison.
1724
1725If an alist element matches @var{key} by this criterion,
1726then @code{assoc-default} returns a value based on this element.
1727If the element is a cons, then the value is the element's @sc{cdr}.
1728Otherwise, the return value is @var{default}.
1729
1730If no alist element matches @var{key}, @code{assoc-default} returns
1731@code{nil}.
1732@end defun
1733
1734@defun copy-alist alist
1735@cindex copying alists
1736This function returns a two-level deep copy of @var{alist}: it creates a
1737new copy of each association, so that you can alter the associations of
1738the new alist without changing the old one.
1739
1740@smallexample
1741@group
1742(setq needles-per-cluster
1743 '((2 . ("Austrian Pine" "Red Pine"))
1744 (3 . ("Pitch Pine"))
1745@end group
1746 (5 . ("White Pine"))))
1747@result{}
1748((2 "Austrian Pine" "Red Pine")
1749 (3 "Pitch Pine")
1750 (5 "White Pine"))
1751
1752(setq copy (copy-alist needles-per-cluster))
1753@result{}
1754((2 "Austrian Pine" "Red Pine")
1755 (3 "Pitch Pine")
1756 (5 "White Pine"))
1757
1758(eq needles-per-cluster copy)
1759 @result{} nil
1760(equal needles-per-cluster copy)
1761 @result{} t
1762(eq (car needles-per-cluster) (car copy))
1763 @result{} nil
1764(cdr (car (cdr needles-per-cluster)))
1765 @result{} ("Pitch Pine")
1766@group
1767(eq (cdr (car (cdr needles-per-cluster)))
1768 (cdr (car (cdr copy))))
1769 @result{} t
1770@end group
1771@end smallexample
1772
1773 This example shows how @code{copy-alist} makes it possible to change
1774the associations of one copy without affecting the other:
1775
1776@smallexample
1777@group
1778(setcdr (assq 3 copy) '("Martian Vacuum Pine"))
1779(cdr (assq 3 needles-per-cluster))
1780 @result{} ("Pitch Pine")
1781@end group
1782@end smallexample
1783@end defun
1784
1785@defun assq-delete-all key alist
1786This function deletes from @var{alist} all the elements whose @sc{car}
1787is @code{eq} to @var{key}, much as if you used @code{delq} to delete
1788each such element one by one. It returns the shortened alist, and
1789often modifies the original list structure of @var{alist}. For
1790correct results, use the return value of @code{assq-delete-all} rather
1791than looking at the saved value of @var{alist}.
1792
1793@example
1794(setq alist '((foo 1) (bar 2) (foo 3) (lose 4)))
1795 @result{} ((foo 1) (bar 2) (foo 3) (lose 4))
1796(assq-delete-all 'foo alist)
1797 @result{} ((bar 2) (lose 4))
1798alist
1799 @result{} ((foo 1) (bar 2) (lose 4))
1800@end example
1801@end defun
1802
1803@defun rassq-delete-all value alist
1804This function deletes from @var{alist} all the elements whose @sc{cdr}
1805is @code{eq} to @var{value}. It returns the shortened alist, and
1806often modifies the original list structure of @var{alist}.
1807@code{rassq-delete-all} is like @code{assq-delete-all} except that it
1808compares the @sc{cdr} of each @var{alist} association instead of the
1809@sc{car}.
1810@end defun