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