|
DataMuseum.dkPresents historical artifacts from the history of: DKUUG/EUUG Conference tapes |
This is an automatic "excavation" of a thematic subset of
See our Wiki for more about DKUUG/EUUG Conference tapes Excavated with: AutoArchaeologist - Free & Open Source Software. |
top - metrics - downloadIndex: T l
Length: 51195 (0xc7fb) Types: TextFile Names: »lispref-3«
└─⟦a05ed705a⟧ Bits:30007078 DKUUG GNU 2/12/89 └─⟦c06c473ab⟧ »./UNRELEASED/lispref.tar.Z« └─⟦1b57a2ffe⟧ └─⟦this⟧ »lispref-3«
Info file: lispref, -*-Text-*- produced by texinfo-format-buffer from file: lispref.texinfo This file documents GNU Emacs Lisp. This is Edition 0.1 Beta of the GNU Emacs Lisp Reference Manual, for Emacs Version 18, with some references to Emacs Version 19. Please read this document for review purposes. Published by the Free Software Foundation, 675 Massachusetts Avenue, Cambridge, MA 02139 USA Copyright (C) 1989 Free Software Foundation, Inc. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Foundation. ▶1f◀ File: lispref Node: Predicates for Strings, Prev: Strings and Characters, Up: Strings and Characters, Next: Creating Strings The Predicates for Strings ========================== For more information about general sequence and array predicates, *Note Sequences Arrays Vectors::, and *Note Arrays::. * Function: stringp OBJECT This function returns `t' if the object is a string, `nil' otherwise. * Function: char-or-string-p OBJECT This function returns `t' if the object is a string or a character (i.e., an integer), `nil' otherwise. ▶1f◀ File: lispref Node: Creating Strings, Prev: Predicates for Strings, Up: Strings and Characters, Next: Comparison of Characters and Strings Creating Strings ================ The following functions return a string. For example, in `emacs/lisp/undigest.el', the `makestring' function is used generate a string of similar characters to use in searching for the separator line in a mail digest. In the `dired-uncompress' function `emacs/lisp/dired.el', the `substring' function is used to extract a filename without its `.Z' extension, whereas in `dired-compress', the `concat' function is used to append `.Z' to a filename. * Function: make-string INTEGER CHARACTER This function returns a string made up of INTEGER repetitions of CHARACTER. (make-string 5 ?x) =>(make-string 0 ?x) => Compare this function to `char-to-string', `make-vector', and `make-list'. (*Note Conversion of Characters and Strings::, *Note Vectors::, and *Note Building Cons Cells and Lists::.) * Function: substring STRING START &optional END This function returns a new string which consists of those characters from STRING in the range from (and including) the character at the index START up to (but excluding) the character at the index `end'. The first character is numbered zero. (substring "abcdefg" 0 3) => In the example, the index for `a' is 0, the index for `b' is 1, and the index for `c' is 2. Thus, three letters, `abc', are copied from the full string. The index `3' marks the character position up to which the substring is copied. The character whose index is three is actually the fourth character in the string. Note that the index location is just before the character that the cursor appears on top of; it may be just before the first character. This location is exactly analogous to the location of point in a buffer, except that the position of the first character in a buffer is 1, but the index of the first character in a string is 0. (*Note Positions::.) A negative number counts from the end of the string, so that -1 is the index of the last character of the string. (substring "abcdefg" -3 -1) => In this example, the index for `e' = -3, the index for `f' = -2, and the index for `g' = -1. More precisely, the starting index, -3, falls between the letters `d' and `e'; and the ending index, -1, falls between the letters `f' and `g'. That is why only the two characters between the two index positions are copied, `e' and `f'. When `nil' is used as an index, it falls after the last character in the string. Thus: (substring "abcdefg" -3 nil) => When given 0 for START and no end argument, the `substring' function returns the whole string passed it as an argument. (substring "abcdefg" 0) => (But don't use `substring' to copy a whole string; use `copy-sequence' instead.) A `wrong-type-argument' error results if either START or END are non-integers. An `args-out-of-range' error results if START indicates a character following END, or if either integer is out of range for the string. * Function: concat &rest SEQUENCES This function returns a new string consisting of the characters in the one or more arguments passed to it. The arguments are not changed. The arguments may be strings, lists of numbers, or vectors of numbers. If no arguments are passed to `concat', the function returns an empty string. (concat "abc" "-def") =>(concat "abc" -123 (list 120 (+ 256 121)) [122]) =>(concat "The " "quick brown " "fox.") =>(concat) => The `concat' functions always constructs a new string which is not `eq' to any existing string. As a feature, in the special case where an argument is an integer (not a sequence of integers), it is converted to a string of digits making up the decimal print representation of the integer. (concat 137) =>(concat 54 321) => For information about other concatenation functions, see `mapconcat' in *Note Mapping Functions::, `vconcat' in *Note Vectors::, and `append' in *Note Building Cons Cells and Lists::. ▶1f◀ File: lispref Node: Comparison of Characters and Strings, Prev: Creating Strings, Up: Strings and Characters, Next: Conversion of Characters and Strings Comparison of Characters and Strings ==================================== * Function: char-equal CHARACTER1 CHARACTER2 This function returns `t' if the arguments represent the same character, `nil' otherwise. This is done by comparing two integers modulo 256. (char-equal ?x ?x) =>(char-to-string (+ 256 ?x)) =>(char-equal ?x (+ 256 ?x)) => * Function: string= STRING1 STRING2 This function returns `t' if the characters of the two strings match exactly. Case is significant. `string-equal' is the same as `string='. (string= "abc" "abc") =>(string= "abc" "ABC") =>(string= "ab" "ABC") => * Function: string-equal STRING1 STRING2 `string-equal' is another name for `string='. * Function: string< STRING1 STRING2 This function compares two strings and finds the first pair of characters, if any, in the two strings that do not match. If the numeric value of the ASCII code of the character from the first string is less than the numeric value of the ASCII code of the character from the second string, then this function returns `t'. If the strings match, the value is `nil'. Lower case letters have higher numeric values in the ASCII character set than their upper case counterparts; numbers and many punctuation characters have a lower numeric value than upper case letters. (string< "abc" "abd") =>(string< "abd" "abc") =>(string< "123" "abc") => When the strings have different lengths, and they match up to the length of STRING1, then the result is `t'. If they match up to the length of STRING2, the result is `nil'. A string without any characters in it is the smallest possible string. (string< "" "abc") =>(string< "ab" "abc") =>(string< "abc" "") =>(string< "abc" "ab") =>(string< "" "") => * Function: string-lessp STRING1 STRING2 `string-lessp' is another name for `string<'. ▶1f◀ File: lispref Node: Conversion of Characters and Strings, Prev: Comparison of Characters and Strings, Up: Strings and Characters, Next: Formatting Strings Conversion of Characters and Strings ==================================== Characters and strings may be converted into each other and into integers. `format' and `prin1-to-string' (*Note Output Functions::) may also be used to convert Lisp objects into strings. `read-from-string' (*Note Input Functions::) may be used to ``convert'' a string representation of a Lisp object into an object. Also `concat', `append', and `vconcat' perform conversion of an integer to decimal representation as a special feature. *Note Documentation::, for a description of the functions `single-key-description' and `text-char-description', which return a string representing the Emacs standard notation of the argument character. These functions are used primarily for printing help messages. * Function: char-to-string CHARACTER This function returns a new string with a length of one character. The value of CHARACTER, modulo 256, is used to initialize the element of the string. This function is similar to `make-string' with an integer argument of 1. (*Note Creating Strings::.) (char-to-string ?x) =>(char-to-string (+ 256 ?x)) =>(make-string 1 ?x) => * Function: string-to-char STRING This function returns the decimal numeric value of the first character in the string. Expressed another way, this function returns the first character of the string in the print syntax for characters. (*Note Character Type::.) If the string is empty, the function returns 0, which is identical to the result if the string begins with the null character, ASCII code 0. (string-to-char "ABC") =>(string-to-char "xyz") =>(string-to-char "") =>(string-to-char "\000") => * Function: int-to-string INTEGER This function returns a string consisting of the digits of INTEGER, base ten. When passed a positive integer as an argument, this function returns an unsigned string. When passed a negative integer, the function returns a string with a leading minus sign. (int-to-string 256) =>(int-to-string -23) => * Function: string-to-int STRING This function returns the integer value of the characters in STRING, read as a number in base ten. The string is read starting from (and including) the first character, and it is read until a non-digit is encountered. If the first character is not a digit, this function returns 0. (string-to-int "256") =>(string-to-int "25 is a perfect square.") =>(string-to-int "X256") => ▶1f◀ File: lispref Node: Formatting Strings, Prev: Conversion of Characters and Strings, Up: Strings and Characters, Next: Character Case Formatting Strings ================== The `message' and `error' functions use conversion specification sequences that are identical to those described here for `format'. * Function: format STRING &rest OBJECTS This function returns a new string that is made up from the characters in STRING with any conversion specification sequences in it replaced by the print representations of the matching OBJECTS. A conversion specification sequence is a string of characters beginning with a `%'. For example, if there is a `%s' in STRING, the `format' function does not print the `%s' as such, but substitutes one of the other arguments there. It evaluates that argument and inserts its print representation in place of the `%s'. (format "The value of fill-column is %d." fill-column) => If STRING contains more than one conversion specification, the conversion specifications are matched in order with successive arguments. Thus, the first conversion specification in STRING is matched with the first argument that follows STRING; the second conversion specification is matched with the second argument that follows STRING, and so on. Any extra conversion specifications (those for which there are no matching arguments) will have unpredictable behavior. Any extra objects will be ignored. Although conversion specifications are supposed to specify the types of object with which they are matched, no error is reported if there is a mismatch between the typed specified by the conversion specification and the type of its corresponding object. The character `%' begins a conversion specification. The characters following it indicate how the object should be represented. The characters recognized are described below: `s' Replace the specification with the print representation of the object. If there is no corresponding object, the empty string is used. `o' Replace the specification with the base eight representation of an integer. `d' Replace the specification with the base ten representation of an integer. `x' Replace the specification with the base sixteen representation of an integer. `c' Replace the specification with the print representation of a character. `%' A single `%' is placed in the string. Any other conversion character results in an `Invalid format operation' error. Here are several examples: (format "The name of this buffer is %s." (buffer-name)) => (format "In hash notation, this buffer is %s." (current-buffer)) => (format "The octal value of 18 is %o, and the hex value is %x." 18 18) => All the specification characters allow an optional numeric prefix between the `%' and the character. The optional numeric prefix defines the minimum width for the object. If the print representation of the object contains fewer characters than this, then it is padded. The padding character is normally a space, but if the numeric prefix starts with a zero, zeros are used for padding. The padding is on the left if the prefix is positive (or starts with zero) and on the right if the prefix is negative. (format "%06d will be padded on the left with zeros" 123) =>(format "%-6d will be padded on the right" 123) => No matter what the prefix, nothing in the print representation will be truncated. This allows the programmer to specify spacing exactly without knowing how many characters there are in the object's print representation. In the three following examples, `%7s' specifies a minimum width of 7. In the first case, the word inserted in place of `%7s' has only 3 letters, so 4 blank spaces are inserted for padding. In the second case, the word "specification" is 13 letters wide but is not truncated. In the third case, the padding is on the right. (This does not work in version 18, but does work in version 19.) (format "The word `%7s' actually has %d letters in it." "foo" (length "foo")) => (format "The word `%7s' actually has %d letters in it." "specification" (length "specification")) => (format "The word `%-7s' actually has %d letters in it." "foo" (length "foo")) =>;; %-7s fails to work in version 18, but does work in version 19. ;; In version 18, padding is not inserted. ▶1f◀ File: lispref Node: Character Case, Prev: Formatting Strings, Up: Strings and Characters Character Case ============== The character case functions change the case both of single characters and characters within strings. The functions only convert alphabetic characters (the letters `A' through `Z' and `a' through `z'); other characters are not converted. The functions do not modify the strings which are passed to them as arguments. The examples below use the characters `X' and `x' which have ASCII values 88 and 120 respectively. * Function: downcase STRING-OR-CHAR This function converts a character or a string to lower case. When the argument is a string, a string is returned. When the argument is a character, the returned value is a Lisp object that is represented in the print syntax for characters; it is the decimal number of the ASCII code for the character. When the argument to `downcase' is a string, the function creates a new string in which each letter in the argument that is upper case is converted to lower case. When the argument to `downcase' is a character, `downcase' returns the print representation of the lower case of that character if it is a letter, or the print representation of the character itself if not. (downcase "The cat in the hat") => (downcase ?X) => * Function: upcase STRING-OR-CHAR This function converts a character or a string to upper case. When the argument is a string, a string is returned. When the argument is a character, the returned value is a Lisp object that is represented in the print syntax for characters; it is the decimal number of the ASCII code for the character. When the argument to `upcase' is a string, the function creates a new string in which each letter in the argument that is lower case is converted to upper case. When the argument to `upcase' is a character, `upcase' returns the upper case of the print representation of that character if it is a letter, or the print representation of the character itself if not. (upcase "The cat in the hat") => (upcase ?x) => * Function: capitalize STRING-OR-CHAR This function capitalizes strings or characters. If STRING-OR-CHAR is a string, the function capitalizes each word in STRING-OR-CHAR. This means that the first character of each word is converted to upper case and the rest are converted to lower case. The definition of a word is any sequence of consecutive characters that are assigned to the `word' category in the current syntax table (*Note Syntax Classes::). When the argument to `capitalize' is a character, `capitalize' returns the upper case of that character if it is a letter, or the character itself if not. In this case, the returned value is a Lisp object that is represented in the print syntax for characters; it is the decimal number of the ASCII code for the character. When the argument is a string, a string is returned. (capitalize "The cat in the hat") => (capitalize "THE 77TH-HATTED CAT") => (capitalize ?x) => ▶1f◀ File: lispref Node: Lists, Prev: Strings and Characters, Up: Top, Next: Sequences Arrays Vectors Lists ***** A "list" represents a sequence of zero or more elements. Lists in Lisp are not a primitive data type; they are built up from "cons cells". A cons cell is a data object which represents an ordered pair. It records two Lisp objects, one labeled as the CAR, and the other labeled as the CDR. (These names are traditional.) A list is either the distinguished symbol `nil' (which denotes the empty list), or one or more cons cells chained together through the CDR. The CARs of these cons cells are the "elements" of the list. * Menu: * Lists as Boxes:: * List-related Predicates:: * Building Cons Cells and Lists:: * List Elements:: * Modifying Lists:: * Lists as Sets:: * Association Lists:: ▶1f◀ File: lispref Node: Lists as Boxes, Prev: Lists, Up: Lists, Next: List-related Predicates Lists as Linked Pairs of Boxes ============================== A cons cell can be illustrated as a a pair of boxes. The first box represents the CAR and the second box represents the CDR. Here is an illustration of the two element list, `(tulip lilly)': --------------- --------------- |car |cdr | |car |cdr | | | | | | | | | o---------->| | | | tulip | | | lilly | nil | | | | | | | --------------- --------------- Each box refers to or `contains' a Lisp object. Each pair of boxes represents a cons cell. The first box, which is the CAR of the first cons cell, refers to or contains `tulip'. The arrow from the CDR of the first cons cell to the second cons cell indicates that the CDR of the first cons cell refers to second cons cell. The exact same list can be illustrated in a different sort of box notation like this: ___ ___ ___ ___ |___|___|--> |___|___|--> nil | | | | --> tulip --> lilly Here is a more complex illustration, this time of the three element list, `((pine needles) oak maple)', the first element of which is a two element list: ___ ___ ___ ___ ___ ___ |___|___|--> |___|___|--> |___|___|--> nil | | | | | | | --> oak --> maple | | ___ ___ ___ ___ --> |___|___|--> |___|___|--> nil | | | | --> pine --> needles The exact same list shown above, `((pine needles) oak maple)', is represented in the second box notation like this: --------------- --------------- --------------- |car |cdr | |car |cdr | |car |cdr | | | | | | | | | | | o | o---------->| | o---------->| | | | | | | | oak | | | maple | nil | | | | | | | | | | | -- | ---------- --------------- --------------- | | | --------------- ----------------- | |car |cdr | |car |cdr | | | | | | | | ------>| | o---------->| | | | pine | | | needles | nil | | | | | | | --------------- ----------------- *Note List Type::, for the read and print syntax of lists, and for more `box and arrow' illustrations of lists. ▶1f◀ File: lispref Node: List-related Predicates, Prev: Lists as Boxes, Up: Lists, Next: Building Cons Cells and Lists Predicates on Lists =================== The following predicates test whether a Lisp object is an atom, cons cell, list, or whether it is the distinguished object `nil'. And the function `nlistp' tests whether a function is *not* a list. * Function: consp OBJECT This function returns `t' if the object is a cons cell, `nil' otherwise. `nil' is not a cons cell, although it *is* a list. * Function: atom OBJECT This function returns `t' if OBJECT is an atom, `nil' otherwise. All objects except cons cells are atoms. (atom OBJECT) == (not (consp OBJECT)) * Function: listp OBJECT This function returns `t' if OBJECT is a cons cell or `nil'. Otherwise, it returns `nil'. (listp '(1)) => t (listp '()) => t * Function: nlistp OBJECT This function is the opposite of `listp': it returns `t' if OBJECT is not a list. Otherwise, it returns `nil'. (listp OBJECT) == (not (nlistp OBJECT)) * Function: null OBJECT This function returns `t' if OBJECT is `nil'. It returns `nil' otherwise. This function is identical to `not', but by convention, `null' is used when OBJECT is considered a list, and `not' is used when it is considered to a truth value (see `not' in *Note Conditionals::). (null '(1)) => nil (null '()) => t ▶1f◀ File: lispref Node: Building Cons Cells and Lists, Prev: List-related Predicates, Up: Lists, Next: List Elements Building Cons Cells and Lists ============================= Many functions build lists, as they reside at the very heart of Lisp. `cons' is the fundamental list building function; however, it is interesting to note that `list' is used more times in the source code for Emacs than `cons'. * Function: cons OBJECT1 OBJECT2 This function is the fundamental function used to build new list structure. It creates a new cons cell, making OBJECT1 the `car', and OBJECT2 the `cdr'. It then returns a pointer to the new cons cell. There is no requirement for OBJECT2 to be of any particular type, although it is normally a list. (cons 1 '(2)) => (1 2) (cons 1 '()) => (1) (cons 1 2) => (1 . 2) * Function: list &rest OBJECTS This function creates a list with OBJECTS as its elements. The resulting list is always `nil'-terminated. If no OBJECTS are given, the empty list is returned. (list 1 2 3 4 5) => (1 2 3 4 5) (list) => nil * Function: make-list LENGTH OBJECT This function creates a list of length LENGTH, with each element being OBJECT. Compare `make-list' to `make-string'. (*Note Creating Strings::.) (make-list 3 'pigs) => (pigs pigs pigs) (make-list 0 'pigs) => nil * Function: append &rest SEQUENCES This function returns a list containing all the elements of SEQUENCES. The SEQUENCES may be lists, vectors, strings, or integers. All arguments except the last one are copied, so none of them are altered. The final argument to `append' may be any object but it is typically a list. The final argument is not copied or converted. (setq trees '(pine oak)) => (pine oak) (setq more-trees (append '(maple birch) trees)) => (maple birch pine oak) trees => (pine oak) more-trees => (maple birch pine oak) You can see what happens by looking at a box diagram. The variable `trees' is set to the list `(pine oak)' and then the variable `more-trees' is set to the list `(maple birch pine oak)'; however, the variable `trees' continues to refer to the original list: more-trees trees | | | ___ ___ ___ ___ | ___ ___ ___ ___ --> | | | | | | --> | | | | | | |___|___|--> |___|___|----> |___|___|--> |___|___|--> nil | | | | | | | | --> maple -->birch --> pine --> oak An empty sequence contributes nothing to the value returned by `append'. As a consequence of this, a final `nil' argument forces a copy of the previous argument. trees => (pine oak) (setq wood (append trees ())) => (pine oak) wood => (pine oak) (eq wood trees) => nil As a feature, in the special case where one of the SEQUENCES is an integer (but not a sequence of integers), it is first converted to a string of digits making up the decimal print representation of the integer. (setq trees '(pine oak)) => (pine oak) (char-to-string \054) => "6" (setq longer-list (append trees 6 '(spruce))) => (pine oak 54 spruce) ?x => 120 (setq x-list (append trees 6 ?x)) => (pine oak 54 . 120) Also, somewhat mysteriously, at first: (append trees 6 ?x nil) => But note that: ?x => (char-to-string \049) =>(char-to-string \050) =>(char-to-string \048) => If no SEQUENCES are given, `nil' is returned. (append) => nil See `nconc' in *Note Rearrangement::, for another way to join lists without copying. See `copy-sequence' in *Note Sequences Arrays Vectors::, for another way to copy sequences. * Function: reverse LIST This function creates a new list whose elements are the elements of LIST, but in reverse order. The original LIST is *not* altered. (setq x '(1 2 3 4)) => (1 2 3 4) (reverse x) => (4 3 2 1) x => (1 2 3 4) ▶1f◀ File: lispref Node: List Elements, Prev: Building Cons Cells and Lists, Up: Lists, Next: Modifying Lists Accessing Elements of Lists =========================== * Function: car CONS-CELL This function returns the value pointed to by the first pointer of the cons cell, CONS-CELL. Expressed another way, this function returns the CAR of CONS-CELL. As a special case, if CONS-CELL is `nil', then `car' is defined to return `nil'. Therefore, any list is allowed as an argument. It is an error if the argument is not a cons cell or `nil'. (car '(a b c)) => a (car '()) => nil * Function: cdr CONS-CELL This function returns the value pointed to by the second pointer of the cons cell, CONS-CELL. Expressed another way, this function returns the CDR of CONS-CELL. As a special case, if CONS-CELL is `nil', then `cdr' is defined to return `nil'. Therefore, any list is allowed as an argument. It is an error if the argument is not a cons cell or `nil'. (cdr '(a b c)) => (b c) (cdr '()) => nil * Function: car-safe OBJECT This function lets you take the CAR of a cons cell while avoiding errors for other data types. It returns the CAR of OBJECT if OBJECT is a cons cell, `nil' otherwise. This is in contrast to `car', which signals an error if OBJECT is not a list. (car-safe OBJECT) == (let ((x OBJECT)) (if (consp x) (car x) nil)) * Function: cdr-safe OBJECT This function lets you take the CAR of a cons cell while avoiding errors for other data types. It returns the CDR of OBJECT if OBJECT is a cons cell, `nil' otherwise. This is in contrast to `cdr', which signals an error if OBJECT is not a list. (cdr-safe OBJECT) == (let ((x OBJECT)) (if (consp x) (cdr x) nil)) * Function: nth N LIST This function returns the Nth element of LIST. Elements are numbered starting with zero, so the CAR of LIST is element number zero. If LIST has fewer than N elements, the value is `nil'. If N is less than zero, then the first element is returned. (nth 2 '(1 2 3 4)) => 3 (nth 10 '(1 2 3 4)) => nil (nth -3 '(1 2 3 4)) => 1 (nth n x) == (car (nthcdr n x)) * Function: nthcdr N LIST This function returns the Nth cdr of LIST. In other words, it removes the first N links of LIST and returns what follows. If N is less than or equal to zero, then all of LIST is returned. If LIST has fewer than N elements, the value is `nil'. (nthcdr 1 '(1 2 3 4)) => (2 3 4) (nthcdr 10 '(1 2 3 4)) => nil (nthcdr -3 '(1 2 3 4)) => (1 2 3 4) ▶1f◀ File: lispref Node: Modifying Lists, Prev: List Elements, Up: Lists, Next: Lists as Sets Modifying Existing List Structure ================================= You can modify the CAR and CDR contents of a cons cell with the primitives `setcar' and `setcdr'. Common Lisp Note: Common Lisp uses functions `rplaca' and `rplacd' to alter list structure; they change structure the same way as `setcar' and `setcdr', but the Common Lisp functions return the cons cell while `setcar' and `setcdr' return the new CAR or CDR. * Menu: * Setcar:: * Setcdr:: * Rearrangement:: ▶1f◀ File: lispref Node: Setcar, Prev: Modifying Lists, Up: Modifying Lists, Next: Setcdr Altering List Elements with `setcar' ------------------------------------ Changing the CAR of a cons cell replaces one element of a list with a different element. This is done with `setcar'. * Function: setcar CONS OBJECT This function stores OBJECT as the new CAR of CONS, replacing its previous CAR. It returns the value OBJECT. (setq x '(1 2)) => (1 2) (setcar x '4) => 4 x => (4 2) When a cons cell is part of the shared structure of several lists, storing a new CAR into the cons changes one element of each of these lists. Here is an example: ;; Create two lists that are partly shared. (setq x1 '(a b c)) => (a b c) (setq x2 (cons 'z (cdr x1))) => (z b c) ;; Replace the CAR of a shared link. (setcar (cdr x1) 'foo) => foo x1 ; Both lists are changed. => (a foo c) x2 => (z foo c) ;; Replace the CAR of a link that is not shared. (setcar x1 'baz) => baz x1 ; Only one list is changed. => (baz foo c) x2 => (z foo c) Here is a graphical depiction of the shared structure of the two lists X1 and X2, showing why replacing `b' changes them both: x1: --------------- --------------- --------------- |car |cdr | |car |cdr | |car |cdr | | a | o---------->| b | o---------->| c | nil | | | | -->| | | | | | --------------- | --------------- --------------- | x2: | --------------- | |car |cdr | | | z | o------- | | | --------------- Here is an alternative form of box diagram, showing the same relationship: ___ ___ ___ ___ ___ ___ |___|___|----> |___|___|--> |___|___|--> nil | --> | | | | | | --> a | --> b --> c | ___ ___ | |___|___|-- | | --> z ▶1f◀ File: lispref Node: Setcdr, Prev: Setcar, Up: Modifying Lists, Next: Rearrangement Altering the CDR of a List -------------------------- The lowest-level primitive for modifying a CDR is `setcdr': * Function: setcdr CONS OBJECT This function stores OBJECT into the cdr of CONS. The value returned is OBJECT, not CONS. (setq x '(1 2)) => (1 2) (setcdr x '(4)) => (4) x => (1 4) You can delete elements from the middle of a list by altering the CDRs of the cons cells in the list. For example, here is the result of deleting the second element, `b', from the list `(a b c)', by changing the CDR of the first cell: (setq x1 '(a b c)) => (a b c) (setcdr x1 '(c)) => (c) x1 => (a c) --------------- --------------- |car |cdr | |car |cdr | | a | o---------------------------------->| c | nil | | | | | | | --------------- --------------- The second cons cell, which previously held the element `b', may still exist and its CAR may still be `b', but it no longer forms part of this list. It is equally easy to insert a new element by changing CDRs: (setq x1 '(a b c)) => (a b c) (setcdr x1 (cons 'd (cdr x1))) => (d b c) x1 => (a d b c) --------------- --------------- --------------- |car |cdr | |car |cdr | |car |cdr | | a | o | -->| b | o---------->| c | nil | | | | | | | | | | | | ---------- | -- | --------------- --------------- | | ------ ------- | | | --------------- | | |car |cdr | | -->| d | o------ | | | --------------- ▶1f◀ File: lispref Node: Rearrangement, Prev: Setcdr, Up: Modifying Lists Functions that Rearrange Lists ------------------------------ Here are some functions that rearrange lists ``destructively'' by modifying the CDRs of their component cons cells. We call these functions ``destructive'' because the original lists passed as arguments to them are chewed up to produce a new list that is returned. * Function: nconc &rest LISTS This function returns a list containing all the elements of LISTS. Unlike `append' (*Note Building Cons Cells and Lists::), the LISTS are *not* copied; instead, the last CDR of each of the LISTS is changed to refer to the following list. The last of the LISTS is not altered. (setq x '(1 2 3)) => (1 2 3) (nconc x '(4 5)) => (1 2 3 4 5) x => (1 2 3 4 5) Since the last argument of `nconc' is not itself modified, it is reasonable to use a constant list, such as ``(4 5)', as is done in the above example. For the same reason, the last argument need not be a list: (setq x '(1 2 3)) => (1 2 3) (nconc x 'z) => (1 2 3 . z) x => (1 2 3 . z) A common pitfall is to use a quoted constant list as a non-last argument to `nconc'. If you do this, your program will change each time you run it! Here is what happens: (defun add-foo (x) ; This function should add (nconc '(foo) x)) ; `foo' to the front of its arg. (symbol-function 'add-foo) => (lambda (x) (nconc (quote (foo)) x)) (setq xx (add-foo '(1 2))) ; It seems to work. => (foo 1 2) (setq xy (add-foo '(3 4))) ; What happened? => (foo 1 2 3 4) (eq xx xy) => t (symbol-function 'add-foo) => (lambda (x) (nconc '(foo 1 2 3 4) x)) * Function: nreverse LIST This function returns the elements of LIST in reverse order. Unlike `reverse', however, LIST is destructively altered by reversing the CDRs in the cons cells forming the list. The last cons cell of the original list is now the first cell of the list. (setq x '(1 2 3 4)) => (1 2 3 4) x => (1 2 3 4) (nreverse x) => (4 3 2 1) x => (1) Here is the `nreverse' of our favorite example, `(a b c)', presented graphically: Reversed list: --------------- --------------- --------------- |car |cdr | |car |cdr | |car |cdr | | a | nil |<-- | b | o |<-- | c | o | | | | | | | | | | | | | | --------------- | ---------- | -- | ---------- | -- | | | | --------------- --------------- * Function: sort LIST PREDICATE This function sorts LIST stably, though destructively, and returns the sorted list. It compares elements using PREDICATE. A "stable" sort is one in which elements with equal sort keys maintain their relative order before and after the sort. Stability is important when successive sorts are used to order elements according to different sets of keys. PREDICATE must be a function of two arguments. It is called with two elements of LIST. To get an increasing order sort, the PREDICATE should return `t' if the first element is ``less than'' the second, or `nil' if not. The destructive aspect of `sort' is that it rearranges the cons cells forming LIST by changing CDRs. A nondestructive sort function would create new cons cells to store the elements in their sorted order. The CARs of the cons cells are never changed; the cons cell that contained the element `a' in the original LIST, still has `a' in its CAR after sorting, but it now appears in a different position in the list due to the change of CDRs. *Note Sorting::, for more functions that perform sorting. (setq nums '(1 3 2 6 5 4 0)) => (1 3 2 6 5 4 0) (sort nums '<) => (0 1 2 3 4 5 6) nums => (1 2 3 4 5 6) Note that `nums' no longer contains 0. This shows why you should save the return-value of sort. Don't assume a variable which held the argument now holds the entire sorted list! See `delq', in *Note Lists as Sets::, for another function that modifies cons cells. ▶1f◀ File: lispref Node: Lists as Sets, Prev: Modifying Lists, Up: Lists, Next: Association Lists Using Lists as Sets =================== Lists can represent unordered mathematical sets---the elements in the list are the members of the set. All you have to do is ignore the order. In these applications, you will probably want to use the functions `memq' and `delq'. * Function: memq OBJECT LIST This function tests to see whether OBJECT is a member of LIST. If it is, `memq' returns a list starting with the first occurrence of OBJECT. Otherwise, it returns `nil'. The letter `q' in `memq' says that it uses `eq' to compare OBJECTS against the elements of the list. (memq 2 '(1 2 3 2 1)) => (2 3 2 1) (memq '(2) '((1) (2))) ; `(2)' and `(2)' are not `eq'. => nil * Function: delq OBJECT LIST This function removes all elements `eq' to OBJECT from LIST. Elements at the front of the list are removed (when necessary) simply by advancing down the list and returning a sublist that starts after those elements: (delq 'a '(a b c)) == (cdr '(a b c)) When an element to be deleted appears in the middle of the list, removing it requires changing the CDRs (*Note Setcdr::). (setq sample-list '(1 2 3 (4))) => (1 2 3 (4)) (delq 1 sample-list) => (2 3 (4)) sample-list => (1 2 3 (4)) (delq 2 sample-list) => (1 3 (4)) sample-list => (1 3 (4)) (delq '(4) sample-list) => (1 3 (4)) Note that `(delq 1 sample-list)' does not remove the first element of `sample-list', but that `(delq 2 sample-list)' removes the second element. Don't assume that a variable which held the argument now has fewer elements, or, conversely, that it holds the original list! (In the final example, the `(4)' that `delq' attempts to match and the `(4)' in the `sample-list' are not `eq'.) Common Lisp note: Common Lisp has functions `union' and `intersection' for set operations, but GNU Emacs Lisp does not have them. You can write them in Lisp if you wish. ▶1f◀ File: lispref Node: Association Lists, Prev: Lists as Sets, Up: Lists Association Lists ================= An "association list", or "alist" for short, records a mapping from keys to values. It is a list of pairs (cons cells): the CAR of each cell is the key, and the CDR is the associated value. The key can be any Lisp object, and so can the value. An sample of an alist is shown below; the key, `pine', is associated with `cones'; the key, `oak', is associated with `acorns'; and the key, `maple', is associated with `seeds'. '((pine . cones) (oak . acorns) (maple . seeds)) The pairs in an alist may be of any kind. For example, in the following alist, the symbol `a' is associated with the number `1', and the string `"b"' is associated with the *list* `(2 3)'. ((a . 1) ("b" 2 3)) We recommend you use dotted pairs consistently, since they are the simplest to handle. Association lists are often used to record information that you might otherwise keep on a stack since new pairs may be simply added to the front of the list. When searching an association list for a pair with a given key, the first pair with that key is returned, even if there are several such pairs. It is *not* an error if an element of an association list is not a cons cell. The alist search functions simply ignore such elements. Note that property lists are similar to association lists in several respects. A property list behaves like an association list in which each key can occur only once. *Note Property Lists::, for a comparison of property lists and association lists. * Function: assoc KEY ALIST This function returns the first pair associated with KEY in ALIST. It compares KEY against the alist elements using `equal'. It returns `nil' if no pair in ALIST has a CAR `equal' to KEY. (setq trees '((pine . cones) (oak . acorns) (maple . seeds))) => ((pine . cones) (oak . acorns) (maple . seeds)) (assoc 'oak trees) => (oak . acorns) (cdr (assoc 'oak trees)) => acorns (assoc 'birch trees) => nil The elements of an association list need not be dotted pairs: (setq colors '((rose red) (lilly white) (buttercup yellow))) => ((rose red) (lilly white) (buttercup yellow)) (assoc 'rose colors) => (rose red) (cdr (assoc 'rose colors)) => (red) In the last example, the CDR is the *list* `(red)'; contrast this with the example using dotted pairs in which the atom `acorn' is returned. Also, the key and the associated value can be any kind of Lisp object, such as numbers, strings, or lists: (setq needles-per-cluster '((2 . ("Austrian Pine" "Red Pine")) (3 . "Pitch Pine") (5 . "White Pine"))) (cdr (assoc 3 needles-per-cluster)) => "Pitch Pine" (cdr (assoc 2 needles-per-cluster)) => ("Austrian Pine" "Red Pine") * Function: assq KEY ALIST This function is like `assoc' in that it returns the first pair associated with KEY in ALIST, but it makes the comparison using `eq' instead of `equal'. `assq' returns `nil' if no pair in ALIST has a CAR `eq' to KEY. This function is used more often than `assoc', since `eq' is faster than `equal' and most alists use symbols as keys. (setq trees '((pine . cones) (oak . acorns) (maple . seeds))) (assq 'pine trees) => (pine . cones) On the other hand, `assq' returns `nil' in the following case: (setq leaves '(("simple leaves" . oak) ("compound leaves" . horsechestnut))) (assq "simple leaves" leaves) => nil (assoc "simple leaves" leaves) => ("simple leaves" . oak) * Function: rassq ALIST VALUE `rassq' is like `assq' except that the CDR of the ALIST pairs is tested instead of the CAR. You can think of this as ``reverse assq'', finding the key for a given value. This function returns the first pair associated with VALUE in ALIST. It returns `nil' if no pair in ALIST has a CDR `eq' to VALUE. (setq trees '((pine . cones) (oak . acorns) (maple . seeds))) (rassq 'acorns trees) => (oak . acorns) However, `rassq' will return `nil' if it cannot match VALUE with the alist: (setq colors '((rose red) (lilly white) (buttercup yellow))) (rassq 'white colors) => nil In this case, the CDR of the pair `(lilly white)' is not the symbol, `white', but is the list `(white)'. This can be seen more clearly if the pair is expressed in the equivalent dotted pair notation: (lilly white) == (lilly . (white)) * Function: copy-alist ALIST This function returns a two-level deep copy of ALIST: it creates a new copy of each pair, so that you can alter the associations of the new alist without changing the old one. (setq needles-per-cluster '((2 . ("Austrian Pine" "Red Pine")) (3 . "Pitch Pine") (5 . "White Pine"))) => ((2 "Austrian Pine" "Red Pine") (3 . "Pitch Pine") (5 . "White Pine")) (setq copy (copy-alist needles-per-cluster)) => ((2 "Austrian Pine" "Red Pine") (3 . "Pitch Pine") (5 . "White Pine")) (eq needles-per-cluster copy) => nil (equal needles-per-cluster copy) => t (eq (car needles-per-cluster) (car copy)) => nil (cdr (car (cdr needles-per-cluster))) => "Pitch Pine" (eq (cdr (car (cdr needles-per-cluster))) (cdr (car (cdr copy)))) => t ▶1f◀