How does append work in Common Lisp?
I just started learning Lisp and I don’t seem to understand the following piece of code:
Where is z appended?
![]()
1 Answer 1
It is appended to an unnamed list to be returned when the loop terminates. As first approximation, you may think of it as a shorthand for
The append here is a loop keyword; it’s not related to the append function, except for sharing the same name — so it’s the loop macro that decides how it works, instead of the append function.
-
The Overflow Blog
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.11.43304
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Append lisp как работает
Many functions build lists, as lists 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 most basic function for building new list structure. It creates a new cons cell, making object1 the CAR, and object2 the CDR. It then returns the new cons cell. The arguments object1 and object2 may be any Lisp objects, but most often object2 is a list.
cons is often used to add a single element to the front of a list. This is called consing the element onto the list. 5 For example:
Note that there is no conflict between the variable named list used in this example and the function named list described below; any symbol can serve both purposes.
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.
This function creates a list of length elements, in which each element is object . Compare make-list with make-string (see Creating Strings).
This function returns a list containing all the elements of sequences . The sequences may be lists, vectors, bool-vectors, or strings, but the last one should usually be a list. All arguments except the last one are copied, so none of the arguments is altered. (See nconc in Functions that Rearrange Lists, for a way to join lists with no copying.)
More generally, the final argument to append may be any Lisp object. The final argument is not copied or converted; it becomes the CDR of the last cons cell in the new list. If the final argument is itself a list, then its elements become in effect elements of the result list. If the final element is not a list, the result is a dotted list since its final CDR is not nil as required in a proper list (see Lists and Cons Cells).
Here is an example of using append :
You can see how append works 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:
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:
This once was the usual way to copy a list, before the function copy-sequence was invented. See Sequences, Arrays, and Vectors.
Here we show the use of vectors and strings as arguments to append :
With the help of apply (see Calling Functions), we can append all the lists in a list of lists:
If no sequences are given, nil is returned:
Here are some examples where the final argument is not a list:
The second example shows that when the final argument is a sequence but not a list, the sequence’s elements do not become elements of the resulting list. Instead, the sequence becomes the final CDR, like any other non-list final argument.
Function: copy-tree tree &optional vecp ¶
This function returns a copy of the tree tree . If tree is a cons cell, this makes a new cons cell with the same CAR and CDR, then recursively copies the CAR and CDR in the same way.
Normally, when tree is anything other than a cons cell, copy-tree simply returns tree . However, if vecp is non- nil , it copies vectors too (and operates recursively on their elements).
Function: flatten-tree tree ¶
This function returns a “flattened” copy of tree , that is, a list containing all the non- nil terminal nodes, or leaves, of the tree of cons cells rooted at tree . Leaves in the returned list are in the same order as in tree .
This function returns object as a list. If object is already a list, the function returns it; otherwise, the function returns a one-element list containing object .
This is usually useful if you have a variable that may or may not be a list, and you can then say, for instance:
This function returns a list of numbers starting with from and incrementing by separation , and ending at or just before to . separation can be positive or negative and defaults to 1. If to is nil or numerically equal to from , the value is the one-element list ( from ) . If to is less than from with a positive separation , or greater than from with a negative separation , the value is nil because those arguments specify an empty sequence.
If separation is 0 and to is neither nil nor numerically equal to from , number-sequence signals an error, since those arguments specify an infinite sequence.
All arguments are numbers. Floating-point arguments can be tricky, because floating-point arithmetic is inexact. For instance, depending on the machine, it may quite well happen that (number-sequence 0.4 0.6 0.2) returns the one element list (0.4) , whereas (number-sequence 0.4 0.8 0.2) returns a list with three elements. The n th element of the list is computed by the exact formula (+ from (* n separation )) . Thus, if one wants to make sure that to is included in the list, one can pass an expression of this exact type for to . Alternatively, one can replace to with a slightly larger value (or a slightly more negative value if separation is negative).
Footnotes
There is no strictly equivalent way to add an element to the end of a list. You can use (append listname (list newelt )) , which creates a whole new list by copying listname and adding newelt to its end. Or you can use (nconc listname (list newelt )) , which modifies listname by following all the CDRs and then replacing the terminating nil . Compare this to adding an element to the beginning of a list with cons , which neither copies nor modifies the list.
Append lisp как работает
На этом шаге мы продолжим изучение элементарных конструкторов.
В диалектах muLISP85 и muLISP87 определено около 20 функций- конструкторов : ACONS, LIST*, APPEND, COPY-LIST, COPY-TREE, FIRSTN, BUTLAST, REMOVE, REMOVE-IF, SUBSTITUTE, SUBSTITUTE-IF, SUBST, SUBST-IF, MAKE-LIST и др.
| Функция | Назначение |
| (CONS OBJECT1 OBJECT2) | Возвращает точечную пару, у которой CAR -элемент указывает на OBJECT1 , а CDR -элемент — на OBJECT2 . |
| (LIST OBJECT1 . OBJECTN) | Создает и возвращает список, состоящий из элементов с OBJECT1 по OBJECTN . |
| (LIST* OBJECT1 . OBJECTN) | Связывает в пару обьекты OBJECT1. OBJECTN и возвращает результирующий обьект. |
| (APPEND LIST1 LIST2 . LISTN) | Создает и возвращает список, состоящий из элементов списков, начиная со списка LIST1 и по список LISTN . |
| (COPY-LIST LIST) | Копирует точечные пары верхнего уровня списка LIST и возвращает список, эквивалентный в смысле EQUAL , списку LIST . |
| (COPY-TREE OBJECT) | Копирует все точечные пары объекта OBJECT и возвращает обьект, эквивалентный OBJECT . |
| (FIRST N LIST) | Копирует и возвращает первые N элементов списка. |
| (BUTLAST LIST N) | Копирует и возвращает все, кроме N последних элементов списка LIST . |
| (REVERSE LIST) | Создает и возвращает список, состоящий из элементов списка LIST , но в обратном порядке. |
| (SUBSTITUTE NEW OLD LIST TEST) | Возвращает копию высокого уровня списка LIST . |
| (MAKE-LIST N OBJECT LIST) | Ссоздает и выдает список из N элементов. |
| REMOVE | Удаляет элементы из списка. |
| SUBST | Заменяет элементы в списке. |
1. Функция (CONS OBJECT1 OBJECT2) возвращает точечную пару, у которой CAR -элемент указывает на OBJECT1 , а CDR -элемент — на OBJECT2 . Если значение системной переменной *FREE-LIST* есть точечная пара, то функция CONS модифицирует и возвращает эту точечную пару и изменяет *FREE-LIST* на (CDR *FREE-LIST*) .
Корректная интерпретация функции (СONS OBJECT1 OBJECT2) зависит от того, как рассматривается OBJECT2 .
Если OBJECT2 — список, то функция CONS создает список, первым элементом которого является OBJECT1 , а остатком — OBJECT2 .
Если OBJECT2 — атом или бинарное дерево, то функция CONS создает дерево, у которого левая ветвь ( CAR -ветвь) есть OBJECT1 , а правая ветвь ( CDR -ветвь) — OBJECT2 . Например: В начало таблицы
2. Функция (LIST OBJECT1 . OBJECTN) создает и возвращает список, состоящий из элементов с OBJECT1 по OBJECTN . Если функция вызвана без аргументов, то функция LIST возвращает признак NIL . Функция LIST может работать с любым количеством аргументов. Например: Приведем код функции: В начало таблицы
3. Функция (LIST* OBJECT1 . OBJECTN) связывает в пару обьекты OBJECT1. OBJECTN и возвращает результирующий обьект. Например: Если функция вызывается с единственным аргументом, то LIST* возвращает этот аргумент. Например: Приведем код функции: В начало таблицы
4. Функция (APPEND LIST1 LIST2 . LISTN) создает и возвращает список, состоящий из элементов списков, начиная со списка LIST1 и по список LISTN . Функция APPEND копирует точечные пары высшего уровня каждого из своих аргументов, кроме последнего.
Если функция вызывается с единственным аргументом, то APPEND возвращает этот аргумент без его копирования. Следовательно, для копирования списка лучше использовать функцию COPY-LIST , чем функцию APPEND .
Отметим, что если функции APPEND и NCONC имеют одинаковые аргументы, то они возвращают, как правило, одинаковые списки. Однако, функция APPEND использует точечные пары для копирования всех, кроме последнего, аргументов, тогда как функция NCONC фактически модифицирует все аргументы, кроме последнего. Например: Приведем код функции: В начало таблицы
5. Функция (COPY-LIST LIST) копирует точечные пары верхнего уровня списка LIST и возвращает список, эквивалентный в смысле EQUAL , списку LIST . Например: Приведем код функции: В начало таблицы
6. Функция (COPY-TREE OBJECT) копирует все точечные пары объекта OBJECT и возвращает обьект, эквивалентный OBJECT . Например: Приведем код функции: В начало таблицы
7. Если N — положительное целое, то функция (FIRST N LIST) копирует и возвращает первые N элементов списка. Функция FIRSTN возвращает NIL , если N — неположительное целое.
Если список LIST имеет N или более элементов, то функция FIRSTN копирует и возвращает элементы списка LIST . Например: Код функции имеет вид: В начало таблицы
8. Если N — нуль или положительное целое, то функция (BUTLAST LIST N) копирует и возвращает все, кроме N последних элементов списка LIST . Например:
Если N пропущено или либо равно нулю, либо не является положительным целым, то функция BUTLAST копирует и возвращает все, кроме последнего, элементы списка LIST . Например: Приведем код функции: В начало таблицы
9. Функция (REVERSE LIST) создает и возвращает список, состоящий из элементов списка LIST , но в обратном порядке.
Функция (REVERSE LIST OBJECT) выдает элементы списка LIST в обратном порядке, присоединенные к OBJECT . Например:
Результат является таким же, как и при работе функции (APPEND (REVERSE LIST) OBJECT) , но вызов REVERSE в качестве второго аргумента более эффективен.
Приведем код функции: В начало таблицы
10. Функция (SUBSTITUTE NEW OLD LIST TEST) возвращает копию высокого уровня списка LIST , замещая на элементы NEW те элементы OLD списка LIST , для которых признак проверки по тесту TEST есть не NIL . Если тест-аргумент есть NIL или не задан, SUBSTITUTE использует EQL -тест.
Функция (SUBSTITUTE-IF NEW TEST LIST) возвращает копию высокого уровня списка LIST , замещая на элементы NEW все элементы списка LIST , для которых признак проверки по тесту TEST есть не NIL . Например: В начало таблицы
11. Функция (MAKE-LIST N OBJECT LIST) создает и выдает список из N элементов, каждый из которых принимает значение OBJECT , присоединенного к списку LIST . Отсутствие N отождествляется с 0, отутствие OBJECT и LIST — с NIL . Например: Приведем код функции: В начало таблицы
12. Опишем теперь конструкторы REMOVE и SUBST . Первая функция служит для удаления элементов из списка, а вторая — для замены элементов. Функции REMOVE и SUBST реализуются в условном варианте. Это означает, что добавляется еще один аргумент, являющийся предикатом, истинность которого проверяется перед применением функции на элементах изменяемого списка. Если результат проверки — истина, то функция выполняется, в противном случае — нет.
Функция (REMOVE ELEMENT LIST TEST) возвращает копию списка LIST со всеми элементами, кроме тех, которые при проверке по тесту TEST имеют признак, не равный NIL и удаляются ( (TEST ELEMENT) не равен NIL ).
Если TEST есть NIL или не задан, функция REMOVE использует EQL -тест.
Функция (REMOVE-IF TEST LIST) возвращает копию списка LIST со всеми элементами, кроме тех, которые имеют при проверке по тесту признак не NIL ( (TEST ELEMENT) не возвращает NIL ) и удаляются. Например:
Функция (SUBST NEW OLD OBJECT TEST) возвращает копию обьекта OBJECT , замещая на NEW все OLD подвыражения обьекта OBJECT , для которых признак проверки по тесту TEST есть не NIL . Если TEST есть NIL или не задан, SUBST использует EQL -тест. Например:
Замечание . Теория L списочных структур имеет нелогические символы CAR, CDR, CONS, ATOM и следующие аксиомы [1, с.213]: В начало таблицы
(1) Математическая логика в программировании: Сб.статей 1980-1988 гг.: Пер.с англ. — М.: Мир, 1991. — 408 с.
Append lisp как работает
append &rest lists => result
Arguments and Values:
list —each must be a proper list except the last, which may be any object .
result —an object . This will be a list unless the last list was not a list and all preceding lists were null .
append returns a new list that is the concatenation of the copies. lists are left unchanged; the list structure of each of lists except the last is copied. The last argument is not copied; it becomes the cdr of the final dotted pair of the concatenation of the preceding lists , or is returned directly if there are no preceding non-empty lists .
Affected By: None.
Exceptional Situations: None.
The following X3J13 cleanup issue, not part of the specification , applies to this section: